Re: select where not in () fails

From: Andrew Gierth <andrew(at)tao11(dot)riddles(dot)org(dot)uk>
To: Gary Stainburn <gary(dot)stainburn(at)ringways(dot)co(dot)uk>
Cc: pgsql-sql(at)lists(dot)postgresql(dot)org, Pavel Stehule <pavel(dot)stehule(at)gmail(dot)com>
Subject: Re: select where not in () fails
Date: 2018-09-22 18:13:03
Message-ID: 871s9lif94.fsf@news-spur.riddles.org.uk
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-sql

>>>>> "Gary" == Gary Stainburn <gary(dot)stainburn(at)ringways(dot)co(dot)uk> writes:

Gary> As I said in my description, some values will be NULL. I just
Gary> thought that these would not be included in the select. I did not
Gary> think that it would stop the subselect from working

https://wiki.postgresql.org/wiki/Don%27t_Do_This#Don.27t_use_NOT_IN

Gary> users=# select count(u_id) from users where u_id not in (select
Gary> distinct emp_u_id from employees where emp_u_id is not null);

Never use DISTINCT inside IN; the IN already implies it.

Always rewrite NOT IN (select ...) to use NOT EXISTS instead, like so:

select count(u_id) from users u
where not exists (select 1 from employees e where u.u_id=e.emp_u_id);

(and always qualify every column reference in the query, especially when
using IN)

--
Andrew (irc:RhodiumToad)

In response to

Browse pgsql-sql by date

  From Date Subject
Next Message ROS Didier 2018-10-06 09:57:25 Why the index is not used ?
Previous Message Pavel Stehule 2018-09-21 16:14:15 Re: select where not in () fails