why isn't this subquery wrong?

From: jonathan vanasco <postgres(at)2xlp(dot)com>
To: pgsql-general general <pgsql-general(at)postgresql(dot)org>
Subject: why isn't this subquery wrong?
Date: 2017-04-20 22:17:25
Message-ID: 0B9030D9-7B8A-4921-9453-D0E3C6254818@2xlp.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general


I ran into an issue while changing a database schema around. Some queries still worked, even though I didn't expect them to.

Can anyone explain to me why the following is valid (running 9.6) ?

schema
CREATE TEMPORARY TABLE example_a__data (
foo_id INT,
bar_id INT
);
CREATE TEMPORARY TABLE example_a__rollup_source (
id int primary key,
name varchar(64),
foo_id INT,
check_bool BOOLEAN
);
CREATE TEMPORARY TABLE example_a__rollup AS
SELECT id, name, foo_id
FROM example_a__rollup_source
WHERE check_bool IS TRUE
;

query:
SELECT foo_id
FROM example_a__data
WHERE foo_id IN (SELECT bar_id FROM example_a__rollup)
;

a raw select of `SELECT bar_id FROM example_a__rollup;` will cause an error because bar_id doesn't exist

postgres doesn't raise an error because example_a__data does have a bar_id -- but example_a__rollup doesn't and there's no explicit correlation in the query.

can someone explain why this happens? i'm guessing there is a good reason -- but I'm unfamiliar with the type of implicit join/queries this behavior is enabling.

Responses

Browse pgsql-general by date

  From Date Subject
Next Message Steve Crawford 2017-04-20 22:38:02 Re: why isn't this subquery wrong?
Previous Message Samuel Williams 2017-04-20 21:45:29 Re: Large data and slow queries