Re: Subqueries

From: Laurenz Albe <laurenz(dot)albe(at)cybertec(dot)at>
To: Narsimham Chelluri <nchelluri(at)gmail(dot)com>, pgsql-novice(at)postgresql(dot)org
Subject: Re: Subqueries
Date: 2025-03-06 14:23:27
Message-ID: 35e4de19cd13bf1b2744fccf647b94e0e4476b61.camel@cybertec.at
Views: Whole Thread | Raw Message | Download mbox | Resend email
Thread:
Lists: pgsql-novice

On Wed, 2025-03-05 at 15:01 -0400, Narsimham Chelluri wrote:
> Can someone please explain to me why my first query does not return an error?
>
> subquerytest=# select * from something where id in (select id);
>  id
> ----
> (0 rows)
>
> I would imagine it has something to do with: "from something" means that "id"
> is available in the subquery and refers to the column in "something" and of
> course does not refer to "somethingelse" because that doesn't have such a
> column on it.

Right.

> And that I would have to disambiguate if it did by using
> aliases or table names preceding a dot.

Right again.

> If that is correct: I almost made a mistake in a subquery where I used
> the wrong column in the subquery. Is it possible to make the subquery refer
> only to values within its own specific from clause and error out otherwise?
> Maybe I could do that with a CTE?

I follow the following rule:
Whenever an SQL statement refers to more than one table, qualify all column
references with the table alias:

select * from something where something.id in (select somethingelse.id);

Yours,
Laurenz Albe

In response to

  • Subqueries at 2025-03-05 19:01:49 from Narsimham Chelluri

Browse pgsql-novice by date

  From Date Subject
Next Message Ayden Gera 2025-04-24 21:50:57 PGDump question/issue
Previous Message Bzzzz 2025-03-06 14:05:06 Re: Subqueries