Group By Vs Order By in SQL
Sure! Here's a quick comparison between GROUP BY and ORDER BY in SQL:
GROUP BY vs ORDER BY in SQL
| Feature | GROUP BY | ORDER BY |
|---|---|---|
| Purpose | Groups rows that have the same values into summary rows (aggregation) | Sorts the result set by one or more columns |
| Used With | Aggregate functions like SUM(), COUNT(), AVG(), etc. | Any SELECT query to arrange rows in a specific order |
| Effect | Combines rows with identical column values into a single row | Changes the display order of rows but does not combine rows |
| Syntax Position | After WHERE and before HAVING / ORDER BY | Last clause in the query |
| Example | SELECT department, COUNT(*) FROM employees GROUP BY department; | SELECT * FROM employees ORDER BY salary DESC; |
| Result | Returns one row per group (e.g., one row per department) | Returns all rows sorted (e.g., employees sorted by salary) |
| Can you use both? | Yes, you can group and then order the grouped results | Yes, usually used to order the final result |
Example combining both:
SELECT department, COUNT(*) AS emp_countFROM employeesGROUP BY departmentORDER BY emp_count DESC;Groups employees by department and counts them.
Then orders departments by the number of employees in descending order.
Summary:
GROUP BY is for grouping data to perform aggregation.
ORDER BY is for sorting the output rows.
If you want, I can show you sample queries or clarify further!