SQL Grouping (GROUP BY) πΒΆ
Prerequisites: SQL Filtering (WHERE)
Mentor's Note: Sometimes you don't want to see individual rows; you want the "Big Picture." Grouping is how we summarize thousands of rows into a single meaningful number! π‘
π The Scenario: The Class Report Card πΒΆ
Imagine you are a teacher with 100 students in 4 different departments (IT, CS, Math, Bio).
- The Logic: You don't want to see every student's individual marks. You want to see the Average Mark for EACH department. π¦
- The Result: You group the students by their "Department" label and calculate the mean. This is exactly what
GROUP BYdoes. β
π Concept ExplanationΒΆ
1. Aggregate Functions (The Calculators)ΒΆ
COUNT(): How many items? π’SUM(): Total sum. βAVG(): Average value. πMAX()/MIN(): Highest and Lowest.
2. The GROUP BY ClauseΒΆ
This clause groups rows that have the same values into summary rows.
3. The HAVING ClauseΒΆ
A common mistake is using WHERE to filter groups.
- WHERE: Filters individual rows BEFORE grouping.
- HAVING: Filters the summary groups AFTER they are calculated.
π¨ Visual Logic: The Grouping ProcessΒΆ
graph TD
A[Raw Data: 100 Students] --> B{GROUP BY Dept}
B --> C[IT Group]
B --> D[CS Group]
C -- AVG --> E[IT Average: 85]
D -- AVG --> F[CS Average: 90]
E --> G[Final Report β
]
F --> G
π» Implementations (Dialect Comparison)ΒΆ
π Sample Dry Run (HAVING)ΒΆ
Logic: GROUP BY City HAVING COUNT(*) > 1
| City | Rows | Count | HAVING (>1)? | Result |
|---|---|---|---|---|
| Surat | 5 | 5 | β Yes | SHOW |
| Mumbai | 1 | 1 | β No | HIDE |
π Technical AnalysisΒΆ
- The "Rule of One": Any column in your
SELECTlist that is not part of an aggregate function MUST appear in theGROUP BYclause. If you forget this, you will get an error! β οΈ
π― Practice Lab π§ͺΒΆ
Task: The Genre Count
Task: You have a BOOKS table with a genre column. Write a query to show how many books are there in each genre.
Hint: SELECT genre, COUNT(*) FROM books GROUP BY genre; π‘
π‘ Interview Tip πΒΆ
"Interviewers ALWAYS ask: 'Can we use aggregate functions in a WHERE clause?' Answer: NO. Aggregate functions work on groups, so they can only be used in the SELECT list or the HAVING clause!"
π‘ Pro Tip: "The whole is greater than the sum of its parts." - Aristotle