Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

IS NULL vs = NULL in where clause + SQL Server

Tags:

How to check a value IS NULL [or] = @param (where @param is null)

Ex:

Select column1 from Table1
where column2 IS NULL => works fine

If I want to replace comparing value (IS NULL) with @param. How can this be done

Select column1 from Table1
where column2 = @param => this works fine until @param got some value in it and if is null never finds a record.

How can this achieve?

like image 376
Sreedhar Avatar asked Mar 22 '10 05:03

Sreedhar


People also ask

Is NULL in where clause SQL Server?

Let's look at how to use the IS NULL condition in a SELECT statement in SQL Server. For example: SELECT * FROM employees WHERE last_name IS NULL; This SQL Server IS NULL example will return all records from the employees table where the last_name contains a null value.

Is NULL in where clause?

Generally, NULL data represents data does not exist or missing data or unknown data. IS NULL & IS NOT NULL in SQL is used with a WHERE clause in SELECT, UPDATE and DELETE statements/queries to validate whether column has some value or data does not exist for that column. Please note that NULL and 0 are not same.

Is NULL and NULL same in SQL?

null is well-defined value which may represent an unknown value, but it may also represent the absence of a value. It should be up to the developer to decide what null represents, but null itself is absolutely a value and null is null = null.

Is NULL () in SQL Server?

The ISNULL() function returns a specified value if the expression is NULL. If the expression is NOT NULL, this function returns the expression.


2 Answers

select column1 from Table1
  where (@param is null and column2 is null)
     or (column2 = @param)
like image 53
Laurence Gonsalves Avatar answered Sep 20 '22 18:09

Laurence Gonsalves


I realize this is an old question, but I had the same one, and came up with another (shorter) answer. Note: this may only work for MS SQL Server, which supports ISNULL(expr,replacement).

SELECT column1 FROM table1
WHERE ISNULL(column2,'') = ISNULL(@param,'')

This also assumes you treat NULL and empty strings the same way.

like image 39
Dan Avatar answered Sep 19 '22 18:09

Dan