</>
Skip to content
MySQL lessons (21/48)

MySQL — Group By

Basic GROUP BY

SELECT category, COUNT(*) as count
FROM products
GROUP BY category;

GROUP BY with Aggregate Functions

SELECT category,
       COUNT(*) as count,
       AVG(price) as avg_price,
       MIN(price) as min_price,
       MAX(price) as max_price
FROM products
GROUP BY category;

GROUP BY Multiple Columns

SELECT category, brand, COUNT(*) as count
FROM products
GROUP BY category, brand;

GROUP BY Examples

-- Users per country
SELECT country, COUNT(*) as user_count
FROM users
GROUP BY country;

-- Average age by gender
SELECT gender, AVG(age) as avg_age
FROM users
GROUP BY gender;

-- Total sales by month
SELECT
    MONTH(order_date) as month,
    SUM(total) as total_sales
FROM orders
GROUP BY MONTH(order_date);

-- Products per category with total stock
SELECT
    category,
    COUNT(*) as product_count,
    SUM(stock) as total_stock
FROM products
GROUP BY category;

Mini Practice

Write MySQL code that:

  1. Groups by single column
  2. Uses aggregate functions
  3. Groups by multiple columns
  4. Groups with date functions

Up Next

Next: Learn about Having clause.

Related Topics

Frequently Asked Questions about Group By

What is Group By in MySQL?

Group By is a fundamental concept in MySQL. This lesson explains it step by step with clear examples, making it easy for beginners to understand.

How do I learn Group By?

Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Group By.

Why is Group By important in MySQL?

Group By is essential for MySQL development. Understanding this concept will help you write better code and solve real-world problems more effectively.