Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comparing a value to a NULL in t-SQL

I was curious if it's legal in t-SQL to compare a NULL to a value?

For instance, if I have:

WITH ctx AS(SELECT 123 AS n0, NULL AS n1)
SELECT n0 FROM ctx
WHERE ctx.n1 < 130

the WHERE clause in that case is always evaluated as FALSE. Is it something I can rely on?

like image 886
ahmd0 Avatar asked Jul 26 '12 05:07

ahmd0


People also ask

How do you compare values with NULL?

Comparing NULL values Since you can't use a equality operator in the WHERE clause (remember, NULL values can't be equated or compared), the right way to compare NULL values is to use the IS and IS NOT operators.

Can null value be compared in SQL?

It is not possible to test for NULL values with comparison operators, such as =, <, or <>. We will have to use the IS NULL and IS NOT NULL operators instead.

How can I compare two values when one is NULL in SQL Server?

SQL has the is [not] null predicate to test if a particular value is null . With is [not] distinct from SQL also provides a comparison operator that treats two null values as the same. Note that you have to use the negated form with not to arrive at similar logic to the equals ( = ) operator.


2 Answers

You can't compare NULL with any other value, it will result in 'UNKNOWN'.

From msdn source

A value of NULL indicates that the value is unknown. A value of NULL is different from an empty or zero value. No two null values are equal. Comparisons between two null values, or between a NULL and any other value, return unknown because the value of each NULL is unknown.

like image 61
Vishwanath Dalvi Avatar answered Sep 28 '22 03:09

Vishwanath Dalvi


All boolean operations in T-Sql with null value returns 'UNKNOWN', which is recognized as false in clauses. You can use ISNULL function when you want set some default value. for example in your case:

WITH ctx AS(SELECT 123 AS n0, NULL AS n1)
SELECT n0 FROM ctx
WHERE isnull(ctx.n1,0) < 130
like image 25
ASpirin Avatar answered Sep 28 '22 03:09

ASpirin