Using LAG and LEAD for Row Comparison in PostgreSQL
📖 Scenario: You work for a retail company that tracks daily sales. You want to compare each day's sales with the previous and next day to see trends.
🎯 Goal: Create a SQL query that uses LAG and LEAD functions to compare each day's sales with the previous and next day.
📋 What You'll Learn
Create a table called
daily_sales with columns sale_date (date) and amount (integer).Insert the exact sales data for five consecutive days.
Write a query that selects
sale_date, amount, previous day's amount using LAG, and next day's amount using LEAD.Order the results by
sale_date ascending.💡 Why This Matters
🌍 Real World
Retail and sales analysts often compare daily or periodic sales to understand trends and make decisions.
💼 Career
Knowing how to use LAG and LEAD functions is valuable for data analysts and database developers to perform time-based comparisons efficiently.
Progress0 / 4 steps