Postgres NOT IN (null) gives no result

后端 未结 6 1325
长发绾君心
长发绾君心 2021-02-07 05:03

I\'m using Postgres with this query

select 
*
from Entity this_ 
where 
(this_.ID not in (null))

Why does this give me no results? I would expe

相关标签:
6条回答
  • 2021-02-07 05:11

    The result of [not] in (null) will always be null. To compare to null you need is [not] null or is [not] distinct from null

    select *
    from Entity this_ 
    where this_.ID is not null
    

    If you want where (ID not in (1,null)) as in your comment you can do

    where ID is not null and ID not in (1)
    
    0 讨论(0)
  • 2021-02-07 05:12
    select * 
    from Entity this_ 
    where (this_.ID not in (null))
    

    "IN" or "NOT IN" do not select NULL values You can write

    select * 
    from Entity this_ 
    where (this_.ID not in (1))
    

    And your selection will not contains null values

    0 讨论(0)
  • 2021-02-07 05:21

    I have had similar in problem and eventually came up with the following solution;

    select * from public."Employee_11" where (COALESCE("Name",'@'),"Surname") 
        in (
            ('@','dummy')
        )
    

    It does return the records which Name column has null values. You can also use this for not in clause which will return not null records of Name;

      select * from public."Employee_11" where (COALESCE("Name",'@'),"Surname") 
            not in (
                ('@','dummy')
            )
    
    0 讨论(0)
  • 2021-02-07 05:29

    I had similar problem. My ego that I knew SQL well, got punctured. Here is the simplified example from scott/tiger tables.

    select empno, ename from emp where deptno not in (10, 20, null);
    

    Returned nothing. Although I use NOT IN condition very sparingly because it does not use index and is very slow. I prefer to use OUTER JOIN instead.

    I tried this query in Postgres and Oracle both and results are the same. So, must be a standards compliant result. NULL behaves this way only in NOT IN condition.

    0 讨论(0)
  • 2021-02-07 05:31

    PostgreSQL uses NULL as undefined value.
    What you're asking is to return the items that are not in a list or an undefined value. Since undefined means that you do not know what's inside, PostgreSQL does not return any item because simply can not respond to the request.
    While the request:

    select * from Entity where id in (1, null)
    

    can return the records, because if it finds an element with ID = 1 knows that is in the collection
    the request:

    select * from Entity where (ID not in (1, null))
    

    can not be satisfied because the null value can be any value.

    0 讨论(0)
  • 2021-02-07 05:34

    You can use <> ANY operator. Example on your code:

    select 
      * 
    from Entity this_ 
    where 
       (this_.ID <> ANY (null))
    
    0 讨论(0)
提交回复
热议问题