0
0
PostgreSQLquery~5 mins

LAG and LEAD for row comparison in PostgreSQL - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
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?
AValue from the previous row
BCurrent row value
CSum of all rows
DValue from the next row
Which clause is required to use LAG() or LEAD() functions?
AORDER BY inside OVER()
BWHERE
CGROUP BY
DHAVING
If you want to compare each row with the row two steps before, which function and parameter do you use?
ALEAD(column, 1)
BLEAD(column, 2)
CLAG(column, 2)
DLAG(column, 1)
What value does LAG() return if there is no previous row?
A0
BNULL
CEmpty string
DError
Which of these is NOT a use case for LAG and LEAD?
ALooking up values in unrelated tables
BCalculating running totals
CFinding differences between rows
DComparing current row with previous or next row
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.