Wednesday, June 30, 2010

Difference between <>NULL/!=NULL/==NULL and IS NOT NULL/IS NULL

Consider following 2 queries:

1. SELECT * FROM Emp WHERE MiddleName <> NULL
2. SELECT * FROM Emp WHERE MiddleName IS NOT NULL

Are the above 2 queries same? If not then what is the difference?

The difference in two queries lies in terms of how SQL Server interprets two queries and executes it at back end. The comparison operator "<>"can only be used with the valid data/ value and NULL doesn’t qualify as any data type and there is no memory location for NULL (practically SQL Server allocates 0 bytes for NULL).
Therefore with the first query, SQL Server will fail to compare the middle name with any values and hence the query will return 0 rows even if table has some NOT NULL values. But please not that there is no error thrown by the SQL Server which is contrary to Oracle.Second query would return all the rows where Middle Name is not null.

Courtesy Pramod and Sandeep

No comments:

Post a Comment