The GROUP BY and ORDER BY clauses in SQL

SQL GROUP BY vs ORDER BY: Key Differences (with Examples)

Understand how ORDER BY sorts rows and how GROUP BY aggregates rows—so you never mix them up again.

Section 1 — Introduction + ORDER BY

Beginners often confuse ORDER BY and GROUP BY because they’re used together frequently. The truth: they do very different jobs. We’ll start with ORDER BY, then compare it with GROUP BY in the next section.

What is ORDER BY in SQL?

ORDER BY sorts the result set based on one or more columns. It does not group or summarize rows— it only arranges them for better readability or reporting. Default sort is ASC (ascending). Use DESC for descending.

Syntax
SELECT column1, column2, ...
FROM table_name
ORDER BY column1 [ASC|DESC], column2 [ASC|DESC];
Example — Sort employees by highest salary
SELECT EmployeeName, Department, Salary
FROM Employees
ORDER BY Salary DESC;

This returns all employees, sorted from the highest to lowest salary. No rows are grouped or aggregated.

Sample Data (before sorting)

EmployeeName Department Salary
AshaSales55000
RohanHR42000
MeeraIT78000

After ORDER BY Salary DESC, the order becomes: Meera, Asha, Rohan.

ORDER BY = sorts rows (presentation layer).

✅ Default is ASC; use DESC for reverse.

No aggregation or grouping happens with ORDER BY.

Keywords: difference between GROUP BY and ORDER BY in SQL, ORDER BY in SQL example, SQL ORDER BY ASC DESC

Section 2 — What is GROUP BY in SQL?

GROUP BY combines rows with the same values into summary rows so you can run aggregates like COUNT, SUM, AVG, MIN, MAX.

Use GROUP BY when you need one row per group (e.g., totals per department). Every non-aggregated column in the SELECT list must also appear in the GROUP BY clause.

Syntax
SELECT group_column, AGGREGATE_FUNCTION(column) AS alias
FROM table_name
GROUP BY group_column;
Example — Total salary and headcount per department
SELECT Department,
       COUNT(*)           AS EmployeeCount,
       SUM(Salary)        AS TotalSalary,
       AVG(Salary)        AS AvgSalary
FROM Employees
GROUP BY Department;

Output = one row per Department with aggregated metrics.

Filtering groups with HAVING

Use HAVING to filter aggregated results (post-group filter).

SELECT Department,
       COUNT(*)  AS EmployeeCount,
       AVG(Salary) AS AvgSalary
FROM Employees
GROUP BY Department
HAVING AVG(Salary) > 60000;

GROUP BY vs ORDER BY — At a Glance

Feature GROUP BY ORDER BY
Purpose Group rows into summaries Sort rows for display
Typical Use With aggregates (COUNT, SUM, AVG…) With or without aggregates
Output Rows One row per group All rows, re-ordered
Filtering HAVING (after aggregation) WHERE (before sorting)
Can Use Together? Yes — group first, then sort the grouped result with ORDER BY.
Keywords: group by in SQL, SQL group by example, SQL having clause, difference between group by and order by in SQL
GROUP BY IN SQL

Section 3 — Use GROUP BY with ORDER BY (+ ASC vs DESC)

Group first, then sort the aggregated result. Control sort direction per column using ASC/DESC.

Logical execution order: FROM → WHERE → GROUP BY → HAVING → SELECT → ORDER BY. That’s why you can sort using aggregate aliases (e.g., TotalSales) in ORDER BY.

Example 1 — Top revenue by product (DESC) with name tie-break (ASC)
SELECT ProductName,
       SUM(Quantity * UnitPrice) AS TotalSales
FROM OrderItems
GROUP BY ProductName
ORDER BY TotalSales DESC, ProductName ASC;

Groups rows per ProductName, then sorts groups by TotalSales (highest first), and alphabetically for ties.

Example 2 — Average salary by department & role (DESC, then ASC)
SELECT Department,
       JobTitle,
       AVG(Salary) AS AvgSalary
FROM Employees
GROUP BY Department, JobTitle
ORDER BY AvgSalary DESC, Department ASC;

Multiple grouping columns are allowed. Sort directions can differ per column.

Example 3 — Keep only groups with ≥ 10 orders, then sort by count
SELECT CustomerID,
       COUNT(*) AS OrderCount
FROM Orders
GROUP BY CustomerID
HAVING COUNT(*) >= 10
ORDER BY OrderCount DESC;

HAVING filters after grouping; the final list is then sorted by the aggregate alias.

✅ You can ORDER BY an alias created in the SELECT list (e.g., TotalSales).

✅ Positional sort works in many DBs: ORDER BY 2 DESC (sort by 2nd selected column). Use sparingly for readability.

⚠️ With DISTINCT, some systems require all ORDER BY columns to appear in the SELECT list.

⚠️ NULLS order varies by DB (e.g., PostgreSQL: NULLS FIRST|LAST). Check your engine’s behavior.

Section 4 — Common Mistakes, ASC/DESC Gotchas & Interview Q&A

Avoid these pitfalls and nail the interview with sharp, real-world answers.

1) Thinking GROUP BY sorts

Many engines do not sort grouped output. If you need order, add ORDER BY explicitly.

2) Non-aggregated columns in SELECT

Every non-aggregated column must appear in GROUP BY (ANSI). Otherwise results are undefined or errors.

3) Using WHERE for aggregates

WHERE filters rows before grouping. To filter aggregated values, use HAVING.

4) Ties without deterministic sort

If values tie, add a second key (e.g., ORDER BY Total DESC, ProductName ASC) for stable ordering.

5) NULL ordering assumptions

Engines differ (e.g., some put NULLs first in ASC). Use engine features (e.g., NULLS LAST or ORDER BY col IS NULL) to control it.

6) Sorting huge text columns

Avoid expensive sorts on large strings. Sort by a key/ID or add proper indexes where possible.

ASC vs DESC — Practical Gotchas

  • Default is ASC. Always specify DESC when you want highest-to-lowest.
  • Mixed directions: You can sort each column differently (ORDER BY score DESC, name ASC).
  • Alias ordering: You can ORDER BY an alias from SELECT (e.g., AvgSalary).
  • Positional ordering: ORDER BY 2 DESC works in many DBs; prefer explicit names for clarity.
  • LIMIT + ORDER BY: For “Top-N”, combine ORDER BY ... DESC with LIMIT N (or FETCH FIRST N ROWS).
Top 3 departments by total salary
SELECT Department, SUM(Salary) AS Total
FROM Employees
GROUP BY Department
ORDER BY Total DESC
LIMIT 3;
Sort with NULLs last (portable)
SELECT ProductName, Price
FROM Products
ORDER BY (Price IS NULL), Price ASC;
Filter rows vs groups correctly
-- Row filter first
SELECT * FROM Orders
WHERE Status = 'Shipped'
ORDER BY OrderDate DESC;

-- Group filter after aggregation
SELECT CustomerID, COUNT(*) AS Cnt
FROM Orders
GROUP BY CustomerID
HAVING COUNT(*) >= 5
ORDER BY Cnt DESC;

Interview Q&A — Quick hitters

What’s the difference between GROUP BY and ORDER BY?

GROUP BY aggregates rows into summaries; ORDER BY sorts rows (or groups) for display. They solve different problems and can be used together.

Does GROUP BY sort results?

Not reliably. Add ORDER BY for deterministic ordering.

When do I use WHERE vs HAVING?

Use WHERE to filter rows before grouping; use HAVING to filter aggregated groups after GROUP BY.

Can I ORDER BY an aggregate alias?

Yes. Because ORDER BY executes after SELECT, aliases like Total or AvgSalary are available.

How to get Top-N groups by an aggregate?

GROUP BY → ORDER BY aggregate DESC → LIMIT N (or FETCH FIRST N ROWS depending on engine).

ORDER BY IN SQL QUERY
groupby and order by together

Summary — GROUP BY vs ORDER BY in SQL

A final quick recap of how GROUP BY and ORDER BY differ and complement each other.

ORDER BY

  • Sorts rows for presentation.
  • ASC (default) or DESC order.
  • No grouping or aggregation.

GROUP BY

  • Groups rows into summaries.
  • Always used with aggregates (SUM, COUNT, AVG…).
  • Use HAVING to filter groups.

Together

  • GROUP BY creates summaries.
  • ORDER BY sorts those summaries.
  • Common for reporting dashboards.

One-Glance Comparison Table

Aspect GROUP BY ORDER BY
Purpose Group rows into summaries Sort rows or groups
Aggregates Used with COUNT, SUM, AVG… Not required
Output Rows One per group All rows reordered
Filtering HAVING (after grouping) WHERE (before sorting)
Together? Yes — group first, then sort results with ORDER BY

🚀 You’re now crystal-clear on GROUP BY vs ORDER BY. Time to practice with real SQL queries!

Try SQL Practice Questions →

Interactive MCQ Quiz — SQL GROUP BY vs ORDER BY

Pick one option for each question and click Submit Quiz. Your score and answers will appear at the end.

    Vista Academy – 316/336, Park Rd, Laxman Chowk, Dehradun – 248001
    📞 +91 94117 78145 | 📧 thevistaacademy@gmail.com | 💬 WhatsApp
    💬 Chat on WhatsApp: Ask About Our Courses