- This topic is empty.
Viewing 1 post (of 1 total)
-
AuthorPosts
-
March 23, 2026 at 1:10 pm #6265
π― Problem Context
You are working with a
schoolstable and want to answer:βHow many schools are there in each city, and which cities have 3 or fewer schools?β
This is a classic SQL aggregation problem using:
GROUP BYCOUNT()HAVING
β Initial Attempt (Your Query)
SELECT schools.city, COUNT(schools.city) FROM schools GROUP BY schools.city HAVING COUNT(schools.city <=3) ORDER BY COUNT(schools.city), schools.city;
π¨ Whatβs Wrong Here?
1. β Incorrect Use of
COUNT()COUNT(schools.city <= 3)π Problem:
schools.city <= 3is a condition (TRUE/FALSE)COUNT()expects a column or*, not a boolean expression
2. β Logical Misplacement
You want:
βFilter cities where the count is β€ 3β
But instead of:
COUNT(condition)You should:
COUNT(column) <= 3
β Correct Query
SELECT schools.city, COUNT(schools.city) FROM schools GROUP BY schools.city HAVING COUNT(schools.city) <= 3 ORDER BY COUNT(schools.city), schools.city;
π‘ Even Better Version (Recommended)
SELECT schools.city, COUNT(*) FROM schools GROUP BY schools.city HAVING COUNT(*) <= 3 ORDER BY COUNT(*), schools.city;
π§ Step-by-Step Explanation
πΉ Step 1: Group Data
GROUP BY schools.cityπ Combines all rows with the same city into groups
πΉ Step 2: Count Rows per Group
COUNT(*)π Counts how many schools are in each city
πΉ Step 3: Filter Groups
HAVING COUNT(*) <= 3π Keeps only cities with 3 or fewer schools
πΉ Step 4: Sort Results
ORDER BY COUNT(*), schools.city;π Sorts by:
- Number of schools (ascending)
- City name (alphabetically)
β οΈ Key Concept:
WHEREvsHAVINGClause Used For Example WHEREFiltering rows WHERE city = 'Kolkata'HAVINGFiltering groups HAVING COUNT(*) <= 3
π§ͺ Debugging Strategy (Very Useful)
Start simple:
SELECT schools.city, COUNT(*) FROM schools GROUP BY schools.city;π See all counts first
π Then addHAVINGto filter
π Practice Exercise
Try modifying this query:
π Find cities with:
- More than 5 schools
- Sorted by highest count first
π§© Final Takeaway
- Use
COUNT(*)for counting rows - Use
GROUP BYto aggregate - Use
HAVINGto filter aggregated results - Never put conditions inside
COUNT
-
AuthorPosts
Viewing 1 post (of 1 total)
- You must be logged in to reply to this topic.
