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!