← All Exercises

Top Two Products per Category with DENSE_RANK

intermediatesql~20min

Background

Category pages often highlight premium products. Price ties must not be broken arbitrarily, so dense ranking fits better than taking a fixed number of rows per group.

Problem

Given a products table, return the two most expensive distinct prices per category. If several products share a top price, include all of them, so a category may return more than two rows.

Input

A PostgreSQL products table with id integer PRIMARY KEY, category text NOT NULL, name text NOT NULL, and price numeric(10,2) NOT NULL.

Output

Rows with category, name, price, and price_rank limited to 1 or 2, ordered by category, price_rank, then name.

Sample tests

Sample 1

Input: Electronics: TV 1500, Phone 900, Phone Mini 900, Cable 10; Books: Novel 20, Guide 15, Map 10
Expected: Books | Novel | 20.00 | 1
Books | Guide | 15.00 | 2
Electronics | TV | 1500.00 | 1
Electronics | Phone | 900.00 | 2
Electronics | Phone Mini | 900.00 | 2

Sample 2

Input: a separate dataset containing only Garden: Rake 25
Expected: Garden | Rake | 25.00 | 1

Your solution

Learning objective

Use DENSE_RANK for top-N-per-group queries, preserve price ties, and filter a window result through a CTE.