Is it possible to have SQL stop checking the WHERE clause once a condition is met? For instance, if I have a statement as 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? In essence, only one of the two checks in the where clause should be used, giving precedence to the first. Example cases below.
Example Cases:
Case1
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 suggested answers, a with
seems the best possible solution to solve what SQL is not inherently able to do. For my specific situation, the issue comes when attempting to put this into an outer apply
, as 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