SQL-Engineering-Handbook

LAG() and LEAD()

LAG and LEAD diagram showing access to previous and next row values

Overview

LAG() looks backward to a previous row; LEAD() looks forward to a following row – both relative to the current row’s position in the window’s ORDER BY sequence. They are the foundation of every period-over-period comparison in analytics SQL.

Learning Objectives

Prerequisites

Syntax

SELECT
    column_a,
    LAG(column_b, offset, default_value)  OVER (ORDER BY sort_column) AS prev_value,
    LEAD(column_b, offset, default_value) OVER (ORDER BY sort_column) AS next_value
FROM table_name;

offset defaults to 1 (one row back/forward); default_value defaults to NULL for rows with no previous/next row.

Dataset Used

employes

Examples

See 05_lag_lead.sql.

Real World Applications

Business Use Cases

Domain Scenario
Finance Month-over-month revenue growth
Retail Previous day’s sales for a trend chart
Banking Stock/asset price change tracking
Marketing Customer activity gap detection

Common Mistakes

Best Practices

Engineering Notes

LAG()/LEAD() are evaluated in the same single sorted pass as other window functions – no self-join is required, which is significantly faster and more readable than the older JOIN table AS t1 ON t1.id = t2.id - 1 pattern.

Practice Questions

  1. Show the previous employee id using LAG().
  2. Show the next employee id using LEAD().
  3. Show the current employee and the previous employee’s name.
  4. Show the current employee and the next employee’s name.
  5. Show the difference between the current emp_id and the previous emp_id (and repeat using a 2-row offset).

Difficulty

Intermediate

Estimated Time

25 minutes

Learning Outcomes

Next Topic

06_FIRST_LAST_NTILE


Lesson Navigation

← Previous: 04_PARTITION_BYModule README → Next: 06_FIRST_LAST_NTILE