- This topic is empty.
-
AuthorPosts
-
March 23, 2026 at 1:29 pm #6266
๐ Learning Post: Understanding GROUP BY vs ORDER BY (and How GROUP BY Reduces Rows
๐ฏ Problem Context
When working with SQL, especially in analytics or reporting, youโll often need to:
Summarize data โ using GROUP BY
Sort results โ using ORDER BY
Many learners confuse these two โ but they serve completely different purposes.
๐งพ Example Table: schools
id name city
1 School A Delhi
2 School B Delhi
3 School C Mumbai
4 School D Mumbai
5 School E Mumbai
6 School F Kolkata
๐ Total rows = 6
๐น Part 1: How GROUP BY Reduces Rows
โ Without GROUP BY
SELECT city FROM schools;
๐ Output:
city
Delhi
Delhi
Mumbai
Mumbai
Mumbai
Kolkata
๐ Rows remain 6
โ With GROUP BY
SELECT city FROM schools
GROUP BY city;
๐ Output:
city
Delhi
Mumbai
Kolkata
๐ Rows reduced from 6 โ 3
๐ง Why Rows Reduce?
GROUP BY:
- Finds unique values
- Combines rows into groups
- Returns one row per group
๐น With Aggregation
SELECT city, COUNT(*)
FROM schools
GROUP BY city;
๐ Output:
city count
Delhi 2
Mumbai 3
Kolkata 1
๐ Still only 3 rows
๐ Each row = summary of a group
๐น Part 2: What ORDER BY Does
โ Sorting Results
SELECT city, COUNT(*)
FROM schools
GROUP BY city
ORDER BY COUNT(*) DESC;
๐ Output (Sorted):
city count
Mumbai 3
Delhi 2
Kolkata 1
๐ Same rows (3)
๐ Just reordered
๐ง Key Insight
ORDER BY does not reduce rows โ it only changes their order.
โ๏ธ GROUP BY vs ORDER BY (Clear Difference)
Feature GROUP BY ๐งฉ ORDER BY ๐ฝ
Purpose Group data Sort data
Effect Reduces rows Keeps same rows
Use Case Aggregation Presentation
Position Before ORDER BY Last clause
โ ๏ธ Common Mistake
SELECT city, name
FROM schools
GROUP BY city;
๐ โ Error (ambiguous name)
โ Correct Version
SELECT city, COUNT(*)
FROM schools
GROUP BY city;
๐ How They Work Together
SELECT city, COUNT(*)
FROM schools
GROUP BY city
HAVING COUNT(*) > 1
ORDER BY COUNT(*) DESC;
๐ง Execution Order (Very Important)
- FROM
- GROUP BY
- HAVING
- SELECT
- ORDER BY
๐งช Practice Exercise
๐ Find cities:
With more than 2 schools
Sorted alphabetically
๐งฉ Final Takeaways
GROUP BY = reduces rows (creates summaries)
ORDER BY = sorts results (no reduction)
Together, they power:
๐ Reports
๐ Dashboards
๐ Data analysis
-
AuthorPosts
- You must be logged in to reply to this topic.
