Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamic where clause based on variable

Tags:

sql

t-sql

I am working on a select statement in SQL and am running into issues trying to create a where clause that includes a case statement or an if else statement. I want to select records based on the value of a variable. If the variable is 'True' then only return records from the select statement where a column is null. If the variable is not 'True' then return all records regardless if that columns is null.

Any tips on how to do this?

Below is a simple example of what i am trying to do:

declare @option1 as varchar(5)

--This can be True or False so to test i just put the Set option below
set @option1 = 'True'

Select a,b,c,d...
from ...
where d = case when @option1 = 'True' then NULL End

This is the part where i do not know what to do. I only need to filter out the records if the variable is 'True' so not sure what to put in the else section of the case.

like image 800
Ben Avatar asked Jun 03 '26 18:06

Ben


2 Answers

You can't test for d = NULL as your CASE statement does because that will always return false since NULL is not equal to NULL (unless you set ANSI_NULLS to 'off').

The simplest thing to do would be to change the WHERE clause to this:

WHERE @option1 = 'False' OR d IS NULL

If you prefer to use a CASE statement for some reason, you can write it like this:

WHERE 1 = CASE WHEN @option1 = 'False' THEN 1 
               WHEN @option1 = 'True' AND d IS NULL THEN 1 
               ELSE 0 
          END
like image 194
PinnyM Avatar answered Jun 06 '26 09:06

PinnyM


This:

UPDATE: PinnyM has straightened me out on this. I am leaving my embarrassing logically flawed argument here for the education of the masses. The solution I propose below after "Try this" is certainly still valid, but PinnyM's solutions is by far more elegant and should be used.

WHERE @option1 = 'False' OR d IS NULL

Will always return all the results given his current select statement (assuming @Option1 is simply a flag parameter passed in).

Try this:

SELECT a, b, c, d
WHERE 
    -- Returns only rows where d is null (if @Option1 is True)
    (@Option1 = 'True' AND d IS NULL) 
    OR
     -- returns all the rows (if @Option1 is False)
    (@Option1 = 'False')
like image 35
XIVSolutions Avatar answered Jun 06 '26 09:06

XIVSolutions



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!