IN Clause with NULL or IS NULL

后端 未结 7 1572
我在风中等你
我在风中等你 2020-11-30 00:26

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\         


        
7条回答
  •  自闭症患者
    2020-11-30 01:05

    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 parentheses. The accepted answer is a bit misleading in this respect.

提交回复
热议问题