Re: [GENERAL] Question about SELECT statements with subselects - Mailing list pgsql-general

From Albe Laurenz
Subject Re: [GENERAL] Question about SELECT statements with subselects
Date
Msg-id A737B7A37273E048B164557ADEF4A58B7221CBB6@ntex2010i.host.magwien.gv.at
Whole thread Raw
In response to [GENERAL] Question about SELECT statements with subselects  (Miloslav Semler <miloslav.semler@crytur.cz>)
Responses Re: [GENERAL] Question about SELECT statements with subselects  (Miloslav Semler <miloslav.semler@crytur.cz>)
List pgsql-general
Miloslav Semler wrote:
> I found strange behavior with subselects and I am not able to explain
> it. I have several tables in schema:
> 
> tramecky, mt_hodnoty, plata_kusy
> 
> in these tables, id is always primary key (serial), table_id is always
> foreign key to table. When I run this query:
> 
> select tramecky.id FROM a.tramecky WHERE
>      id NOT IN(SELECT tramecky_id FROM a.plata_kusy) AND
>      expedicni_plato IS NULL
> 
> I get 55 rows.
> 
> When I run this query:
> 
> select tramecky.id FROM a.tramecky WHERE
>      id NOT IN(SELECT tramecky_id FROM a.plata_kusy) AND
>      id NOT IN(SELECT tramecky_id FROM a.mt_hodnoty) AND
>      expedicni_plato IS NULL
> 
> I get no rows.. so I expect that rows with foreign keys tramecky_id of
> 55 rows are present in table mt_hodnoty. However result of query:
> 
> select mt_hodnoty.id FROM a.mt_hodnoty WHERE tramecky_id NOT IN(SELECT
> tramecky_id FROM a.plata_kusy)
> 
> is empty set. Can anybody explain such strange behavior?

There is probably one or more rows in "mt_hodnoty" where "tramecky_id" is NULL.

Then the subselect  SELECT tramecky_id FROM a.mt_hodnoty
contains a NULL values, and the NOT IN clause will result in NULL,
which is not TRUE, so the result set is empty.

The NULL value does not show up in your second query, because
the condition NULL NOT IN (...) is also always NULL.

Yours,
Laurenz Albe

--
Sent via pgsql-general mailing list (pgsql-general@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-general

pgsql-general by date:

Previous
From: Miloslav Semler
Date:
Subject: [GENERAL] Question about SELECT statements with subselects
Next
From: Miloslav Semler
Date:
Subject: Re: [GENERAL] Question about SELECT statements with subselects