Ranking Functions
Explore how to accurately retrieve the top two products by revenue within each category using SQL ranking functions. Understand the differences between ROW_NUMBER, RANK, and DENSE_RANK, and learn how to handle ties, apply deterministic ordering, and correctly filter results by staging ranked outputs in queries.
The interviewer asks, “For each product category, return the two products with the highest revenue during the previous calendar week.” The result must contain one row for each selected product within its category, with up to two products per category. Grouping only by category calculates total revenue per category but does not provide the product-level revenue needed to rank individual products.
The synthetic orders(order_id, product_id, category, revenue, order_date) table contains multiple orders per product, so the first stage aggregates revenue at the category and product_id grain. We then need a window function, a calculation that examines related result rows while preserving each row. OVER (...) defines the rows available to that calculation. PARTITION BY category creates a partition, the separate set of product rows ranked within each category.
The ranking order must use total product revenue descending. When two products have the same revenue, the business request must tell us whether two rows are enough or whether every tied product belongs in the result.
Lines 23–41: The inserted data is shaped so that multiple order-grain rows roll up to one product row, and at least one category has a product-level revenue tie (e.g.,
bookshas two products at100) soRANK()vsDENSE_RANK()differences are visible.Lines 49–58: Revenue is first aggregated at the required output grain for ranking (
category × product_id) before any window function runs....