Correlated Subquery Top N Per Group
Find the top N rows per group using a correlated subquery with a count of better rows for ranking.
Code
SELECT department, employee_name, salary
FROM employees e1
WHERE (
SELECT COUNT(*)
FROM employees e2
WHERE e2.department = e1.department
AND e2.salary > e1.salary
) < 3
ORDER BY department, salary DESC;What the code does
At its core this is a single SELECT statement against employees.
Breaking the statements into their working parts: a WHERE clause limiting a statement to the rows that qualify; COUNT aggregation; an ORDER BY that fixes the output order.
Applying it
Point it at the employees table.
Statements that matter
SELECT department, employee_name, salary
FROM employees e1
WHERE (
SELECT COUNT(*)
FROM employees e2
WHERE e2.department = e1.department
AND e2.salary > e1.salary
) < 3
ORDER BY department, salary 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 relations are involved here?
- The references are `employees`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.