r/mysql • u/Glittering_Bat_1846 • Oct 26 '26
question Quick question on difference between these two queries
Hi! I have been practicing SQL on LeetCode when I ran into something I could use some clarification on.
Can someone explain why I get different values for approved_count with the two following queries:
Query 1)
select LEFT(trans_date,7) as month, country, count(id) as trans_count, count(state="approved") as approved_count, sum(amount) as trans_total_amount, SUM(
CASE when state = "approved" then amount
ELSE 0
END
) as approved_total_amount
from Transactions
group by month, countryQuery 2)
select LEFT(trans_date,7) as month, country, count(id) as trans_count, SUM(
CASE WHEN state="approved" then 1 else 0 end
) as approved_count, sum(amount) as trans_total_amount, SUM(
CASE when state = "approved" then amount
ELSE 0
END
) as approved_total_amount
from Transactions
group by month, country
Query 1 fails the test but query 2 succeeds. For the following input table:
| id | country | state | amount | trans_date |
| --- | ------- | -------- | ------ | ---------- |
| 121 | US | approved | 1000 | 2018-12-18 |
| 122 | US | declined | 2000 | 2018-12-19 |
| 123 | US | approved | 2000 | 2019-01-01 |
| 124 | DE | approved | 2000 | 2019-01-07 |Query 1 yields:
| month | country | trans_count | approved_count | trans_total_amount | approved_total_amount |
|---|---|---|---|---|---|
| 2018-12 | US | 2 | 2 | 3000 | 1000 |
| 2019-01 | US | 1 | 1 | 2000 | 2000 |
| 2019-01 | DE | 1 | 1 | 2000 | 2000 |
While query 2 yields:
| month | country | trans_count | approved_count | trans_total_amount | approved_total_amount |
|---|---|---|---|---|---|
| 2018-12 | US | 2 | 1 | 3000 | 1000 |
| 2019-01 | US | 1 | 1 | 2000 | 2000 |
| 2019-01 | DE | 1 | 1 | 2000 | 2000 |
Any assistance would be appreciated!
I found out that using SUM(state="approved") does work, as well. So it has something to do with COUNT.
4
Upvotes
4
u/ssnoyes Oct 26 '26
COUNT(expression) does not count only when the expression is true. It counts all non-NULL values, including false/0.
1
u/Basic_Reporter9579 Oct 26 '26
What do you expect
state="approved"to be? A countable value or null?1
u/TheGoodOne777 Oct 26 '26
Hello! The count is counting both approved and declined states, but if you put count(0) the query is going to run even faster on DB2 database for example, but still you'll get 2 as a result.
1
u/BetterDistrict3979 Oct 27 '26
COUNT()only cares if a value isn't NULL. When you runstate="approved", the database evaluates that as true or false, which usually translates to 1 or 0. Since both of those are actual values,COUNT()just tallies every single row anyway. I always stick toSUMwith aCASEstatement for this exact reason. It actually adds up the specific matches and saves you from dealing with stupid logic bugs later.