Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WHERE clause using values that could be NULL

I need to do something like this:

DECLARE @firstname VARCHAR(35)
DECLARE @lastname VARCHAR(35)

SELECT *
FROM Customers 
WHERE Firstname = @firstname AND Lastname = @lastname

The problem is that @firstname and @lastname could sometimes be NULL. In those cases, the query above would fail to find matching rows because NULL is never equal to NULL.

If one of these variables is NULL, I'd like to return a match if the corresponding value in the database is also NULL. But, of course, SQL Server uses IS to compare for NULL. And if either value is NULL in the example above, it is not considered a match.

Is there any way to accomplish this?

like image 301
Jonathan Wood Avatar asked Jul 31 '26 05:07

Jonathan Wood


1 Answers

Just use AND/OR logic e.g.

SELECT *
FROM Customers
WHERE ((Firstname IS NULL AND @firstname IS NULL) OR Firstname = @firstname)
AND ((Lastname IS NULL AND @lastname IS NULL) OR Lastname = @lastname);
like image 110
Dale K Avatar answered Aug 03 '26 00:08

Dale K



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!