LEAD And LAG — SQL Technical Interview Questions & Answers

LEAD And LAG

LEAD And LAG

  • Window functions compute across related rows without collapsing them. ROW_NUMBER() OVER (ORDER BY marks DESC) ranks students but keeps every row. GROUP BY would squash them.
  • MySQL 8+: ROW_NUMBER, RANK, DENSE_RANK, SUM() OVER (PARTITION BY city). PARTITION BY is ‘GROUP BY that doesn’t hide rows’.
  • Trap: window functions on 5.7. Trap: using GROUP BY when you still needed each student row plus a rank.
  • On the example next to this theory: LEAD And LAG — wHERE combines predicates with AND/OR; LIKE does pattern match.

Technical Interview Tip: ROW_NUMBER() OVER (ORDER BY marks DESC) AS rank

Code Examples for LEAD And LAG

LEAD And LAG — sample query

CREATE TABLE products (id INTEGER PRIMARY KEY, name TEXT, price REAL);
INSERT INTO products VALUES (1, 'Pen', 10), (2, 'Book', 200), (3, 'Bag', 50);
SELECT * FROM products
WHERE price BETWEEN 20 AND 150 AND name LIKE 'B%';

LEAD And LAG — wHERE combines predicates with AND/OR; LIKE does pattern match.

How to Explain LEAD And LAG to an Interviewer

Window vs GROUP BY?

Window keeps rows GROUP BY collapses them