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.

SqlData Fetching

Code

snippet
-- 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: WHERE first, 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

FAQ

Which objects does the SQL touch?
The references are `staff`.