Account
AccNo Balance
A1 5000
A2 5000
A3 10000
A4 15000
A5 18000
Consider the given SQL query.
SELECT AccNo FROM Account AS A
WHERE (SELECT COUNT(*) FROM Account AS B
WHERE A.Balance < B.Balance) >= (SELECT COUNT(*)
FROM Account AS C WHERE A.Balance > C.Balance)
The number of rows returned by the SQL query is __________ . (Answer in integer)
3.00
Step-by-Step Solution
Insight: This is the classic median/rank pattern using correlated subqueries to count strictly greater and strictly smaller elements.
Exam route: For each balance, count the number of strictly greater and strictly smaller balances. Keep the row if greater >= smaller.
Learning route:
Step 1: Recognize the pattern. The query uses correlated subqueries to count elements greater than and smaller than the current row's value. This is a standard technique for finding medians or ranks.
Step 2: Evaluate for A1 (Balance = 5000).
- Count of B where 5000 < B.Balance: B can be A3(10000), A4(15000), A5(18000). Count = 3.
- Count of C where 5000 > C.Balance: None. Count = 0.
- Condition: 3 >= 0. TRUE.
Step 3: Evaluate for A2 (Balance = 5000).
- Same as A1. Count greater = 3, Count smaller = 0.
- Condition: 3 >= 0. TRUE.
Step 4: Evaluate for A3 (Balance = 10000).
- Count of B where 10000 < B.Balance: A4(15000), A5(18000). Count = 2.
- Count of C where 10000 > C.Balance: A1(5000), A2(5000). Count = 2.
- Condition: 2 >= 2. TRUE.
Step 5: Evaluate for A4 (Balance = 15000).
- Count of B where 15000 < B.Balance: A5(18000). Count = 1.
- Count of C where 15000 > C.Balance: A1(5000), A2(5000), A3(10000). Count = 3.
- Condition: 1 >= 3. FALSE.
Step 6: Evaluate for A5 (Balance = 18000).
- Count of B where 18000 < B.Balance: None. Count = 0.
- Count of C where 18000 > C.Balance: A1, A2, A3, A4. Count = 4.
- Condition: 0 >= 4. FALSE.
Step 7: Count the TRUE rows: A1, A2, A3. Total = 3.
Verification: The condition greater >= smaller identifies the median or lower-middle elements. For 5 elements, the median is the 3rd element (10000), and the lower-middle includes the two 5000s. Total 3 rows.