Assigning Row Numbers with ROW_NUMBER() in MySQL
📖 Scenario: You work at a bookstore that keeps track of book sales. Each sale record includes the book title, the sale date, and the number of copies sold. You want to assign a unique row number to each sale ordered by the sale date to identify the sequence of sales.
🎯 Goal: Build a SQL query that uses the ROW_NUMBER() window function to assign a row number to each sale ordered by sale_date.
📋 What You'll Learn
Create a table called
book_sales with columns id, book_title, sale_date, and copies_sold.Insert exactly 5 rows into
book_sales with specified values.Write a query that selects all columns and adds a
row_num column using ROW_NUMBER() ordered by sale_date ascending.Ensure the final query includes the
row_num column.💡 Why This Matters
🌍 Real World
Assigning row numbers helps in ranking or ordering records in reports, such as sales sequences or event logs.
💼 Career
Understanding window functions like ROW_NUMBER() is essential for data analysts and database developers to write advanced queries for business insights.
Progress0 / 4 steps