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 πŸ‘€