Received: from malur.postgresql.org ([2a02:16a8:dc51::56]) by arkaria.postgresql.org with esmtps (TLS1.2:ECDHE_RSA_AES_256_CBC_SHA384:256) (Exim 4.89) (envelope-from ) id 1g3mP6-0007tN-Nx for pgsql-sql@arkaria.postgresql.org; Sat, 22 Sep 2018 18:13:16 +0000 Received: from localhost ([127.0.0.1] helo=malur.postgresql.org) by malur.postgresql.org with esmtp (Exim 4.89) (envelope-from ) id 1g3mP2-0004xG-Gt for pgsql-sql@arkaria.postgresql.org; Sat, 22 Sep 2018 18:13:12 +0000 Received: from magus.postgresql.org ([2a02:c0:301:0:ffff::29]) by malur.postgresql.org with esmtps (TLS1.2:ECDHE_RSA_AES_256_CBC_SHA384:256) (Exim 4.89) (envelope-from ) id 1g3mP2-0004wQ-AL for pgsql-sql@lists.postgresql.org; Sat, 22 Sep 2018 18:13:12 +0000 Received: from lungold.riddles.org.uk ([82.68.208.19]) by magus.postgresql.org with esmtps (TLS1.2:ECDHE_RSA_AES_256_CBC_SHA384:256) (Exim 4.89) (envelope-from ) id 1g3mOz-0005sP-5Z for pgsql-sql@lists.postgresql.org; Sat, 22 Sep 2018 18:13:11 +0000 Received: from [192.168.127.1] (port=52921 helo=caithnard.riddles.org.uk) by lungold.riddles.org.uk with esmtps (TLSv1.2:ECDHE-RSA-AES256-GCM-SHA384:256) (Exim 4.88 (FreeBSD)) (envelope-from ) id 1g3mOv-000AlK-Nq; Sat, 22 Sep 2018 18:13:05 +0000 Received: from [127.0.0.1] (port=56940 helo=caithnard.riddles.org.uk) by caithnard.riddles.org.uk with esmtp (Exim 4.89 (FreeBSD)) (envelope-from ) id 1g3mOu-00084S-Pr; Sat, 22 Sep 2018 18:13:04 +0000 From: Andrew Gierth To: Gary Stainburn Cc: pgsql-sql@lists.postgresql.org, Pavel Stehule Subject: Re: select where not in () fails In-Reply-To: <201809211620.16084.gary.stainburn@ringways.co.uk> (Gary Stainburn's message of "Fri, 21 Sep 2018 16:20:16 +0100") Message-ID: <871s9lif94.fsf@news-spur.riddles.org.uk> References: <201809211608.41086.gary.stainburn@ringways.co.uk> <201809211620.16084.gary.stainburn@ringways.co.uk> User-Agent: Gnus/5.13 (Gnus v5.13) Emacs/25.1 (berkeley-unix) Date: Sat, 22 Sep 2018 19:13:03 +0100 MIME-Version: 1.0 Content-Type: text/plain List-Id: List-Help: List-Subscribe: List-Post: List-Owner: List-Archive: Precedence: bulk >>>>> "Gary" == Gary Stainburn 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)