Select .... where id not in (....) returns 0 incorrectly

From: "J(dot) Roeleveld" <joost(at)antarean(dot)org>
To: "pgsql-generallists(dot)postgresql(dot)org" <pgsql-general(at)lists(dot)postgresql(dot)org>
Subject: Select .... where id not in (....) returns 0 incorrectly
Date: 2022-04-04 12:08:27
Message-ID: 5820573.lOV4Wx5bFT@iris
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general

Hi all,

While trying to write some queries to clean up records I no longer need, I
come up with a very strange situation where numbers literally don't add up as
expected.

If anyone can help me trace where this strange behaviour is coming from and
how to resolve it, please let me know.
In case this is already resolved in a recent version, I am currently using
version 11.14.

Please see the following log from psql:

joost=> create temporary table q ( id integer );
CREATE TABLE
joost=> insert into q ( id ) select snapshotlistid from backupitem;
INSERT 0 765
joost=> insert into q ( id ) select snapshotlistid from queue;
INSERT 0 3183

joost=> select count(1) from q;
count
-------
3948
(1 row)

joost=> select count(1) from snapshotlist where id in (select id from q);
count
-------
1810
(1 row)

joost=> select count(1) from snapshotlist where id not in (select id from q);
count
-------
0
(1 row)

joost=> select count(1) from snapshotlist where id not in (select id from
snapshotlist where id in (select id from q));
count
---------
2293923
(1 row)

The tables are defined like: (Note, I did remove some fields from the tables
which have no impact. Most are foreign keys to further tables or varchar data
fields)

CREATE TABLE snapshotlist (
id SERIAL PRIMARY KEY,
active boolean,
created TIMESTAMP DEFAULT clock_timestamp(),
modified TIMESTAMP
);

CREATE TABLE queue (
id SERIAL PRIMARY KEY,
queuetask VARCHAR(500) NOT NULL,
snapshotlistid INTEGER REFERENCES snapshotlist(id) ON DELETE RESTRICT,
uuid uuid NOT NULL,
UNIQUE(uuid)
);

CREATE TABLE backupitem (
id SERIAL PRIMARY KEY,
snapshotlistid INTEGER REFERENCES snapshotlist(id) ON DELETE RESTRICT NOT
NULL,
UNIQUE(snapshotlistid)
);

Responses

Browse pgsql-general by date

  From Date Subject
Next Message Sebastien Flaesch 2022-04-04 12:38:47 Re: Transaction and SQL errors
Previous Message David Rowley 2022-04-04 11:44:40 Re: Transaction and SQL errors