Output Alias Order By Versus Where Having
SELECT-list aliases are visible to ORDER BY but not to WHERE or HAVING; PostgreSQL additionally lets GROUP BY refer to output column names.
Code
-- 逻辑求值顺序:FROM → WHERE → GROUP BY → HAVING → SELECT(别名在这里诞生)→ ORDER BY
SELECT
team_id,
COUNT(*) AS entries,
SUM(score)::numeric / COUNT(*) AS avg_score
FROM submissions
WHERE score >= 0 -- WHERE 在 SELECT 之前执行:avg_score 在这里不可见
GROUP BY team_id -- PG 允许 GROUP BY 引用输出名 entries;WHERE 与 HAVING 才不可见
HAVING COUNT(*) > 1 -- HAVING 里别名不可见:用聚合本身,或重复写表达式
ORDER BY avg_score DESC; -- ORDER BY 在 SELECT 之后:别名可用
-- WHERE 里要用聚合别名只能包一层子查询:
-- 别名在外层 SELECT 里诞生,外层 WHERE 才看得见
SELECT *
FROM (
SELECT team_id, COUNT(*) AS entries
FROM submissions
GROUP BY team_id
) per_team
WHERE entries > 1
ORDER BY entries DESC;How the snippet works
What runs here is SELECT — submissions are the objects involved.
What the statements actually assemble: a WHERE clause that keeps only the rows a statement is meant to touch; COUNT, SUM aggregation; a GROUP BY that collapses matching rows into one output row per group; an ORDER BY that fixes the output order.
Applying it
The submissions table is the working surface here.
Statements that matter
SELECT *
FROM (
SELECT team_id, COUNT(*) AS entries
FROM submissions
GROUP BY team_id
) per_team
WHERE entries > 1
ORDER BY entries DESC;
Interactive Tools for This Topic
PostgreSQL EXPLAIN AnalyzerAnalyze PostgreSQL EXPLAIN ANALYZE text or FORMAT JSON plans locally to flag Seq Scans, slow nodes, row misestimates, disk sorts, and index hints.SQL DDL to TypeScript ConverterConvert SQL CREATE TABLE DDL statements into strict TypeScript interfaces with nullable, array, enum, JSONB, and Date or ISO string column mappings.Multi-Mode Escape & Unescape CodecEscape and unescape strings safely across JSON, JavaScript, SQL single-quoted literals, POSIX shell single quotes, and RFC 4180 CSV cells in your browser.SQL FormatterReformat SQL by uppercasing reserved words and breaking lines before SELECT, FROM, WHERE, and other clauses.
FAQ
- Which tables appear in this script?
- The references are `submissions`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.