Recall & Review
beginner
What is a running total in SQL?
A running total is a cumulative sum of values in a column, calculated row by row, adding each value to the sum of all previous values.
Click to reveal answer
intermediate
How can you calculate a running total without using window functions?
You can calculate a running total by using a correlated subquery that sums all rows up to the current row based on an ordering column.
Click to reveal answer
intermediate
Write a simple SQL query snippet to calculate a running total without window functions.
SELECT t1.id, t1.amount, (SELECT SUM(t2.amount) FROM table_name t2 WHERE t2.id <= t1.id) AS running_total FROM table_name t1 ORDER BY t1.id;
Click to reveal answer
intermediate
Why might using window functions be preferred over correlated subqueries for running totals?
Window functions are usually more efficient and easier to read because they avoid repeated subqueries and can process rows in a single pass.
Click to reveal answer
beginner
What is a correlated subquery in the context of running totals?
A correlated subquery is a subquery that refers to the outer query's current row, allowing it to calculate sums up to that row for the running total.
Click to reveal answer
Which SQL clause is essential to order rows when calculating a running total without window functions?
✗ Incorrect
ORDER BY is used to define the sequence of rows so the running total sums values in the correct order.
What does a correlated subquery do in a running total calculation?
✗ Incorrect
The correlated subquery sums values from the start up to the current row to produce the running total.
Which of these is a disadvantage of using correlated subqueries for running totals?
✗ Incorrect
Correlated subqueries run a subquery for each row, which can be slow on large tables.
If you cannot use window functions, what SQL feature helps to calculate running totals?
✗ Incorrect
Correlated subqueries allow calculating running totals by summing rows up to the current one.
In the query: SELECT t1.id, (SELECT SUM(t2.amount) FROM table t2 WHERE t2.id <= t1.id) FROM table t1, what does 't2.id <= t1.id' ensure?
✗ Incorrect
The condition sums all amounts from rows with id less than or equal to the current row's id, creating a running total.
Explain how to calculate a running total in SQL without using window functions.
Think about summing all previous rows for each row.
You got /3 concepts.
Describe the advantages and disadvantages of using correlated subqueries for running totals compared to window functions.
Consider performance and compatibility.
You got /3 concepts.