GROUP BY With Joins

Which goes first, GROUP BY or ORDER BY?

GROUP BY runs before ORDER BY in SQL. Here is the order SQL processes clauses in, with a sales example that groups totals and then sorts them.

On this page
  1. GROUP BY comes first
  2. The order of clauses
  3. Example: totals by region, sorted
  4. Sorting in MySQL 8.0 and later
  5. Common mistakes

GROUP BY comes first

GROUP BY runs before ORDER BY. In the query text you write GROUP BY first, and the database groups the rows before it sorts the final result. ORDER BY is one of the last steps.

The order of clauses

Clauses are written in this order:

SELECT ...
FROM ...
WHERE ...
GROUP BY ...
HAVING ...
ORDER BY ...
LIMIT ...

Putting ORDER BY before GROUP BY is a syntax error. The database also works through the clauses in a logical order that differs from how they are written:

  1. FROM and JOIN gather the rows.
  2. WHERE filters individual rows.
  3. GROUP BY builds the groups.
  4. HAVING filters the groups.
  5. SELECT chooses the output columns.
  6. ORDER BY sorts the rows.
  7. LIMIT keeps the requested number of rows.

ORDER BY comes after SELECT in this order, so it can use column aliases and aggregate results that the groups already have. The optimizer may take a different internal path, but the result matches this sequence.

Example: totals by region, sorted

Here is a small sales table:

CREATE TABLE sales (
  sale_id INT PRIMARY KEY,
  region VARCHAR(50) NOT NULL,
  amount DECIMAL(10, 2) NOT NULL
);

INSERT INTO sales (sale_id, region, amount) VALUES
  (1, 'North', 120.00),
  (2, 'South', 80.00),
  (3, 'North', 60.00),
  (4, 'West', 200.00),
  (5, 'South', 50.00);

This query adds up the amounts for each region and sorts the totals:

SELECT region,
       SUM(amount) AS total_sales
FROM sales
GROUP BY region
ORDER BY total_sales DESC;

The result has three rows:

region total_sales
West 200.00
North 180.00
South 130.00

GROUP BY builds one group per region and adds up the amounts in each. ORDER BY then sorts those totals from highest to lowest, using the alias total_sales.

To keep only the top rows, add LIMIT after ORDER BY. Learners searching for “How to retrieve last 5 records in SQL?” use the same ORDER BY and LIMIT pattern.

Sorting in MySQL 8.0 and later

GROUP BY doesn’t sort its output on its own in MySQL 8.0 and later. The GROUP BY region DESC form of sorting was removed in MySQL 8.0.13, so ORDER BY is the way to sort grouped results.

Common mistakes

  • Writing ORDER BY before GROUP BY. That is a syntax error.
  • Sorting by a column that isn’t grouped or aggregated. With ONLY_FULL_GROUP_BY on, ORDER BY follows the same rule as the SELECT list and fails with error 1055.
  • Expecting an order without ORDER BY. Rows from a grouped query can come back in any order.

The complete guide to group by with joins

Using GROUP BY With INNER JOIN in MySQL
Read the guide

Keep exploring

Guides from other topics

All topics →