I’m learning PostgreSQL and want to understand the exact order in which SQL statements are evaluated. After researching, I found the following evaluation order:
1. FROM
2. ON
3. JOIN
4. WHERE
5. GROUP BY
6. HAVING
7. SELECT
8. AS
9. DISTINCT
10. ORDER BY
11. LIMIT / OFFSET
Based on this order, it seems that when I create an alias, I can’t use it in the clauses that are evaluated before the SELECT
statement. However, I’m confused about how this works with subqueries. For example:
SELECT first_name, last_name
FROM customer AS c
WHERE EXISTS(
(SELECT * FROM payment AS p
WHERE p.customer_id = c.customer_id
AND amount > 11)
);
How can the subquery use the alias c
and, how does the subquery get access to the alias c
before it is created?
Could someone provide insights how does this work?
Thank you in advance for the help!
2
Answers
This is mentioned in the docs:
Section 9.23.1
EXISTS
also says the same thing.Note also:
This is not the same as a scalar subquery. A scalar subquery is used in place of a single value in an expression, and must only return a single row (or none). Whereas a lateral join can return multiple rows, and joins back to the previous table references as normal.
As a side point, your list of evaluation order isn’t accurate.
SELECT
andAS
are essentially the same thing.ON
andJOIN
are also. You are also missing Window Functions which come afterHAVING
, and set operatorsUNION
and friends, which come afterDISTINCT
but beforeORDER BY
.c
is an alias for a table, so it belongs to theFROM
clause, so it makes sense that it is available in a subquery inWHERE
.Consider the following query:
x
is a column alias,t
andc
are table aliases.This will work:
But this will not: