Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL and logical operators and null checks

I've got a vague, possibly cargo-cult memory from years of working with SQL Server that when you've got a possibly-null column, it's not safe to write "WHERE" clause predicates like:

 ... WHERE the_column IS NULL OR the_column < 10 ...

It had something to do with the fact that SQL rules don't stipulate short-circuiting (and in fact that's kind-of a bad idea possibly for query optimization reasons), and thus the "<" comparison (or whatever) could be evaluated even if the column value is null. Now, exactly why that'd be a terrible thing, I don't know, but I recall being sternly warned by some documentation to always code that as a "CASE" clause:

 ... WHERE 1 = CASE WHEN the_column IS NULL THEN 1 WHEN the_column < 10 THEN 1 ELSE 0 END ...

(the goofy "1 = " part is because SQL Server doesn't/didn't have first-class booleans, or at least I thought it didn't.)

So my questions here are:

  1. Is that really true for SQL Server (or perhaps back-rev SQL Server 2000 or 2005) or am I just nuts?
  2. If so, does the same caveat apply to PostgreSQL? (8.4 if it matters)
  3. What exactly is the issue? Does it have to do with how indexes work or something?

My grounding in SQL is pretty weak.

like image 927
Pointy Avatar asked Dec 21 '11 00:12

Pointy


People also ask

Is NULL a logical operator in SQL?

In SQL ternary logic, NULL equates to the value of unknown. The take-away: Any logical operation involving a NULL results in a value of unknown except for TRUE OR NULL and FALSE AND NULL.

What operators deal with NULL in SQL?

The NULL is not zero or blank. It represents an unknown or inapplicable value. It can't be compared using AND / OR logical operators. The special operator 'IS' is used with the keyword 'NULL' to locate 'NULL' values.

What is NULL check in SQL?

A field with a NULL value is a field with no value. If a field in a table is optional, it is possible to insert a new record or update a record without adding a value to this field. Then, the field will be saved with a NULL value. Note: A NULL value is different from a zero value or a field that contains spaces.

Which SQL logical operator is used to compare a value with NULL?

You can use the IS NULL operator to test whether a given value expression is Null: . . .


1 Answers

Instead of

the_column IS NULL OR the_column < 10

I'd do

isnull(the_column,0) < 10

or for the first example

WHERE 1 = CASE WHEN isnull(the_column,0) < 10 THEN 1 ELSE 0 END ...
like image 72
L J Avatar answered Oct 12 '22 08:10

L J