Skip to main content
InterviewHubPRO
Section Overview
Q15

Question 15 of 50

Part 2: Core Architecture & Implementation (Mid-Level)

30%
SQL & Relational Databases (50 Qs)•Part 2: Core Architecture & Implementation (Mid-Level)

What are `LEAD()` and `LAG()` window functions used for?

senior LevelCode ExampleSystem Design

In Simple Words: Allows accessing data from preceding or succeeding rows without self-joins:

  • LAG(col, N): Accesses value from $N$ rows before the current row (e.g. comparing today's revenue against yesterday's revenue).
  • LEAD(col, N): Accesses value from $N$ rows after the current row (e.g. calculating duration until next user click event).
sql
SELECT
  order_date,
  revenue,
  revenue - LAG(revenue, 1) OVER (ORDER BY order_date) AS day_over_day_change
FROM daily_sales;