Missing Partition By Ranks Globally
Without PARTITION BY, rank() orders the entire table; adding it restarts ranking inside each group, fixing silently wrong per-team standings.
Code
-- missing PARTITION BY: rank() spans the whole table
CREATE TABLE staff (
name text NOT NULL,
dept text NOT NULL,
score int NOT NULL
);
INSERT INTO staff VALUES
('ada', 'dev', 92),
('raj', 'dev', 85),
('lin', 'ops', 90),
('kim', 'ops', 78);
-- partition omitted: the 90 in ops still ranks behind the 85 in dev
SELECT name, dept, score,
rank() OVER (ORDER BY score DESC) AS global_rank
FROM staff
ORDER BY score DESC;
-- PARTITION BY added: ranking restarts inside each department
SELECT name, dept, score,
rank() OVER (PARTITION BY dept ORDER BY score DESC) AS dept_rank
FROM staff
ORDER BY dept, score DESC;How it works
What runs here is SELECT / INSERT / CREATE — staff are the objects involved.
Breaking the statements into their working parts: a window function (OVER (…)) computing values across rows without collapsing them; an ORDER BY that fixes the output order; NOT NULL qualifiers on the required columns.
What to watch for
- Remember the evaluation order:
WHEREfirst, window functions later — filtering on the latter needs another query level.
Putting it to use
The staff table is the working surface here.
Core lines
SELECT name, dept, score,
rank() OVER (PARTITION BY dept ORDER BY score DESC) AS dept_rank
FROM staff
ORDER BY dept, score DESC;
SELECT name, dept, score,
rank() OVER (ORDER BY score DESC) AS global_rank
FROM staff
ORDER BY score DESC;
INSERT INTO staff VALUES
('ada', 'dev', 92),
('raj', 'dev', 85),
('lin', 'ops', 90),
('kim', 'ops', 78);
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 objects does the SQL touch?
- The references are `staff`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.