Interview Question

What is LAG()?

LAG reads a value from an earlier ordered row.

💡 Concept ✅ Quick Revision 🗃️ SQL

Answer

LAG returns a value from an earlier row in the window ordering. • An offset chooses how many rows back to read. • A default can be supplied when no earlier row exists. • It is useful for change calculations and previous-row comparisons.

💡 SQL Example

SELECT ordered_at, amount, LAG(amount) OVER (ORDER BY ordered_at) AS previous_amount FROM payments;

Result

Each payment with the previous payment amount

⚡ Quick Revision

LAG reads a value from an earlier ordered row.