Search RU
Tasks / SQL / Top product per category
Statement medium

Top product per category

For every category, find the product with the highest revenue. Each category
must appear exactly once.

Result columns: `category`, `name`, `revenue`.

If several products in a category share the top revenue, pick the one with the
smaller `name` (ascending). Sort the result by `category` ascending.

SQL · PostgreSQL
sqlwindow-functionsrow-numbercte
Schema
CREATE TABLE products (
    id integer PRIMARY KEY,
    category text NOT NULL,
    name text NOT NULL,
    revenue integer NOT NULL
);
Data
INSERT INTO products (id, category, name, revenue) VALUES
    (1, 'books', 'Alpha Guide', 15000),
    (2, 'books', 'Beta Guide', 15000),
    (3, 'books', 'Gamma Guide', 9000),
    (4, 'games', 'Dice Set', 22000),
    (5, 'games', 'Board Pro', 18000),
    (6, 'tools', 'Hammer', 5000),
    (7, 'tools', 'Wrench', 5000),
    (8, 'tools', 'Saw', 5000);
query.sql PostgreSQL 17
AI mentor

The AI mentor is available after you log in: it sees your attempt history and does not spend resources on anonymous requests.

Log in and ask
Hints 1 of 3 unlocked · attempts: 0
Hint 1

Compare products within a category, not across the whole table. That calls for
a window function with `PARTITION BY category`.

Hint 2 — unlocks after 1 attempt
Hint 3 — unlocks after 3 attempts