0
0
SQLquery~5 mins

LAG function for previous row access in SQL - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What does the LAG function do in SQL?
The LAG function lets you look at the value from a previous row in the same result set without using a self-join. It helps compare current row data with previous row data easily.
Click to reveal answer
beginner
Write the basic syntax of the LAG function.
LAG(column_name, offset, default_value) OVER (PARTITION BY partition_column ORDER BY order_column) Here, offset is how many rows back to look (default 1), and default_value is what to return if no previous row exists.
Click to reveal answer
intermediate
Why do we use the OVER clause with LAG?
The OVER clause defines how to group and order rows for the LAG function. It tells SQL which rows to compare and in what order, so it knows which previous row to look at.
Click to reveal answer
beginner
What happens if there is no previous row when using LAG?
If there is no previous row, LAG returns NULL by default or the specified default value if provided. This prevents errors and lets you handle edge cases.
Click to reveal answer
beginner
Give a real-life example where LAG is useful.
LAG is useful to compare sales of a product this month with last month. For example, you can find the difference in sales between current and previous month to see growth or decline.
Click to reveal answer
What does the LAG function return by default if there is no previous row?
ANULL
B0
CAn error
DThe current row value
Which clause is required to specify the order of rows for the LAG function?
AGROUP BY
BORDER BY inside OVER()
CWHERE
DHAVING
What is the default offset value for LAG if not specified?
A0
B2
C1
DNULL
Which of these is a valid use of LAG?
ATo get the previous row's value
BTo filter rows
CTo sum all rows
DTo get the next row's value
Can LAG be used without the OVER() clause?
AOnly with GROUP BY
BYes, always
COnly in MySQL
DNo, OVER() is required
Explain how the LAG function works and why it is useful.
Think about comparing current data with past data in a list.
You got /4 concepts.
    Describe the syntax of the LAG function and the role of each part.
    Break down the function into its parameters and the window definition.
    You got /4 concepts.