Using LAG Function to Access Previous Row Data
📖 Scenario: You work for a small retail company that tracks daily sales. You want to compare each day's sales with the previous day's sales to see how sales change day by day.
🎯 Goal: Build a SQL query using the LAG function to retrieve the previous day's sales amount alongside the current day's sales.
📋 What You'll Learn
Create a table called
daily_sales with columns sale_date (date) and amount (integer).Insert exactly these rows into
daily_sales: ('2024-01-01', 100), ('2024-01-02', 150), ('2024-01-03', 120), ('2024-01-04', 130).Write a query selecting
sale_date, amount, and the previous day's amount using the LAG function.Order the results by
sale_date ascending.💡 Why This Matters
🌍 Real World
Retail companies often compare daily sales to previous days to understand trends and make decisions.
💼 Career
Knowing how to use window functions like LAG is important for data analysts and database developers to perform time-based comparisons.
Progress0 / 4 steps