Recall & Review
beginner
What does the LAG() function do in SQL?
LAG() lets you look at a value from a previous row in the same result set without using a self-join. It's like looking back one step in a list.
Click to reveal answer
beginner
How does the LEAD() function differ from LAG()?
LEAD() looks forward to the next row's value, while LAG() looks backward to the previous row's value. Both help compare rows easily.
Click to reveal answer
intermediate
What is a common use case for LAG and LEAD functions?
They are often used to compare current row values with previous or next rows, like finding changes over time or calculating differences between rows.
Click to reveal answer
intermediate
Write a simple SQL snippet using LAG() to get the previous month's sales for each row.
SELECT month, sales, LAG(sales) OVER (ORDER BY month) AS prev_month_sales FROM sales_data;
Click to reveal answer
beginner
What happens if there is no previous row when using LAG()?
LAG() returns NULL if there is no previous row to look at, so you can handle missing data gracefully.
Click to reveal answer
What does LEAD() function return?
✗ Incorrect
LEAD() returns the value from the next row in the result set.
Which clause is required to use LAG() or LEAD() functions?
✗ Incorrect
LAG() and LEAD() require an ORDER BY clause inside the OVER() to define row order.
If you want to compare each row with the row two steps before, which function and parameter do you use?
✗ Incorrect
LAG(column, 2) looks two rows back from the current row.
What value does LAG() return if there is no previous row?
✗ Incorrect
LAG() returns NULL when no previous row exists.
Which of these is NOT a use case for LAG and LEAD?
✗ Incorrect
LAG and LEAD work within the same result set, not for unrelated table lookups.
Explain how LAG and LEAD functions help compare rows in a table.
Think about looking backward and forward in a list.
You got /4 concepts.
Write a SQL query using LEAD() to find the next month's sales for each month in a sales table.
Use LEAD() with ORDER BY month inside OVER()
You got /4 concepts.