Processing Order
- SELECT within WITH
- FROM
- WHERE
- GROUP BY
- HAVING
- SELECT
- Functions on columns, DISTINCT, etc.
- UNION, INTERSECT, EXCEPT
- ORDER BY
- LIMIT
Manual
SELECT https://www.postgresql.org/docs/14/sql-select.html
SELECTreturns rows from zero or more tables. The general processing ofSELECTis as follows:
- All queries in the
WITHlist are computed. These effectively serve as temporary tables that can be referenced in theFROMlist. AWITHquery that is referenced more than once inFROMis computed only once, unlessNOT MATERIALIZEDis specified.- All elements in the
FROMlist are computed. (Each element in theFROMlist is either a real or virtual table.) If more than one element is specified in theFROMlist, they are cross-joined together.- If the
WHEREclause is specified, all rows that do not satisfy the condition are eliminated from the output.- If the
GROUP BYclause is specified, or if there are aggregate function calls, the output is combined into groups of rows that match on one or more values, and the results of aggregate functions are computed. If theHAVINGclause is present, it eliminates groups that do not satisfy the given condition.- The actual output rows are computed using the
SELECToutput expressions for each selected row or row group.SELECT DISTINCTeliminates duplicate rows from the result.SELECT DISTINCT ONeliminates rows that match on all the specified expressions.SELECT ALL(the default) returns all candidate rows, including duplicates.- Using the operators
UNION,INTERSECT, andEXCEPT, the output of more than oneSELECTstatement can be combined to form a single result set.- If the
ORDER BYclause is specified, the returned rows are sorted in the specified order.- If the
LIMIT(orFETCH FIRST) orOFFSETclause is specified, theSELECTstatement only returns a subset of the result rows.- If a
FOR UPDATE,FOR NO KEY UPDATE,FOR SHARE, orFOR KEY SHAREclause is specified, theSELECTstatement locks the selected rows against concurrent updates.
Side Note
I noticed that the processing order of DISTINCT differs between PostgreSQL 8.0.4 and PostgreSQL 14. I wonder why.