What is the difference between GROUP BY and ORDER BY?
GROUP BY collapses rows that share a value into groups so you can run aggregates like COUNT or SUM on each group. ORDER BY simply sorts the result rows in ascending or descending order. GROUP BY changes how many rows you get, while ORDER BY only changes the order they appear in.
- GROUP BY collapses rows into groups, usually with aggregate functions.
- ORDER BY sorts the result rows and does not combine them.
- GROUP BY runs before ORDER BY in query execution.
GROUP BY groups
It combines rows with the same value into one row per group, which is why it is almost always used with an aggregate function to summarise each group.
ORDER BY sorts
It leaves the number of rows unchanged and just arranges them, for example newest first or alphabetically.
SELECT department, COUNT(*) AS staff
FROM employees
GROUP BY department -- one row per department
ORDER BY staff DESC; -- sort those rows
The one line difference is GROUP BY summarises rows into groups, ORDER BY sorts the rows. Showing that they often appear together, with GROUP BY first and ORDER BY last, demonstrates you understand query flow.
Frequently asked questions
Can you use GROUP BY and ORDER BY together?
Yes. GROUP BY forms the groups first, then ORDER BY sorts the grouped results, for example ordering each category by its total sales.
Must GROUP BY columns appear in SELECT?
Any non aggregated column in SELECT must appear in GROUP BY, otherwise the query is ambiguous and most databases reject it.
Common follow up questions
Related interview questions
Want the full SQL guide?
Read every SQL concept with notes, diagrams, and code in one place. Track your progress as you go.
Open the SQL guide All SQL questions