Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

IN Clause with NULL or IS NULL

Postgres is the database

Can I use a NULL value for a IN clause? example:

SELECT * FROM tbl_name WHERE id_field IN ('value1', 'value2', 'value3', NULL) 

I want to limit to these four values.

I have tried the above statement and it doesn't work, well it executes but doesn't add the records with NULL id_fields.

I have also tried to add a OR condition but this just make the query run and run with no end in sight.

SELECT * FROM tbl_name WHERE other_condition = bar AND another_condition = foo AND id_field IN ('value1', 'value2', 'value3') OR id_field IS NULL 

Any suggestions?

like image 380
Phill Pafford Avatar asked Jun 15 '11 17:06

Phill Pafford


People also ask

Can I use NULL in in clause?

NULL has a special status in SQL. It represents the absence of value so, it cannot be used for comparison. If you use it for comparison, it will always return NULL. In order to use NULL value in NOT IN Clause, we can make a separate subquery to include NULL values.

Is NULL in condition?

Description. The IS NULL condition is used in SQL to test for a NULL value. It returns TRUE if a NULL value is found, otherwise it returns FALSE. It can be used in a SELECT, INSERT, UPDATE, or DELETE statement.

Can we use with NULL in SQL?

NULL can be assigned, but using ' = NULL ', ' <> NULL ', or any other comparison operator, in an expression with NULL as a value, is illegal in SQL and should trigger an error. It can never be correct.

Is NULL or in SQL Server?

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


2 Answers

An in statement will be parsed identically to field=val1 or field=val2 or field=val3. Putting a null in there will boil down to field=null which won't work.

(Comment by Marc B)

I would do this for clairity

SELECT * FROM tbl_name WHERE  (id_field IN ('value1', 'value2', 'value3') OR id_field IS NULL) 
like image 146
Daniel A. White Avatar answered Sep 23 '22 14:09

Daniel A. White


Your query fails due to operator precedence. AND binds before OR!
You need a pair of parentheses, which is not a matter of "clarity", but pure logic necessity.

SELECT * FROM   tbl_name WHERE  other_condition = bar AND    another_condition = foo AND   (id_field IN ('value1', 'value2', 'value3') OR id_field IS NULL);

The added parentheses prevent AND binding before OR. If there were no other WHERE conditions (no AND) you would not need additional parentheses. The accepted answer is misleading in this respect.

like image 42
Erwin Brandstetter Avatar answered Sep 24 '22 14:09

Erwin Brandstetter