Re: order by alias - doesn't work sometimes?

From: Tom Lane <tgl(at)sss(dot)pgh(dot)pa(dot)us>
To: depesz(at)depesz(dot)com
Cc: pgsql-bugs(at)lists(dot)postgresql(dot)org
Subject: Re: order by alias - doesn't work sometimes?
Date: 2025-10-14 15:10:31
Message-ID: 959907.1760454631@sss.pgh.pa.us
Views: Whole Thread | Raw Message | Download mbox | Resend email
Thread:
Lists: pgsql-bugs

hubert depesz lubaczewski <depesz(at)depesz(dot)com> writes:
> But:
> =$ select unnest( ARRAY['d', 'c', 'a'] ) x order by x <> 'a';
> ERROR: column "x" does not exist
> LINE 1: select unnest( ARRAY['d', 'c', 'a'] ) x order by x <> 'a';
> ^

> Obviously I can put the unnest() call in from, and then it works, but
> I'm curious, why we can `order by x`, but not `order by x <> 'a'` ?

ORDER BY output-column-alias is a messy hangover from SQL92.
In later SQL versions, identifiers in ORDER BY have the same
interpretation as in WHERE and other clauses, namely they are
columns sourced by the FROM clause. Supporting both interpretations
makes for a lot of ambiguity, so we only allow the old interpretation
in exactly the case required by SQL92, namely "ORDER BY identifier".

This is documented ...

regards, tom lane

In response to

Responses

Browse pgsql-bugs by date

  From Date Subject
Next Message hubert depesz lubaczewski 2025-10-14 15:46:23 Re: order by alias - doesn't work sometimes?
Previous Message hubert depesz lubaczewski 2025-10-14 14:50:56 order by alias - doesn't work sometimes?