Understanding GROUP BY and ORDER BY in MySQL

 3 min read

YouTube video ID: zgYqUP_PhQo

Source: YouTube video by Alex The AnalystWatch original video

PDF

Introduction

This article explains how to use the GROUP BY and ORDER BY clauses in MySQL, covering grouping rows, applying aggregate functions, handling errors, and sorting results. Real‑world examples illustrate each concept.

GROUP BY Basics

  • Purpose: Groups rows that share the same values in one or more columns.
  • Result: Each distinct combination of the grouped columns appears once.
  • Typical Use: Combine with aggregate functions (AVG, MIN, MAX, COUNT, etc.) to compute summary statistics for each group.

Simple Example – Grouping by Gender

SELECT gender FROM demographics GROUP BY gender;
  • Returns two rows: male and female.
  • Equivalent to SELECT DISTINCT gender, but GROUP BY prepares the data for aggregates.

Common Mistake – Selecting Non‑Grouped Columns

SELECT first_name, gender FROM demographics GROUP BY gender;
  • MySQL throws an error: "select list is not in GROUP BY clause and contains non‑aggregated columns".
  • Rule: Every column in the SELECT list must either be:
  • Included in the GROUP BY clause, or
  • Wrapped in an aggregate function.
  • Correct query:
SELECT gender FROM demographics GROUP BY gender;

Using Aggregate Functions

Aggregate functions operate on the rows within each group.

Average Age by Gender

SELECT gender, AVG(age) AS avg_age
FROM demographics
GROUP BY gender;
  • Output: male → 41.3, female → 38.5.
  • Shows that females are, on average, younger than males.

Other Aggregates

FunctionDescriptionExample (using gender)
MAX(age)Highest age in each groupSELECT gender, MAX(age) FROM demographics GROUP BY gender;
MIN(age)Lowest age in each groupSELECT gender, MIN(age) FROM demographics GROUP BY gender;
COUNT(*)Number of rows per groupSELECT gender, COUNT(*) FROM demographics GROUP BY gender;

Grouping on Multiple Columns

You can group by more than one column.

SELECT occupation, salary
FROM salary_table
GROUP BY occupation, salary;
  • If two employees share the same occupation and salary, they collapse into a single row.
  • Different salaries for the same occupation produce separate rows (e.g., two office_manager rows with $50k and $60k).

ORDER BY Basics

  • Purpose: Sorts the result set.
  • Default: Ascending (ASC).
  • Syntax: ORDER BY column_name [ASC|DESC];

Simple Ordering by Name

SELECT * FROM demographics ORDER BY first_name;
  • Produces alphabetical order A → Z.

Descending Order

SELECT * FROM demographics ORDER BY first_name DESC;
  • Produces reverse alphabetical order Z → A.

Ordering by Multiple Columns

SELECT * FROM demographics
ORDER BY gender ASC, age ASC;
  • First groups rows by gender, then sorts ages within each gender.
  • Changing age DESC flips the age order while keeping gender order.

Importance of Column Order in ORDER BY

  • The sequence of columns matters. Example:
ORDER BY age ASC, gender ASC;
  • If age values are unique, the secondary gender column has no effect because there are no ties to break.

Using Column Positions in ORDER BY (Not Recommended)

  • MySQL allows numeric positions instead of column names.
SELECT * FROM demographics ORDER BY 5, 4;  -- 5 = gender, 4 = age
  • Works but is fragile: adding/removing columns changes the meaning.
  • Best practice: always use explicit column names.

Key Takeaways

  • GROUP BY aggregates rows sharing the same values; every selected column must be grouped or aggregated.
  • Aggregate functions (AVG, MIN, MAX, COUNT, etc.) provide summary statistics per group.
  • ORDER BY sorts results; column order and direction (ASC/DESC) control the final layout.
  • Prefer explicit column names over positional ordering to avoid future bugs.

The concepts covered here form the foundation for more advanced SQL topics such as HAVING clauses, subqueries, stored procedures, and triggers, which will be explored in the next lesson.

GROUP BY lets you collapse rows into meaningful groups for aggregation, while ORDER BY lets you present those results in a clear, sorted order. Mastering both clauses is essential for writing efficient, readable SQL queries.

Frequently Asked Questions

Who is Alex The Analyst on YouTube?

Alex The Analyst is a YouTube channel that publishes videos on a range of topics. Browse more summaries from this channel below.

Does this page include the full transcript of the video?

Yes, the full transcript for this video is available on this page. Click 'Show transcript' in the sidebar to read it.

PDF