What if you could instantly see yesterday's data next to today's without flipping pages or writing notes?
Why LAG function for previous row access in SQL? - Purpose & Use Cases
Imagine you have a list of daily sales numbers on paper, and you want to compare each day's sales to the previous day. You try to do this by flipping back and forth between pages or writing down extra notes to remember the previous day's number.
This manual way is slow and confusing. You might lose track of which day you are on, make mistakes copying numbers, or waste time flipping pages. It's hard to keep everything organized and accurate.
The LAG function in SQL lets you look at the previous row's value easily, right next to the current row. It automatically remembers the previous data for you, so you can compare or calculate differences without any extra effort.
SELECT date, sales FROM daily_sales;
-- Then manually compare each row with the previous one outside SQLSELECT date, sales, LAG(sales) OVER (ORDER BY date) AS previous_day_sales FROM daily_sales;
It makes comparing current and past data simple and fast, unlocking powerful trend analysis and insights.
A store manager can quickly see how today's sales compare to yesterday's, helping decide if a promotion worked or if changes are needed.
Manually tracking previous rows is slow and error-prone.
LAG function automatically accesses previous row data in SQL.
This enables easy comparisons and better data insights.
Practice
LAG function do?Solution
Step 1: Understand the purpose of LAG
The LAG function is used to access data from a previous row relative to the current row in a query result.Step 2: Compare options with definition
Returns the value from the previous row in the result set correctly states that LAG returns the previous row's value. Other options describe different functions or behaviors.Final Answer:
Returns the value from the previous row in the result set -> Option CQuick Check:
LAG = previous row value [OK]
- Confusing LAG with LEAD (next row)
- Thinking LAG sums values
- Assuming LAG filters rows
LAG to get the previous salary ordered by employee ID?Solution
Step 1: Recall LAG syntax
LAG requires an OVER clause with ORDER BY to define the row order for previous row access.Step 2: Match syntax with options
LAG(salary) OVER (ORDER BY employee_id) correctly uses OVER (ORDER BY employee_id). The other options misuse syntax or keywords.Final Answer:
LAG(salary) OVER (ORDER BY employee_id) -> Option AQuick Check:
LAG syntax = LAG() OVER (ORDER BY ...) [OK]
- Omitting OVER clause
- Using PARTITION BY without ORDER BY
- Incorrect keyword order
Employees with columns id and salary, what will this query return?SELECT id, salary, LAG(salary) OVER (ORDER BY id) AS prev_salary FROM Employees;
Assuming data:
id | salary
1 | 5000
2 | 6000
3 | 5500Solution
Step 1: Understand LAG with ORDER BY id
LAG(salary) returns the salary from the previous row ordered by id. For id=1, no previous row exists, so NULL is returned.Step 2: Apply LAG to each row
Row 1: prev_salary = NULL
Row 2: prev_salary = salary of id=1 = 5000
Row 3: prev_salary = salary of id=2 = 6000Final Answer:
[{id:1, salary:5000, prev_salary:NULL}, {id:2, salary:6000, prev_salary:5000}, {id:3, salary:5500, prev_salary:6000}] -> Option AQuick Check:
LAG returns previous row's value or NULL if none [OK]
- Assuming first row has previous value
- Mixing up current and previous rows
- Ignoring ORDER BY effect
SELECT id, salary, LAG(salary) ORDER BY id AS prev_salary FROM Employees;
Solution
Step 1: Check LAG function syntax
LAG requires an OVER() clause to specify ordering. The query uses ORDER BY without OVER(), which is invalid.Step 2: Confirm correct syntax
The correct syntax is LAG(salary) OVER (ORDER BY id). The query misses OVER(), causing a syntax error.Final Answer:
Missing OVER() clause for LAG function -> Option DQuick Check:
LAG needs OVER() with ORDER BY [OK]
- Using ORDER BY without OVER()
- Placing alias before function
- Misunderstanding LAG usage
id. Which query correctly calculates this difference?Solution
Step 1: Understand the goal
We want to subtract the previous salary from the current salary, ordered by id.Step 2: Check each option's correctness
SELECT id, salary, salary - LAG(salary) OVER (ORDER BY id) AS diff FROM Employees; correctly uses LAG(salary) OVER (ORDER BY id) and subtracts it from salary.
SELECT id, salary, LAG(salary) - salary OVER (ORDER BY id) AS diff FROM Employees; reverses subtraction order.
SELECT id, salary, salary - LAG(salary) FROM Employees ORDER BY id; misses OVER clause.
SELECT id, salary, salary - LAG(salary) PARTITION BY id AS diff FROM Employees; misuses PARTITION BY without OVER.Final Answer:
SELECT id, salary, salary - LAG(salary) OVER (ORDER BY id) AS diff FROM Employees; -> Option BQuick Check:
Difference = current - previous salary using LAG [OK]
- Forgetting OVER() clause
- Subtracting in wrong order
- Misusing PARTITION BY without OVER
Ready to prove it?
Pass the test and this pattern moves unknown
