Interview Q&A / SQL & DBMS

IntermediateQuick answer1 min readUpdated 3 Oct 2026

What do LAG and LEAD do in SQL?

SHORT ANSWER

LAG returns a value from a previous row and LEAD from a following row, within the window order. They compare a row to its neighbour without a self join.

Explain it simply

Looking at a daily petrol price list, LAG lets you glance at the previous line to see yesterday's price, and LEAD lets you peek at the next line. Neither needs you to build a second copy of the table.

Example

Table fuel(day, price) with prices 100, 102, 101 on days 1 to 3.

sql
SELECT day, price,
       LAG(price)  OVER (ORDER BY day) AS prev_price,
       LEAD(price) OVER (ORDER BY day) AS next_price,
       price - LAG(price) OVER (ORDER BY day) AS change
FROM fuel;
daypriceprev_pricenext_pricechange
1100NULL102NULL
21021001012
3101102NULL-1
  • The first row has no previous row, so LAG gives NULL. LEAD on the last row is also NULL.
  • Optional arguments: LAG(price, 2, 0) looks two rows back and returns 0 instead of NULL when there is no such row.
  • Add PARTITION BY to restart per group, for example per product.

What to say in the interview

"LAG and LEAD fetch a value from a row at a given offset before or after the current row in the window order. They replace self joins for day-over-day or month-over-month comparisons."

Common mistakes

  • Omitting ORDER BY in OVER, which makes the previous row meaningless.

#sql#window-functions#lag#lead

Related questions

Practise more SQL & DBMS questions

Test your recall with short answers, then return to the detailed explanations when you need context.

Open SQL & DBMS quick answers →

Get new questions like this by email

One short email when something new and useful lands. No spam, unsubscribe in one tap.

By subscribing you agree to the Privacy Policy.