🗄️ SQL examples

GROUP BY Examples in SQL

Summarize data by category, month, region or customer. This page gives you the syntax, five practical examples, common mistakes, and copy-ready SQL you can adapt.

Updated 2026-06-125 practical examplesCopy-ready SQL

💡 Ideas for You

Learning resources for SQL queries, databases and reporting workflows.

4 useful links

Some links in this section may be affiliate links. Choose only what is useful for your own work.

What GROUP BY does

Summarize data by category, month, region or customer. SQL syntax can vary by database, but the pattern below is a useful starting point for reports and analysis.

Syntax or pattern

SELECT category, SUM(amount) FROM table_name GROUP BY category;
✍️

5 practical examples

1

Sales by region

Summarize total sales for each region.

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

GROUP BY collapses rows into one result per region.

2

Orders by customer

Count orders for each customer.

SELECT customer_id, COUNT(*) AS order_count FROM orders GROUP BY customer_id;

This is useful for customer activity analysis.

3

Revenue by product category

Group sales by product category.

SELECT p.category, SUM(oi.quantity * oi.unit_price) AS revenue FROM order_items oi JOIN products p ON oi.product_id = p.product_id GROUP BY p.category;

Join first, then group by the reporting category.

4

Monthly order count

Group orders by month.

SELECT DATE_TRUNC('month', order_date) AS month, COUNT(*) AS orders FROM orders GROUP BY DATE_TRUNC('month', order_date);

The date expression used in SELECT usually needs to match GROUP BY.

5

Average order value by channel

Compare channels by average order amount.

SELECT channel, AVG(total_amount) AS avg_order_value FROM orders GROUP BY channel;

Averages by group are useful in ecommerce reports.

Common mistakes to avoid

  • Forgetting that SQL dialects vary across PostgreSQL, SQL Server, MySQL, BigQuery and SQLite.
  • Using SELECT * in production reports when only a few columns are needed.
  • Not checking join keys, duplicate rows or NULL values before trusting results.

FAQ

Will this SQL work in every database?

The idea is portable, but function names and date syntax may vary. Check your database dialect if a function is not recognized.

Should I use this in a report query?

Yes, if the pattern matches the business question and you have checked filters, joins and row counts.

Why does my result have too many rows?

The most common reasons are duplicate join keys, missing filters or grouping at the wrong level of detail.