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?
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.
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.
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.
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.
An
in
statement will be parsed identically tofield=val1 or field=val2 or field=val3
. Putting a null in there will boil down tofield=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)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With