- Why can't use SUM() in WHERE?
- Why can't use AS in WHERE or GROUP BY?
😎 You will get the reason why it is like that
When you see this SQL, what do you think about order?
SELECT * FROM clients WHERE age >= 30 GROUP BY usa HAVING salary > 1000 ORDER BY id desc LIMIT 100
Seems like sql executes from SELECT ?
actually it's not true
-- SQL executes in this order FROM | WHERE | GROUP BY | HAVING | SELECT | ORDER BY | LIMIT
FROM | WHERE 👈 👈 | GROUP BY 👈 👈 | HAVING | SELECT | ORDER BY | LIMIT
Before WHERE executes, GROUP BY has not executed yet, so we can't use COUNT() SUM() in WHERE.
In other word, it's possible to use these functions in HAVING.
FROM | WHERE 👈 👈 | GROUP BY 👈 👈 | HAVING | SELECT 👈 👈 | ORDER BY 👀 👀 | LIMIT
take it easy, man. Because ORDER BY executes after SELECT.
You can't read name which is created by "AS" before define it.
Thank you for reading 🤗