3

What is happening here?

I got two tables, test1 and test2:

create table test1 (id1 int4 primary key);
create table test2 (id2 int4 primary key);

As expected, this query:

select id1 from test2;

produces a syntax error:

ERROR:  column "id1" does not exist
LINE 1: select id1 from test2;

However, when I try to execute this query:

select * from test1 where id1 in (select id1 from test2);

PostgreSQL doesn't complain, executes the query and gives me:

 id1
-----
(0 rows)

Is there any logic in this? Or should I file a bug report?

1
  • 1
    Aside: I'd use the the generally superior WHERE EXISTS () instead of WHERE col IN (). Commented Oct 16, 2013 at 15:44

1 Answer 1

4

Columns from outer select are visible in sub-select.

Your query is equivalent to:

select * 
from test1 
where test1.id1 in (select test1.id1 from test2);
Sign up to request clarification or add additional context in comments.

2 Comments

Ok, so if table test1 contains a single value 42, the subquery is interpreted as "select 42 from test2", which is valid sql?
Tnx :) Just got a real life example of this behavior and it confused the hell out of me :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.