TGViewer
Coding Interview Preparation Coding Interview Preparation @coding_interview_preparation · 5.9K subscribers
Post #1372 338
📊 SQL SATURDAY #3 - GROUP BY and Aggregates


orders
+----+-------------+--------+------------+
| id | customer_id | amount | order_date |
+----+-------------+--------+------------+
| 1 | 1 | 250 | 2024-01-05 |
| 2 | 1 | 100 | 2024-02-14 |
| 3 | 2 | 75 | 2024-01-20 |
| 4 | 3 | 500 | 2024-03-01 |
| 5 | 2 | 200 | 2024-03-15 |


Question: Find the total spend per customer, only for customers who spent more than $150 total.

sql
SELECT customer_id, SUM(amount) AS total_spent
FROM orders
GROUP BY customer_id
HAVING SUM(amount) > 150;


⚠️ The classic trap: using WHERE instead of HAVING here.

sql
-- WRONG:
SELECT customer_id, SUM(amount) AS total_spent
FROM orders
WHERE SUM(amount) > 150 -- ❌ ERROR
GROUP BY customer_id;


WHERE filters rows before grouping happens - it has no idea what SUM(amount) even means yet, since that's calculated during grouping. HAVING filters after the aggregation, which is exactly what you need for conditions on aggregate functions.

Simple rule to remember: WHERE filters rows, HAVING filters groups.

What SQL clause order still confuses you sometimes? (No shame - even senior engineers mix this up under pressure) 👇
  • ❤ 1
More from @coding_interview_preparation
  1. Oct 8, 2026If you're prepping for system design interviews, this repo is gold It contains a curated,…
  2. Oct 6, 2026document post
  3. Oct 4, 2026💼 Why Your Resume Gets Rejected Before a Human Reads It You may have good skills and proj…
  4. Oct 2, 2026🧠 Coding Myths You Should Stop Believing There's a lot of advice online about learning to…
  5. Oct 1, 2026Most Asked Topics in AI Engineer Interviews Based on 2026 candidate reports
  6. Sep 30, 2026💼 What Companies Actually Look For in a Fresher Think companies only care about your CGPA…
Threads Profile ViewerView any public Threads profile without an account.Open ThreadLook →Writing with AI? Make it sound human.Metric37 rewrites AI drafts so they read naturally. Free AI detector, 1,500 words free.Try Metric37 →