The GROUP BY and ORDER BY clauses in SQL
SQL GROUP BY vs ORDER BY with simple examples for beginners

Introduction

Why SQL beginners confuse GROUP BY and ORDER BY

Many SQL beginners confuse ORDER BY and GROUP BY because both are often used in the same query. However, they perform completely different tasks.

In this guide, you’ll first learn how ORDER BY sorts rows, then understand how GROUP BY groups data for aggregation — followed by a clear comparison table and real examples.

ORDER BY

Sorts rows for display and reporting.

GROUP BY

Groups rows to calculate totals, counts, and averages.

Why It Matters

Frequently asked in SQL interviews and exams.

The main difference between ORDER BY and GROUP BY in SQL is that ORDER BY sorts rows in the result set, while GROUP BY groups rows to perform aggregation such as COUNT(), SUM(), and AVG().

ORDER BY vs GROUP BY in SQL

Key differences explained clearly

Feature ORDER BY GROUP BY
Purpose Sorts rows in the result set Groups rows for aggregation
Used With SELECT queries Aggregate functions (COUNT, SUM, AVG)
Data Processing No grouping or summarization Rows are combined into grouped results
Execution Order Executed after GROUP BY Executed before ORDER BY
Sorting Keywords ASC, DESC Not applicable
Typical Use Case Sorting reports and result sets Creating summaries and totals
Interview Importance Medium High

Section 2 — What is GROUP BY in SQL?

GROUP BY combines rows with the same values so you can calculate totals, counts, and averages.

Use GROUP BY when you need one row per group, such as totals per department or average salary per role. Any column that is not part of an aggregate function must appear in the GROUP BY clause.

GROUP BY Syntax and Example

Aggregating data correctly

SELECT group_column, AGGREGATE_FUNCTION(column) AS alias
FROM table_name
GROUP BY group_column;
    
SELECT Department,
       COUNT(*)    AS EmployeeCount,
       SUM(Salary) AS TotalSalary,
       AVG(Salary) AS AvgSalary
FROM Employees
GROUP BY Department;
    

This query returns one row per department with aggregated metrics such as total employees and average salary.

Filtering GROUP BY Results with HAVING

Post-aggregation filtering

Use HAVING to filter aggregated results. Unlike WHERE, HAVING works after grouping is complete.

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

The key difference between GROUP BY and ORDER BY in SQL is that GROUP BY aggregates rows into summary results, while ORDER BY only sorts rows without aggregation.

GROUP BY vs ORDER BY — Quick Comparison

Understand when to use each clause

Feature GROUP BY ORDER BY
Purpose Groups rows into summaries Sorts rows for display
Common Use With aggregate functions Sorting query results
Result Rows One row per group All rows reordered
Filtering Clause HAVING WHERE
Can Be Used Together? Yes — GROUP BY runs first, then ORDER BY sorts the grouped result.

Next Step

Learn how to combine GROUP BY and ORDER BY with ASC and DESC.

Continue →

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 — Using GROUP BY with ORDER BY (ASC vs DESC)

Group data first, then sort the aggregated result using ASC or DESC.

Logical SQL execution order:
FROM → WHERE → GROUP BY → HAVING → SELECT → ORDER BY

Because ORDER BY runs last, you can safely sort using aggregate aliases such as TotalSales or AvgSalary.

Example 1: Sort by Aggregate (DESC) with Tie-Break (ASC)

Most common real-world pattern

SELECT ProductName,
       SUM(Quantity * UnitPrice) AS TotalSales
FROM OrderItems
GROUP BY ProductName
ORDER BY TotalSales DESC, ProductName ASC;
    

This query groups rows by ProductName, sorts products by TotalSales (highest first), and alphabetically orders products with equal sales.

Example 2: Multiple GROUP BY Columns with Mixed Sorting

Department + role analytics

SELECT Department,
       JobTitle,
       AVG(Salary) AS AvgSalary
FROM Employees
GROUP BY Department, JobTitle
ORDER BY AvgSalary DESC, Department ASC;
    

You can group by multiple columns and apply different sort directions for each column in ORDER BY.

Example 3: HAVING + ORDER BY on Aggregate Alias

Filter groups, then sort them

SELECT CustomerID,
       COUNT(*) AS OrderCount
FROM Orders
GROUP BY CustomerID
HAVING COUNT(*) >= 10
ORDER BY OrderCount DESC;
    

HAVING filters grouped results, and ORDER BY sorts the remaining groups using the aggregate alias.

Pro Tips & Gotchas

Important interview and production notes

Alias Sorting

You can ORDER BY an alias defined in the SELECT clause.

Positional ORDER BY

ORDER BY 2 DESC works in many DBs but hurts readability.

DISTINCT Rules

Some DBs require ORDER BY columns to appear in SELECT.

NULL Sorting

NULL order differs by database (e.g., NULLS FIRST/LAST).

Up Next

Common mistakes, ASC vs DESC traps, and interview questions.

Continue →

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

Avoid common SQL pitfalls and answer interview questions with confidence.

Common GROUP BY & ORDER BY Mistakes

Seen often in interviews and production code

GROUP BY does not sort

Grouped results are not ordered unless you explicitly use ORDER BY.

Missing GROUP BY columns

All non-aggregated SELECT columns must appear in GROUP BY.

WHERE vs HAVING

WHERE filters rows before grouping; HAVING filters after aggregation.

No tie-breaker in ORDER BY

Add a second sort column to avoid non-deterministic ordering.

NULL ordering assumptions

NULL sorting differs by database; always handle explicitly.

Sorting large text columns

Prefer indexed numeric keys for better performance.

ASC vs DESC — Practical Gotchas

Small details that cause big bugs

  • ASC is default. Always specify DESC when needed.
  • You can mix directions: ORDER BY score DESC, name ASC
  • ORDER BY supports aliases defined in SELECT.
  • Positional ordering (ORDER BY 2) works but hurts readability.
  • Top-N queries use ORDER BY + LIMIT (or FETCH FIRST).

Common SQL Recipes

Patterns you should remember

-- 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 approach)
SELECT ProductName, Price
FROM Products
ORDER BY (Price IS NULL), Price ASC;
    
-- WHERE vs HAVING example
SELECT CustomerID, COUNT(*) AS OrderCount
FROM Orders
GROUP BY CustomerID
HAVING COUNT(*) >= 5
ORDER BY OrderCount DESC;
    

Interview Questions & Answers

Frequently asked SQL questions

What is the difference between GROUP BY and ORDER BY?
GROUP BY aggregates rows into summary results, while ORDER BY sorts rows or groups for display.
Does GROUP BY sort the results?
No. GROUP BY does not guarantee ordering. Always use ORDER BY explicitly.
When should I use WHERE vs HAVING?
WHERE filters rows before grouping. HAVING filters aggregated groups.
Can I ORDER BY an aggregate alias?
Yes. ORDER BY runs after SELECT, so aggregate aliases are available.
How do I get Top-N groups?
Use GROUP BY, then ORDER BY the aggregate in DESC order, and apply LIMIT.

Final Step

Read the summary and download the SQL cheat sheet.

Continue →
ORDER BY IN SQL QUERY
groupby and order by together

Summary — GROUP BY vs ORDER BY in SQL

A quick recap of how GROUP BY and ORDER BY differ and how they work together.

ORDER BY

Sorts rows for presentation and reporting.

Uses ASC (default) or DESC.

No grouping or aggregation.

GROUP BY

Groups rows into summary results.

Always paired with aggregate functions.

Use HAVING to filter groups.

Together

GROUP BY creates summaries.

ORDER BY sorts those summaries.

Common in analytics and dashboards.

GROUP BY vs ORDER BY — One-Glance Comparison

Everything you need to remember

Aspect GROUP BY ORDER BY
Purpose Group rows into summaries Sort rows or grouped results
Aggregates Required (COUNT, SUM, AVG…) Not required
Output Rows One row per group All rows reordered
Filtering HAVING (after grouping) WHERE (before sorting)
Used Together? Yes — GROUP BY runs first, then ORDER BY sorts the result.

You’re Ready to Practice 🚀

You now understand GROUP BY vs ORDER BY clearly. Strengthen your skills with hands-on SQL queries.

Try SQL Practice Questions →

GROUP BY vs ORDER BY — Visual Summary

One glance. Zero confusion.

📊 ORDER BY

Purpose: Sort rows

Works on: Result set

Keywords: ASC, DESC

Aggregation: ❌ No

Use when: You want ordered output

🧮 GROUP BY

Purpose: Group rows

Works on: Raw data

Keywords: COUNT, SUM, AVG

Aggregation: ✅ Yes

Use when: You need summaries

🔗 TOGETHER

Step 1: GROUP BY → summarize

Step 2: ORDER BY → sort

Execution: GROUP first

Common in: Reports & dashboards

Interview: ⭐ Very common

How SQL Thinks (Execution Flow)

FROMWHEREGROUP BYHAVINGSELECTORDER BY

This is why ORDER BY can use aggregate aliases.

One-Line Takeaway

GROUP BY creates summaries.
ORDER BY sorts results.
Use both together for clean, powerful SQL reports.

Ready to Practice?

Apply what you learned with real SQL problems and interview-style questions.

Start Practicing →

Interactive Quiz — GROUP BY vs ORDER BY

Answer one question at a time. Results appear at the end.

Question 1 of 10

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