ℹ️ Select 'Choose Exercise', or randomize 'Next Random Exercise' in selected language.

Choose Exercise:
Timer 00:00
WPM --
Score --
Acc --
Correct chars --

Top-N Query with Window Functions

SQL MySQL

Goal -- WPM

Ready
Exercise Algorithm Area
1WITH RankedProducts AS (
2SELECT
3product_id,
4category,
5product_name,
6price,
7ROW_NUMBER() OVER (
8PARTITION BY category
9ORDER BY price DESC
10) as rn
11FROM
12products
13)
14SELECT
15product_id,
16category,
17product_name,
18price
19FROM
20RankedProducts
21WHERE
22rn <= 3;
23
24-- Explanation:
25-- 1. The Common Table Expression (CTE) `RankedProducts` assigns a rank to each product within its category.
26-- 2. `PARTITION BY category` ensures that ranking restarts for each distinct category.
27-- 3. `ORDER BY price DESC` ranks products from highest price to lowest within each category.
28-- 4. `ROW_NUMBER()` assigns a unique sequential integer to each row within its partition.
29-- 5. The outer query then selects products where the assigned rank (`rn`) is 3 or less,
30-- effectively giving us the top 3 most expensive products per category.
31
32-- Edge Case:
33-- If a category has fewer than 3 products, all products in that category will be returned
34-- (as their ranks will be 1, 2, etc., all <= 3).
35-- If multiple products share the same highest price in a category, `ROW_NUMBER()` will assign them distinct ranks arbitrarily.
36-- If you need to include all products tied for the Nth position, use `RANK()` or `DENSE_RANK()` instead of `ROW_NUMBER()`.
Algorithm description viewbox

Top-N Query with Window Functions

Algorithm description:

This scenario focuses on implementing a Top-N query in MySQL using window functions. It involves ranking products within each category based on their price and then selecting the top N (in this case, 3) products from each category. Top-N queries are common for leaderboards, recommendations, and identifying top performers in various domains.

Algorithm explanation:

The query uses a Common Table Expression (CTE) named `RankedProducts` to first rank products. The `ROW_NUMBER()` window function is applied, partitioning the data by `category` and ordering it by `price` in descending order. This assigns a unique rank to each product within its category, with the highest price getting rank 1. The outer query then filters these ranked products, selecting only those where the rank (`rn`) is less than or equal to 3. If a category has fewer than 3 products, all of them will be included. Using `RANK()` or `DENSE_RANK()` instead of `ROW_NUMBER()` would handle ties differently, including all products tied for the Nth position. The time complexity is dominated by the sorting within the window function, typically O(N log N), where N is the total number of products. Space complexity is O(N) for the CTE.

Pseudocode:

1. Define a CTE named `RankedProducts`.
2. Select product details: `product_id`, `category`, `product_name`, `price`.
3. Assign a rank using `ROW_NUMBER()` OVER (PARTITION BY category ORDER BY price DESC).
4. Alias the rank as `rn`.
5. Select from `RankedProducts`.
6. Filter the results where `rn` is less than or equal to 3.