- This topic is empty.
Viewing 1 post (of 1 total)
-
AuthorPosts
-
March 24, 2026 at 5:19 pm #6268
Problem Context
You are working with a
schoolstable and want to answer:βHow many Public Schools are there in each city, and which cities have 3 or fewer Public Schools?β
Additionally, you want the result:
- Sorted by count (descending)
- Then by city name (ascending)
β Initial Query (Common Mistake)
SELECT city, COUNT(type) AS cc FROM schools HAVING type = "Public School" AND cc<=3 GROUP BY city ORDER BY cc DESC, city ASC;
π¨ Whatβs Wrong?
1. β Incorrect Clause Order
SQL follows a strict execution order:
SELECT β FROM β WHERE β GROUP BY β HAVING β ORDER BYπ But the query used:
HAVING ... GROUP BY ...β This breaks SQL syntax
2. β Using
HAVINGInstead ofWHEREHAVING type = "Public School"π Problem:
HAVINGfilters groups- This condition filters rows
β Must use
WHERE
3. β Using Alias in
HAVINGcc <= 3π Not always supported across SQL engines
π Safer to use:COUNT(*) <= 3
β Correct Query
SELECT city, COUNT(*) AS cc FROM schools WHERE type = "Public School" GROUP BY city HAVING COUNT(*) <= 3 ORDER BY cc DESC, city ASC;
π§ Step-by-Step Breakdown
πΉ Step 1: Filter Rows (
WHERE)WHERE type = "Public School"π Keeps only rows where school type is “Public School”
πΉ Step 2: Group Rows (
GROUP BY)GROUP BY cityπ Groups all remaining rows by city
πΉ Step 3: Aggregate (
COUNT)COUNT(*)π Counts how many public schools exist per city
πΉ Step 4: Filter Groups (
HAVING)HAVING COUNT(*) <= 3π Keeps only cities with β€ 3 public schools
πΉ Step 5: Sort Results (
ORDER BY)ORDER BY cc DESC, city ASC;π Sorts:
- Highest count first
- Then city alphabetically
βοΈ WHERE vs HAVING (Critical Concept)
Clause Works On Example WHEREIndividual rows type = "Public School"HAVINGGroups COUNT(*) <= 3
π§ͺ Debugging Strategy (Very Important)
Step 1: Check filtering
SELECT * FROM schools WHERE type = "Public School";Step 2: Check grouping
SELECT city, COUNT(*) FROM schools WHERE type = "Public School" GROUP BY city;Step 3: Add filtering on groups
HAVING COUNT(*) <= 3;
π‘ Pro Tips
- Use
COUNT(*)instead ofCOUNT(column)unless needed - Always remember SQL order
- Think in phases:
- Filter rows
- Group data
- Aggregate
- Filter groups
- Sort
π Practice Exercise
Modify the query to:
π Find cities with:
- More than 5 public schools
- Sorted by city name only
π§© Final Takeaways
WHEREfilters before groupingGROUP BYcreates groupsHAVINGfilters after groupingORDER BYcontrols final output order
-
AuthorPosts
Viewing 1 post (of 1 total)
- You must be logged in to reply to this topic.
