Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why can't I use a boolean expression in a SQL CASE expression inside a WHERE clause?

I want to write a query with the following logic:

  • If @fundKey is greater than 0, look for funds with a key matching @fundKey.
  • Otherwise, look for funds with a key less than 1000000.

If I were to write this logic in JavaScript it would be something like this:

funds.filter(x => fundKey > 0 ? x.FundKey === fundKey : x.FundKey < 1000000)

I tried to write a query like this

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

DECLARE @fundKey INT = -1;
SELECT FundKey, FundName FROM dbo.Funds
WHERE CASE WHEN @fundKey > 0 THEN FundKey = @fundKey ELSE FundKey < 1000000 END

but it seems that the syntax is invalid. Why can’t I use the result of a boolean expression in a WHERE clause? Is there a different way to write this logic without being too verbose?

>Solution :

Because a CASE expression returns a scalar value not a boolean result. Though, you shouldn’t be use a CASE expression on a column in the WHERE anyway; it won’t be SARGable. Use explicit AND and OR logic.

For your query, this means you should actually be doing:

DECLARE @fundKey INT = -1;

SELECT FundKey,
       FundName
FROM dbo.Funds
WHERE (@fundKey > 0 AND FundKey = @fundKey)
   OR (@fundKey <= 0 AND < 1000000);

Likely, as well, you’ll want to add an OPTION (RECOMPILE) as the plans could be quite different for the 2 boolean clauses.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading