In the world of modern data-driven applications, the ability to extract insights from raw data is a vital skill. Microsoft SQL Server’s Transact-SQL (T-SQL) language offers a rich set of features that allow developers and data analysts to manipulate and query data with precision and efficiency. Among its most powerful constructs are Common Table Expressions (CTEs) and functions like `RANK()`, which together open the door to sophisticated analytical queries.
In this article, we’ll explore how T-SQL can be used to identify the top-N best-selling products within each product category in an e-commerce environment. This real-world use case is common in retail and business intelligence systems where stakeholders need quick insights into what products are driving sales across various categories.
Why T-SQL?
T-SQL is more than just a database querying language. It extends standard SQL with procedural programming capabilities, error handling, and transaction control, making it a powerful choice for both OLTP and OLAP systems. Its deep integration with Microsoft SQL Server means you can write complex logic directly within the database layer, reducing the overhead of data transfers and simplifying application design.
Understanding the RANK() Function
The RANK() function is a handy function that assigns a rank to each row within a result set partition, based on the ordering of one or more columns. Unlike `ROW_NUMBER()`, which assigns a unique sequential number to each row, `RANK()` allows ties—if two or more rows have the same values in the ORDER BY clause, they receive the same rank. However, it may also skips the subsequent rank(s).
Some Use cases include:
- Leaderboards
- Salary comparisons
- Top-N analysis per group
- Duplicate detection
Real-World Scenario: Top-N Best-Selling Products by Category
Let’s say you manage an online store and want to know the top 3 best-selling products in each category based on the total quantity sold. This helps your marketing team focus promotions and helps inventory planners stock up effectively.
To achieve this, we’ll use:
- A CTE to summarize total sales by product
- A RANK() function to rank products within each category
- A filter to extract only the top 3 products per category
Sample SQL Query
WITH ProductSales AS
( SELECT p.ProductID, p.ProductName, c.CategoryName, SUM(od.Quantity) AS TotalSold
FROM Products p
JOIN OrderDetails od ON p.ProductID = od.ProductID
JOIN Categories c ON p.CategoryID = c.CategoryID
GROUP BY p.ProductID, p.ProductName, c.CategoryName ),
RankedProducts AS (
SELECT *, RANK() OVER (PARTITION BY CategoryName ORDER BY TotalSold DESC) AS RankInCategory
FROM ProductSales )
SELECT * FROM RankedProducts WHERE RankInCategory <= 3;
Sample Data
Products Table

Categories Table

OrderDetails Table

Breakdown of the Query
- ProductSales CTE: Aggregates total quantity sold (`SUM(od.Quantity)`) per product, along with its name and category.
- RankedProducts CTE: Applies `RANK()` to each product within its category (`PARTITION BY CategoryName`) based on descending order of `TotalSold`.
- Final SELECT: Filters to only return products with `RankInCategory` less than or equal to 3.
Sample Output (Illustrative)

Benefits of This Approach
- Clarity: The use of CTEs makes the query modular and easy to understand.
- Scalability: Works efficiently on large datasets using SQL Server’s optimized execution engine.
- Customizability: You can easily adjust the N-value (e.g., top 5, top 10) or add more filtering (e.g., by date range or region).
T-SQL, with tools like `RANK()` and CTEs, empowers developers to write expressive and powerful queries that solve real business problems. In the context of e-commerce, this approach helps highlight top-performing products, offering a data-driven foundation for strategic decisions in sales, marketing, and supply chain management.