Challenge - 5 Problems
LEAD Function Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ query_result
intermediate2:00remaining
Output of LEAD function with default offset
Given the table Sales with columns
id and amount, what is the output of this query?SELECT id, amount, LEAD(amount) OVER (ORDER BY id) AS next_amount FROM Sales ORDER BY id;
SQL
CREATE TABLE Sales (id INT, amount INT); INSERT INTO Sales VALUES (1, 100), (2, 200), (3, 300);
Attempts:
2 left
💡 Hint
LEAD returns the value of the next row in the order specified.
✗ Incorrect
The LEAD function with default offset 1 returns the amount from the next row ordered by id. For the last row, there is no next row, so it returns null.
❓ query_result
intermediate2:00remaining
LEAD function with offset 2
What is the output of this query on the same Sales table?
SELECT id, amount, LEAD(amount, 2) OVER (ORDER BY id) AS next_2_amount FROM Sales ORDER BY id;
SQL
CREATE TABLE Sales (id INT, amount INT); INSERT INTO Sales VALUES (1, 100), (2, 200), (3, 300), (4, 400);
Attempts:
2 left
💡 Hint
Offset 2 means skipping one row and looking two rows ahead.
✗ Incorrect
LEAD(amount, 2) returns the amount value two rows after the current row ordered by id. Rows without a second next row return null.
📝 Syntax
advanced2:00remaining
Identify the syntax error in LEAD usage
Which option contains a syntax error when using the LEAD function?
Attempts:
2 left
💡 Hint
Check the placement of parentheses and commas in LEAD function.
✗ Incorrect
Option C is missing a comma between the first argument and the ORDER BY clause inside LEAD, which is invalid syntax. LEAD requires the ORDER BY clause in the OVER() clause, not inside the function arguments.
❓ optimization
advanced2:00remaining
Optimizing LEAD usage with partitioning
Given a Sales table with columns
region, id, and amount, which query correctly uses LEAD to get the next amount within each region?Attempts:
2 left
💡 Hint
Partitioning groups rows before applying LEAD.
✗ Incorrect
Option A partitions rows by region, so LEAD returns the next amount within the same region ordered by id. Option A ignores regions, C partitions incorrectly, and D misuses aggregation.
🧠 Conceptual
expert2:00remaining
Understanding LEAD with default value
What will be the output of the
Assuming the last row has
next_amount column for the last row in this query?SELECT id, amount, LEAD(amount, 1, 999) OVER (ORDER BY id) AS next_amount FROM Sales ORDER BY id;
Assuming the last row has
id = 4 and amount = 400.Attempts:
2 left
💡 Hint
The third argument in LEAD is the default value if no next row exists.
✗ Incorrect
LEAD(amount, 1, 999) returns the amount from the next row ordered by id. For the last row, since no next row exists, it returns the default value 999 instead of NULL.