Filter Window Output Via Subquery
Window functions evaluate after WHERE, so filtering on row_number output requires numbering rows in a CTE first, then selecting rn = 1 outside.
Code
WITH employees(dept, name, salary) AS (
VALUES
('infra', 'ada', 4200),
('infra', 'kim', 3800),
('infra', 'raj', 3800),
('web', 'mei', 3300),
('web', 'zoe', 2900)
),
-- 第一步:在子查询/CTE 里编号
ranked AS (
SELECT
dept, name, salary,
ROW_NUMBER() OVER (PARTITION BY dept ORDER BY salary DESC) AS rn
FROM employees
)
-- 第二步:在外层过滤窗口输出
SELECT dept, name, salary
FROM ranked
WHERE rn = 1
ORDER BY dept;
-- 直接写 WHERE ROW_NUMBER() OVER (...) = 1 会报错:
-- ERROR: window functions are not allowed in WHERE
-- 窗口函数在 WHERE 过滤完行之后才求值,只能先编号再过滤。
-- 并列最高时 ROW_NUMBER 只取其一;要并列全取改用 RANK() <= 1 或 DISTINCT ON。Inside the snippet
At its core this is a single SELECT statement against employees and ranked.
The pieces that do the work: a CTE (WITH … AS) that names an intermediate result before the main query; a WHERE clause that limits which rows the statement affects; a window function (OVER (…)) computing values across rows without collapsing them; an ORDER BY that fixes the output order.
Caveats
- Window functions evaluate after
WHERE/GROUP BY, so filtering on their output in the same-levelWHEREwill not work — use an outer query or a CTE.
Using it
The employees table is the working surface here.
Interactive Tools for This Topic
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.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.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 relations are involved here?
- `employees`, `ranked`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.