Bird
0
0

Identify the error in this query intended to calculate running totals:

medium📝 Debug Q6 of 15
SQL - Advanced Query Patterns
Identify the error in this query intended to calculate running totals:
SELECT id, amount, (SELECT SUM(amount) FROM sales WHERE id < id) AS running_total FROM sales ORDER BY id;
AThe ORDER BY clause is missing.
BThe subquery condition 'id < id' compares the same column without alias, causing always false condition.
CThe query uses window functions which are not allowed.
DThe SUM() function cannot be used in subqueries.
Step-by-Step Solution
Solution:
  1. Step 1: Analyze the subquery condition

    The condition 'id < id' compares the same column from the same table without alias, so it is always false.
  2. Step 2: Understand the effect on running total

    Because the condition is always false, the subquery returns NULL or zero, so running_total is incorrect.
  3. Final Answer:

    The subquery condition 'id < id' compares the same column without alias, causing always false condition. -> Option B
  4. Quick Check:

    Incorrect subquery condition = Always false [OK]
Quick Trick: Use table aliases to distinguish columns in subqueries [OK]
Common Mistakes:
  • Not using aliases causing ambiguous column references
  • Misunderstanding subquery logic
  • Assuming SUM() can't be in subqueries

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More SQL Quizzes