Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write this Conditional where clause in SQl Server?

Tags:

sql

sql-server

Hi I have the following type of query:

Select a,b from tab1 whre tab1.id in 
 (Select id from tab2 where x=1 and y=2 and  z>getdate())

Now z is a datetime column in tab2 and it is nullable column.So I want the check z > getdate() only if it is not null. Checked Conditional WHERE clause in SQL Server but could not do it accurately.Basically I dont want the 'z' column check in the above query if it is null in tab2.

Thanks in advance.

like image 212
user2948533 Avatar asked Jul 18 '26 06:07

user2948533


2 Answers

Did you mean:

Select a,b from tab1 where tab1.id in 
 (Select id from tab2 where x=1 and y=2 and  (z is null or (z is not null and z>getdate())))
like image 152
HoneyBadger Avatar answered Jul 19 '26 19:07

HoneyBadger


I think you need a combination of AND and OR operators. When combining these you need to be aware of operator precedence. In my example I've used brackets to ensure that x, y AND z are checked together, with z then rechecked separately. The query returns any record where check block 1 OR 2 is true.

In my example I've used a JOIN but you can apply this same technique to your original sub query.

Example

SELECT
    t1.a,
    t1.b
FROM
    Tab1 AS t1
        INNER JOIN Tab2 AS t2            ON t1.Id = t2.Id
WHERE
    (
        -- Check block 1.
        t2.x = 1
        AND t2.y = 1
        AND t2.z > GETDATE()                
    )
    -- Check block 2.
    OR z IS NULL
;

EDIT: I'm not entirely sure I understand the question. If you could provide some sample records and the expected output that would help.

like image 27
David Rushton Avatar answered Jul 19 '26 20:07

David Rushton