Bird
0
0

Consider this query intended to calculate a running total:

medium📝 Debug Q14 of 15
SQL - Advanced Query Patterns
Consider this query intended to calculate a running total:
SELECT id, amount, (SELECT SUM(amount) FROM sales WHERE id < s.id) AS running_total FROM sales s ORDER BY id;

What is the main issue with this query?
AIt will cause a syntax error due to missing GROUP BY.
BIt uses window functions which are not allowed.
CIt excludes the current row's amount from the running total.
DIt sums amounts from unrelated tables.
Step-by-Step Solution
Solution:
  1. Step 1: Analyze the subquery condition

    The subquery sums amounts where id is less than current row's id, so it excludes the current row's amount.
  2. Step 2: Understand running total definition

    Running total should include the current row's amount, so condition should be id <= s.id, not id < s.id.
  3. Final Answer:

    It excludes the current row's amount from the running total. -> Option C
  4. Quick Check:

    Use id <= current id to include current row [OK]
Quick Trick: Check if current row is included in sum condition [OK]
Common Mistakes:
  • Using < instead of <= in subquery condition
  • Expecting window functions in this query
  • Assuming syntax error due to GROUP BY

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More SQL Quizzes