SQL
All Top 50 SQL Interview Questions#43
Top N Records Per Group Using PARTITION BY in SQL
MediumFlipkartInterview Question #43
Asked at FlipkartGiven `products` (product_id, category, sales_volume), write a SQL query to select the top 3 products with the highest sales volume in each category.
Input Table: products
5 rows preview| product_id | category | sales_volume |
|---|---|---|
| 1 | Laptops | 500 |
| 2 | Laptops | 450 |
| 3 | Laptops | 400 |
| 4 | Laptops | 300 |
| 5 | Phones | 900 |
Expected Output Structure4 rows
| category | product_id | sales_volume | category_rank |
|---|---|---|---|
| Laptops | 1 | 500 | 1 |
| Laptops | 2 | 450 | 2 |
| Laptops | 3 | 400 | 3 |
| Phones | 5 | 900 | 1 |
Interview Context
Asked frequently in data analyst and business analyst technical rounds. Focus on clean filtering, optimal indexing usage, and unambiguous column selection.
PostgreSQL 15
Ready to execute
Click "Run Query" or press Ctrl + Enter to test your query.
Output will be verified against the test dataset.