Is it possible for SQL to stop checking the WHERE clause after the condition is met? For example, if I have an instruction as shown below:
SELECT * FROM Table1 WHERE Table1.SubID = (SELECT TOP 1 SubID FROM Table2 ORDER BY Date DESC) OR Table1.OrderID = (SELECT TOP 1 OrderID FROM Table2 ORDER BY Date DESC)
Is it possible to stop execution after the first check? Essentially, you should use only one of the two checks in the where clause, giving priority to the first. Examples are below.
Sample cases:
Case 1
Table1 SubID=600 OrderID=5 Table2 TOP 1 SubID=NULL Table2 TOP 1 OrderID=5 Matches the OrderID to 5
Case 2
Table1 SubId=600 OrderId=5 Table2 Top 1 SubID=600 Table2 Top 1 OrderID=3 Matches to SubID=600, not OrderID=3
Given the suggested answers, with seems to be the best solution to solve what SQL inherently cannot do. For my specific situation, the problem occurs when trying to include this in outer apply , as shown below.
SELECT * FROM tbl_MainFields OUTER APPLY ( WITH conditional AS ( SELECT 1 AS 'choice', PlanCode, Carrier FROM tbl_payers WHERE tbl_payers.PlanCode = ( SELECT TOP 1 PlanCode FROM tbl_payerDenials WHERE tbl_payerDenials.AccountNumber = tbl_mainFields.AccountNumber ORDER BY InsertDate DESC ) UNION ALL SELECT 2 AS 'choice', PlanCode, Carrier FROM tbl_payers WHERE tbl_payers.OrderNum = ( SELECT TOP 1 DenialLevel FROM tbl_payerDenials WHERE tbl_payerDenials.AccountNumber = tbl_mainFields.AccountNumber ORDER BY InsertDate DESC ) ) SELECT PlanCode AS DenialPC, Carrier AS DenialCAR FROM conditional WHERE choice = (SELECT MIN(choice) FROM conditional) ) denialData
source share