Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Coalesce in WHERE clause

Tags:

sql

sql-server

I'm trying to implement optional parameters in a stored procedure that I have but I am running into a problem. Here's a simplified query to illustrate the issue:

SET ANSI_NULLS OFF

DECLARE @MiddleName VARCHAR(20);
SET @MiddleName = NULL;

SELECT * FROM [Customer]
WHERE [LastName] = 'Torres'
AND [MiddleName] = COALESCE(@MiddleName, [MiddleName])

When I run this query I need to get one row back because one Torres has NULL in the [MiddleName] column. But the query returns zero rows. Using IFNULL() produces the same result. From researching COALESCE, I was under the impression that NULL would be returned if all expressions are NULL. As I am not a SQL expert I assume that I am missing something, but what is it.....

Thanks in advance for any help.

like image 890
mpeterb Avatar asked Mar 11 '09 15:03

mpeterb


People also ask

Can you use coalesce in where clause?

Since COALESCE function is an expression in itself, it can be used in any statement or clause that accepts expressions like SELECT, WHERE and HAVING.

Where can you use coalesce?

The SQL server's Coalesce function is used to handle the Null values. The null values are replaced with user-defined values during the expression evaluation process. This function evaluates arguments in a particular order from the provided arguments list and always returns the first non-null value.

How do you use coalesce in case statement in SQL?

The SQL COALESCE function can be syntactically represented using the CASE expression. For example, as we know, the Coalesce function returns the first non-NULL values. SELECT COALESCE (expression1, expression2, expression3) FROM TABLENAME; The above Coalesce SQL statement can be rewritten using the CASE statement.

What is coalesce () in SQL?

Definition and Usage. The COALESCE() function returns the first non-null value in a list.


2 Answers

The problem is that in sql, "WHERE Null = Null" will never return any rows since Null does not equal itself.

You have to do

SELECT * FROM [Customer]
WHERE [LastName] = 'Torres'
AND ( @MiddleName IS NULL OR [MiddleName] = @MiddleName )
like image 68
David Avatar answered Sep 26 '22 03:09

David


You state you are looking for the query to return the row where the field MiddleName is NULL. Unfortunately (NULL = NULL) does not return true, it returns NULL.

You need something like...

SELECT * FROM [Customer]
WHERE [LastName] = 'Torres'
AND ([MiddleName] = @MiddleName OR @MiddleName IS NULL)
like image 31
MatBailie Avatar answered Sep 26 '22 03:09

MatBailie