Lesson Description
Look at the row before/after; accumulate values.
Lesson 2 of 4
Progress: 0/3 exercises solved (0%)
Solve all exercises below to unlock the next lesson.
Lesson Description
Look at the row before/after; accumulate values.
Easy Project
Mini project: Turn this lesson into a real-world query artifact by writing one clean business report query and validating output quality.
These window functions look at neighboring rows or accumulate values over an ordered sequence.
LAG(col, n, default) returns the value of col from n rows before the current row:
SELECT
first_name,
hire_date,
salary,
LAG(salary) OVER (ORDER BY hire_date) AS prev_hire_salary,
salary - LAG(salary) OVER (ORDER BY hire_date) AS salary_diff
FROM employees
ORDER BY hire_date;
LEAD(col, n, default) returns the value from n rows ahead:
SELECT
order_date,
id AS order_id,
LEAD(order_date) OVER (ORDER BY order_date, id) AS next_order_date
FROM orders;
The third argument sets the value when no prior/next row exists (default is NULL):
LAG(salary, 1, 0) OVER (ORDER BY hire_date) -- returns 0 for the first row
SELECT
order_date,
id,
COUNT(*) OVER (ORDER BY order_date, id) AS running_count
FROM orders
ORDER BY order_date, id;
SELECT
hire_date,
salary,
SUM(salary) OVER (ORDER BY hire_date, id) AS cumulative_payroll
FROM employees
ORDER BY hire_date;
PARTITION BY resets the running total at the start of each group.PARTITION BY looks at neighbors within the partition only.LAG(value, 12) for monthly year-over-year.This lesson is part of Window Functions. Focus on the core idea in LAG, LEAD, and running totals, then validate with deliberate practice.
What to master
Common mistakes
High-level strategy
Task ladder
Transparent data checks
Retention loop
Logical reasoning for commands
WHERE
Why: Limits rows to only the business-relevant subset.
Memory cue: Filter early to reduce noise.
ORDER BY
Why: Makes output deterministic and reviewable.
Memory cue: No ORDER BY means no guaranteed row order.
AS alias
Why: Makes output columns readable for teams and reports.
Memory cue: If the name is clear, the query is easier to trust.
Concept check
3 quick questions. One at a time. Instant score at the end.
From the store sandbox, return one row per order with order_date, id (order_id), and a running_orders column showing the cumulative count of orders up to and including that date, ordered by order_date then id.
Return first_name, last_name, hire_date, salary, and salary_diff — the difference between this employee's salary and the previous hire's salary (ordered by hire_date, then id). Use LAG.
From the store sandbox, return id (alias order_id), order_date, and next_order_date (the date of the following order when sorted by order_date, id). Use LEAD.
Lesson 2 of 4
0/3 solved (0%)
Finish this lesson to unlock next.