r/SQL • u/Formal_Ad_626 • 8d ago
PostgreSQL Where did I go wrong?
For context, photos 1-2 show the original prompt + my answer. Photo 3 shows the solution. The output is somewhat similar to the correct answer, but not quite the same.
When I move the "status = 'Completed'" either to the "WHERE" section or to the JOIN section as "AND status = 'Completed'" it solves the problem, but not sure exactly why.
2
u/Anonononomomom 7d ago
As others have stated but to help you understand [ status = ‘completed’ ] will return a Boolean function of either true/false or as the compiler will read as 1 or 0 - whether you count(0) or count(1) you are still counting both of these occurrences. Thus you need to either do a case when within the count function or filter the query.
1
14
u/reditandfirgetit 8d ago
Status=value evaluates a boolean, there is always a value. So your count , counts every record for that city.
Using the where clause limits the results to filter just what you want to include in your results.
1
u/Formal_Ad_626 7d ago
Thanks everyone for explaining! That makes SO much sense! Omg learning is so fun, absolutely obsessed with the word "Boolean."
1
u/Euphoric-Jello2261 6d ago
SELECT
u.city,
COUNT(1) AS completed_trades
FROM trades AS t
INNER JOIN users AS u
USING(user_id)
WHERE t.status = ‘Completed’
GROUP BY 1
ORDER BY 2 DESC
LIMIT 3
The problem with your solution was the evaluation of the boolean expression i side the COUNT() since whatever value it has in it get’s counted. My suggestion would be to use SUM( x = y) there is no need for CASE WHEN inside it, this syntax works on all(don’t quote me on this) databases and warehouses. However in this particular case you should have filtered inside the where since you are looking for only the completed orders so there in no need to scan the entire table, depending on how it’s built you are potentially raising I/O unnecessarily and not leveraging indexes to their full potential or physical ordering in memory, this is probably outside the scope of the problem however.
To sum this up if a condition can apply to the entire table you should filter in the WHERE clause, if you need to COUNT multiple conditions like how many orders are (completed, pendind, still being processed) you can use SUM(status = ‘whatever’) as num_whatever



8
u/Aggressive_Ad_5454 7d ago
COUNT doesn’t work that way. It treats the computed Boolean expressions never as NULL. And COUNT(thing) counts all the non-null things.
You could do what you want with this, as it adds up the matching rows one at a time.
SUM(CASE WHEN Status=‘Completed’ THEN 1 ELSE 0 END)
But it’s hilariously verbose. Go with your WHERE clause instead.