11. Top three products per category, ties included

SQLEasyTie trap

top n per group · rank · dense_rank · row_number · window functions

How the Colab notebook works

The notebook has the data, an answer cell and a check() function. You need a Google account; nothing is installed on your machine. Free Colab runs only two or three notebooks at a time, so end the session of a finished problem (Runtime > Disconnect and delete runtime) before opening the next one. "Mark as solved" is remembered in this browser only.

The situation

The merchandising team wants a "top three sellers" list for each product category. Two products with the same number of units sold are equally good, so neither may be dropped just because the list is "full".

Input tables

product_sales

One row per product.

Column Type Description
product_id BIGINT Unique per product.
category STRING The product's category.
product_name STRING Display name.
units_sold BIGINT Units sold this quarter. NULL means no sales were recorded for the product.

Requirement

Return the top three products of every category by units_sold.

  • The best-selling product of a category has sales_rank 1.
  • Products with the same units_sold share the same rank. The next lower value gets the rank it would have had without the tie: after two products tied at rank 2, the next product is rank 4, not 3.
  • Keep every product whose sales_rank is 3 or less. That can be more than three products when there is a tie, and fewer when the category is small.
  • Products with a NULL units_sold are not ranked and do not appear.

Expected output

One row per product that makes the list.

Column Type Description
category STRING
product_id BIGINT
product_name STRING
units_sold BIGINT
sales_rank INT 1, 2 or 3.

Solve it in the browser

This editor runs DuckDB inside your browser. Nothing is installed and nothing is sent to a server. DuckDB's SQL is close to Spark SQL but not identical. The Colab notebook runs real Spark.

query.sql DuckDB, in your browser
Ctrl + Enter runs the query

Your result appears here. Your draft is kept in this browser.

Explanation

Show explanationGives the answer away. Try the problem first.

The approach

"Top N per group" is a window function problem: number the rows inside each group, then keep the low numbers. SQL has three numbering functions, and the whole problem is choosing the right one. On the values 520, 480, 480, 455 they give:

units_sold ROW_NUMBER() RANK() DENSE_RANK()
520 1 1 1
480 2 2 2
480 3 2 2
455 4 4 3
  • ROW_NUMBER() never repeats a number. Tied rows get different numbers, in an order you did not choose.
  • RANK() gives tied rows the same number and then skips: after two rows at 2, the next is 4. This is how a sports table works.
  • DENSE_RANK() gives tied rows the same number and does not skip: the next is 3.

The requirement says the product after a two-way tie at rank 2 is rank 4. That is RANK().

SELECT category, product_id, product_name, units_sold, sales_rank
FROM (
    SELECT
        category, product_id, product_name, units_sold,
        RANK() OVER (PARTITION BY category ORDER BY units_sold DESC) AS sales_rank
    FROM product_sales
    WHERE units_sold IS NOT NULL
) ranked
WHERE sales_rank <= 3

Two details:

  • The rank cannot be filtered in the same SELECT that computes it. Window functions run after WHERE, so the filter goes in an outer query.
  • Products with a NULL units_sold are removed before ranking. If they are left in, they still get a rank, and in small categories that rank is 3 or less.

The table has 56 products in 11 categories. The correct result has 33 rows.

Common wrong answers

ROW_NUMBER(). Returns 29 rows: exactly three per category, two for the category with two products. In "Phones" two products tie for third place with 610 units, and ROW_NUMBER() keeps one of them. Which one is not defined, so the result can change between runs. Any time a ranking can have ties, ROW_NUMBER() needs a reason.

DENSE_RANK(). Returns 36 rows. It does not skip after a tie, so a fourth and fifth product slip in: "Laptops" (520, 480, 480, 455) gets four rows because 455 is dense rank 3, "Tablets" gets four and "Monitors" gets five. DENSE_RANK() answers a different question: the products with the three highest sales figures.

Forgetting the NULL filter. Returns 35 rows. "Printers" has two products and both have NULL sales; they tie at rank 1 and both appear. In a larger category the NULLs would simply rank last and go unnoticed, which is why this one is easy to miss in testing.

ORDER BY units_sold DESC LIMIT 3. Three rows in total, not three per category.

Edge cases in the data

Case Category What it catches
Two-way tie for 2nd, then a 4th value Laptops DENSE_RANK() lets the 4th product in.
Tie exactly at the cut-off Phones ROW_NUMBER() drops one of two equal products.
Tie for 1st Tablets DENSE_RANK() again: ranks 1, 1, 2, 3 instead of 1, 1, 3, 4.
Three-way tie for 2nd Monitors Four rows with RANK(), three with ROW_NUMBER(), five with DENSE_RANK().
Every product tied Cameras All five are rank 1.
Fewer than three products Audio Assuming every category returns three rows.
Products with NULL sales Wearables, Printers Ranking NULLs instead of removing them.