IN Clause with NULL or IS NULL

后端 未结 7 1540
我在风中等你
我在风中等你 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 00:41
    SELECT *
    FROM tbl_name
    WHERE coalesce(id_field,'unik_null_value') 
    IN ('value1', 'value2', 'value3', 'unik_null_value')
    

    So that you eliminate the null from the check. Given a null value in id_field, the coalesce function would instead of null return 'unik_null_value', and by adding 'unik_null_value to the IN-list, the query would return posts where id_field is value1-3 or null.

    0 讨论(0)
  • 2020-11-30 00:54

    The question as answered by Daniel is perfctly fine. I wanted to leave a note regarding NULLS. We should be carefull about using NOT IN operator when a column contains NULL values. You won't get any output if your column contains NULL values and you are using the NOT IN operator. This is how it's explained over here http://www.oraclebin.com/2013/01/beware-of-nulls.html , a very good article which I came across and thought of sharing it.

    0 讨论(0)
  • 2020-11-30 00:56

    I know that is late to answer but could be useful for someone else You can use sub-query and convert the null to 0

    SELECT *
    FROM (SELECT CASE WHEN id_field IS NULL 
                    THEN 0 
                    ELSE id_field 
                END AS id_field
          FROM tbl_name) AS tbl
    WHERE tbl.id_field IN ('value1', 'value2', 'value3', 0)
    
    0 讨论(0)
  • 2020-11-30 00:59

    Null refers to an absence of data. Null is formally defined as a value that is unavailable, unassigned, unknown or inapplicable (OCA Oracle Database 12c, SQL Fundamentals I Exam Guide, p87). So, you may not see records with columns containing null values when said columns are restricted using an "in" or "not in" clauses.

    0 讨论(0)
  • 2020-11-30 01:02

    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)
    
    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题