Hard sql

PostgreSQL ROW_NUMBER ranking

Problem

Rank employees by salary within each department using window functions.

Hints
  • ROW_NUMBER() OVER (PARTITION BY ... ORDER BY ...)

Your practice code

Ready — edit the code above and click Run.

Solution

-- PostgreSQL schema
CREATE TABLE employees (id SERIAL PRIMARY KEY, name TEXT, dept_id INT, salary NUMERIC(10,2));
CREATE TABLE departments (id SERIAL PRIMARY KEY, name TEXT);
INSERT INTO employees (name, dept_id, salary) VALUES ('Ali',1,90000),('Sara',2,120000);
INSERT INTO departments (name) VALUES ('Engineering'),('Sales');
SELECT name, salary, dept_id,
       ROW_NUMBER() OVER (PARTITION BY dept_id ORDER BY salary DESC) AS rn
FROM employees;

Try solving on your own first, then reveal the official answer.

Explanation

Window functions: PARTITION BY groups, ORDER BY ranks within group.

Toolliyo Assistant
Ask about tutorials, ebooks, training, pricing, mentor services, and support. I use public site content only—not admin or internal tools.

care@toolliyo.com

Need callback? Share your details