Using ROW_NUMBER, RANK, and DENSE_RANK in PostgreSQL
📖 Scenario: You work for a company that wants to analyze sales data to see how salespeople rank based on their monthly sales.The company wants to assign ranks to salespeople to identify top performers, handle ties properly, and also assign unique row numbers for each salesperson.
🎯 Goal: Build a PostgreSQL query that uses ROW_NUMBER(), RANK(), and DENSE_RANK() window functions to rank salespeople by their sales amount in descending order.
📋 What You'll Learn
Create a table called
sales with columns salesperson (text) and sales_amount (integer).Insert the exact sales data provided into the
sales table.Write a query that selects all columns and adds three new columns:
row_num using ROW_NUMBER(), rank_num using RANK(), and dense_rank_num using DENSE_RANK(), all ordered by sales_amount descending.Ensure the query orders the final output by
sales_amount descending.💡 Why This Matters
🌍 Real World
Ranking salespeople or items by performance is common in business reports and dashboards to identify top performers and handle ties correctly.
💼 Career
Understanding and using window functions like ROW_NUMBER, RANK, and DENSE_RANK is essential for data analysts and database developers to create advanced queries for reporting and analytics.
Progress0 / 4 steps