LEAD vs LAG in SQL (Track Changes Like a Pro)
After mastering ranking functions, the next must-know SQL window functions for analytics and interviews are
π LEAD() and LAG().
These functions help you compare a row with its previous or next rowβa very common requirement in time-series analysis, reporting, and analytics.
π§ Problem Statement
π Given employee salaries ordered by year, find the salary change compared to the previous year.
Sample data:
| year | salary |
|---|---|
| 2021 | 70,000 |
| 2022 | 80,000 |
| 2023 | 90,000 |
π Using LAG() (Previous Row)
SELECT year,
salary,
LAG(salary) OVER (ORDER BY year) AS prev_salary
FROM employee_salary;
π Output Explanation
LAG()fetches the value from the previous row- First row returns
NULL(no previous record)
Result logic:
- 2021 β NULL
- 2022 β 70,000
- 2023 β 80,000
β Calculate Salary Increment (Real Use Case)
SELECT year,
salary,
salary - LAG(salary) OVER (ORDER BY year) AS salary_increment
FROM employee_salary;
β Commonly used in:
- Year-over-year growth
- Revenue comparison
- Trend analysis
π Using LEAD() (Next Row)
SELECT year,
salary,
LEAD(salary) OVER (ORDER BY year) AS next_salary
FROM employee_salary;
π What LEAD() Does
- Fetches the next rowβs value
- Last row returns
NULL
Useful for:
- Forecast comparisons
- Finding upcoming changes
- Session analysis
π LEAD vs LAG (Quick Comparison)
| Function | Looks at | Typical use |
|---|---|---|
| LAG() | Previous row | Growth, decline, trends |
| LEAD() | Next row | Forecasting, next-step analysis |
π‘ Interview Tip
π If a problem mentions:
- Previous value β think LAG()
- Next value β think LEAD()
These functions avoid self-joins, making queries:
- Cleaner
- Faster
- Easier to read
π¬ Interview Question for You
How would you find consecutive login days for users using LAG()?
Think gaps, dates, and window functions π
Comments (0)
No comments yet. Be the first to share your thoughts!
Leave a Comment