Re: [HACKERS] correlated subquery - Mailing list pgsql-hackers

From Tom Lane
Subject Re: [HACKERS] correlated subquery
Date
Msg-id 5329.946509487@sss.pgh.pa.us
Whole thread Raw
In response to correlated subquery  (Bruce Momjian <pgman@candle.pha.pa.us>)
List pgsql-hackers
Bruce Momjian <pgman@candle.pha.pa.us> writes:
> Is this a good example of a required correlated subquery:
>     SELECT f1.firstname, f1.lastname, f1.age
>     FROM friends f1
>     WHERE age = (
>                  SELECT MAX(age)
>                  FROM friends f2
>                  WHERE f1.state = f2.state
>                 )
>     ORDER BY firstname, lastname

> It finds the oldest person in each state.  HAVING can't do that, right?

Yes, I think you are right.  You could find the oldest age in each state
with a HAVING:
SELECT state, MAX(age) FROM friends GROUP BY state;

but I don't see any way to get the other attributes of the record(s)
matching that age, except by using a subselect.
        regards, tom lane


pgsql-hackers by date:

Previous
From: Adriaan Joubert
Date:
Subject: Re: [HACKERS] Index corruption
Next
From: wieck@debis.com (Jan Wieck)
Date:
Subject: Re: [HACKERS] Index corruption