1. Home
  2. Blog
  3. Databases & SQL

Databases & SQL

SQL GROUP BY and HAVING Explained With Examples

Turn rows into summaries. Learn how GROUP BY builds groups, how HAVING filters them, and how both differ from WHERE, using one small sample table.

By Stack QuoraUpdated Oct 30, 20268 min read
SQL GROUP BY HAVING explained with examples

Key takeaways

  • GROUP BY collapses rows that share a value into one row per group, so you can use aggregate functions.
  • HAVING filters groups after aggregation; WHERE filters individual rows before it.
  • Every column in SELECT must be in GROUP BY or inside an aggregate function.
  • Aggregate functions such as COUNT, SUM, AVG, MIN and MAX are the usual partners.

Sooner or later you need answers such as “how many orders did each customer place?” or “which products earned more than $1,000?” A plain SELECT lists rows, but these questions need summaries. That is where SQL GROUP BY HAVING comes in.

This tutorial explains both clauses step by step with a small orders table. All queries use standard SQL and work in PostgreSQL, MySQL, SQL Server and SQLite with minor differences.

If you are brand new to SQL, read our SQL tutorial for beginners first, then come back and run the examples.

Sample data for SQL GROUP BY HAVING

We will use an orders table.

CREATE TABLE orders (
  id INT PRIMARY KEY,
  customer VARCHAR(50),
  product VARCHAR(50),
  amount DECIMAL(10,2),
  status VARCHAR(20)
);

INSERT INTO orders VALUES
(1, 'Asha',  'Keyboard', 50.00,  'paid'),
(2, 'Asha',  'Mouse',    20.00,  'paid'),
(3, 'Ravi',  'Monitor',  200.00, 'paid'),
(4, 'Ravi',  'Keyboard', 50.00,  'refunded'),
(5, 'Meera', 'Mouse',    20.00,  'paid'),
(6, 'Meera', 'Monitor',  200.00, 'paid'),
(7, 'Meera', 'Keyboard', 50.00,  'paid');

GROUP BY in SQL

GROUP BY splits rows into groups that share the same value in one or more columns. Aggregate functions then run once for each group.

SELECT customer, COUNT(*) AS orders_count, SUM(amount) AS total_spent
FROM orders
GROUP BY customer;
customer orders_count total_spent
Asha 2 70.00
Ravi 2 250.00
Meera 3 270.00

Seven rows became three, one per customer. Without GROUP BY, SUM(amount) would collapse the whole table into one row.

Common aggregate functions

  • COUNT(*): number of rows in the group.
  • SUM(col): total of a numeric column.
  • AVG(col): average value.
  • MIN(col) and MAX(col): smallest and largest values.

Grouping by more than one column

SELECT customer, product, COUNT(*) AS times_bought
FROM orders
GROUP BY customer, product;

Each unique customer and product pair becomes its own group.

SQL GROUP BY HAVING: the HAVING clause in SQL

The HAVING clause filters groups after the aggregate values are calculated. Use it when your condition involves an aggregate such as SUM or COUNT.

SELECT customer, SUM(amount) AS total_spent
FROM orders
GROUP BY customer
HAVING SUM(amount) > 100;

This returns only Ravi (250.00) and Meera (270.00), because Asha’s total of 70.00 does not pass the filter. You cannot write WHERE SUM(amount) > 100, because WHERE runs before any group exists.

SQL GROUP BY HAVING vs WHERE: which one filters what

Aspect WHERE HAVING
Filters Individual rows Groups
Runs Before GROUP BY After GROUP BY
Can use aggregates? No Yes
Works without GROUP BY? Yes Rarely, treats the table as one group

You can use both in one query. Here we first ignore refunded orders with WHERE, then keep customers who spent over 100:

SELECT customer, SUM(amount) AS total_paid
FROM orders
WHERE status = 'paid'
GROUP BY customer
HAVING SUM(amount) > 100
ORDER BY total_paid DESC;

Result: Meera with 270.00 and Ravi with 200.00 (his refunded 50.00 order was removed by WHERE). Filter with WHERE whenever you can, because it reduces the rows before grouping and is usually faster.

Quick tip: Ask yourself, “Am I filtering rows or filtering totals?” Rows go in WHERE, totals go in HAVING.

Logical order of execution

SQL does not run in the order you write it. A simplified view of the logical order is:

  1. FROM and joins
  2. WHERE
  3. GROUP BY
  4. HAVING
  5. SELECT
  6. ORDER BY
  7. LIMIT

This explains why you can use ORDER BY total_paid but, in many databases, not a SELECT alias in HAVING. The PostgreSQL aggregate tutorial walks through the same idea, and the SQLite SELECT documentation describes how grouping is processed.

SQL GROUP BY HAVING with joins

Grouping becomes powerful when combined with joins, for example counting orders per customer name from a separate table. Our SQL joins explained guide covers the join types you will use first.

SELECT c.name, COUNT(o.id) AS orders_count
FROM customers c
LEFT JOIN orders o ON o.customer_id = c.id
GROUP BY c.name
HAVING COUNT(o.id) = 0;

This finds customers who have never ordered. Counting o.id instead of * makes unmatched rows count as zero.

Common SQL GROUP BY HAVING mistakes

  • Selecting a column that is not grouped. SELECT customer, product, SUM(amount) ... GROUP BY customer fails in most databases because product is neither grouped nor aggregated.
  • Using WHERE for aggregates. Move conditions on SUM, COUNT or AVG to HAVING.
  • Forgetting NULLs. COUNT(col) ignores NULL values while COUNT(*) does not, and NULLs form their own group.
  • Putting all filters in HAVING. Row-level filters belong in WHERE for speed.

For testers, these queries are also great for data checks: find duplicate emails with GROUP BY email HAVING COUNT(*) > 1, or confirm totals match what the application shows.

SELECT email, COUNT(*) AS copies
FROM users
GROUP BY email
HAVING COUNT(*) > 1;

Final thoughts

Once you see that GROUP BY builds groups and HAVING filters them, SQL GROUP BY HAVING stops feeling tricky. Practise with your own tables: count, sum and average by different columns, then add HAVING to keep only the groups that matter. Combine it with joins and you can answer most reporting questions in a single query.

Frequently asked questions

What is the difference between WHERE and HAVING in SQL?

WHERE filters individual rows before grouping and cannot use aggregates. HAVING filters groups after aggregation and can use functions such as SUM and COUNT.

Can I use HAVING without GROUP BY?

Yes in some databases, where the whole result is treated as one group, but it is rare. Normally HAVING is paired with GROUP BY.

Can I use a column alias in HAVING?

It depends on the database. MySQL allows it, while PostgreSQL and SQL Server do not, so repeat the aggregate expression to be portable.

Does GROUP BY sort the results?

Not reliably. Add ORDER BY if you need a specific order, because grouping order is not guaranteed.

How do I find duplicate rows with GROUP BY?

Group by the columns that should be unique and use HAVING COUNT(*) > 1 to list the values that appear more than once.

Keep learning

Work with Stack Quora

Need help with testing, WordPress or SEO?

We help teams ship better software and grow their sites. Tell us what you are working on and we will suggest a clear next step.

Keep reading

More guides on testing, AI & modern development

Enjoyed this article? Pick a topic and jump straight into our newest tutorials.

Databases & SQL

SQL GROUP BY and HAVING Explained With Examples

SQL GROUP BY and HAVING explained with sample tables, aggregate functions, WHERE vs HAVING and common mistakes, with queries you…

Read article →
Software Development

HTTP Status Codes Cheat Sheet for Developers and Testers

An HTTP status codes cheat sheet for developers and testers: every common 1xx to 5xx code, what it means and…

Read article →
Test Automation

Selenium WebDriver Waits Explained: Implicit, Explicit and Fluent

Selenium waits explained: implicit, explicit and fluent waits with Python examples, when to use each and how to remove flaky…

Read article →
Software Testing

Test Automation Mistakes Beginners Make and How to Avoid Them

The 10 test automation mistakes beginners make, from flaky waits to automating everything, and the practical fixes that keep your…

Read article →
Artificial Intelligence

Claude Opus 5.5 vs Sonnet 5.5: Pricing, Speed and When to Use Each

Claude Opus 5.5 vs Sonnet 5.5 compared: listed pricing, context, speed and a simple guide to which model fits coding,…

Read article →
Artificial Intelligence

Best AI Code Review Tools for Developers in 2026

Compare the best AI code review tools in 2026: CodeRabbit, GitHub Copilot, Qodo, Greptile and more. See what each does,…

Read article →
Software Development

What Is an API? A Simple Guide for Beginners

What is an API? Learn in plain English how APIs work, the main types, HTTP methods and status codes, with…

Read article →
Test Automation

Playwright Locators Cheat Sheet With Examples

A practical Playwright locators cheat sheet: getByRole, getByText, getByLabel, test IDs, CSS, filtering and chaining, with copy-paste examples for stable…

Read article →
Software Testing

How to Write Test Cases: Format, Examples and Best Practices

Learn how to write test cases with a clear format, login and checkout examples, a reusable template and best practices…

Read article →
Artificial Intelligence

Gemini 4 Argon: What’s New and How It Compares to Earlier Gemini Models

Gemini 4 Argon is Google's new flagship reasoning model. See its API limits, app features, coding focus and how to…

Read article →
Databases & SQL

SQL Joins Explained With Examples (Inner, Left, Right, Full)

SQL joins explained step by step with sample tables and queries: INNER, LEFT, RIGHT, FULL, CROSS and SELF joins, plus…

Read article →
Software Development

Python Virtual Environment Tutorial: venv, pip and uv

Learn how to create, activate and manage a Python virtual environment with venv, pip and uv, including requirements files, .gitignore…

Read article →
Test Automation

Playwright vs Cypress in 2026: Which Should You Pick?

Playwright vs Cypress compared for 2026: browsers, languages, speed, debugging, parallel runs, CI and cost. Find out which end-to-end testing…

Read article →
Software Testing

Smoke Testing vs Sanity Testing: Differences With Real Examples

Smoke testing checks that a build is stable enough to test. Sanity testing checks that a specific fix works. Learn…

Read article →
Artificial Intelligence

Claude Haiku 5.5: Features, Pricing and Use Cases for Developers

Claude Haiku 5.5 is Anthropic's fastest and lowest-priced model. See its 1M-token context, pricing, API changes and the best use…

Read article →
Software Testing

End to End Testing Best Practices: Boost Reliability in 2026

Flaky tests waste time and hide real bugs. Learn end to end testing best practices that make your tests stable,…

Read article →
Test Automation

Best Test Automation Framework 2026: Choose the Right One

Not sure which test automation framework to pick? Compare the main types, use a simple checklist, and see how Playwright,…

Read article →
Artificial Intelligence

AI Agents Best Practices: Deploy Reliable Intelligent Bots

AI agents can save hours of work, but only when they are built with care. Learn AI agents best practices…

Read article →
Test Automation

Test Automation Framework Example: Build a Scalable Suite

See a real test automation framework example with folder layout, page objects, test data and CI steps. Copy the structure…

Read article →
Software Testing

Best Test Automation Tools 2026: Top Picks for QA Teams

Compare the best test automation tools in 2026 for web, mobile and API testing. See what each tool does well,…

Read article →
Software Development

REST API Best Practices 2026: Build Scalable Services

Learn REST API best practices for 2026: clear URLs, correct status codes, versioning, pagination, security and error handling, with simple…

Read article →
Artificial Intelligence

MCP Stateless Architecture: What’s New in MCP 2026

The MCP 2026-07-28 spec removes sessions and the handshake. See how stateless MCP works, what breaks, what gets easier to…

Read article →
Artificial Intelligence

WebMCP Explained: How AI Agents Will Interact With Websites

WebMCP lets a website publish tools that AI agents can call directly. Learn the Declarative and Imperative APIs, code examples,…

Read article →
Databases & SQL

SQL Tutorial for Beginners: Complete Guide to SQL in 2026

Learn SQL from scratch. Create tables, insert and query data, filter, sort, group, join tables and use subqueries and indexes,…

Read article →
Software Development

Git Tutorial for Beginners: Complete Guide to Git and GitHub in 2026

Learn Git from zero. Create repositories, commit, branch, merge, fix mistakes and work with GitHub pull requests, using simple commands…

Read article →
DevOps

Docker Tutorial for Beginners: Complete Guide to Docker in 2026

New to Docker? Learn containers, images, Dockerfiles, volumes, networks and Docker Compose with simple commands and a small project you…

Read article →
Databases & SQL

Vector Databases Explained: How Vector Search and AI Databases Work in 2026

Vector databases search by meaning, not just keywords. Learn embeddings, similarity search, HNSW indexes, pgvector and how to choose the…

Read article →
Software Testing

API Testing with Postman: A Complete Guide for Beginners and QA Testers

Learn API testing with Postman from scratch. Send requests, read status codes, add auth, write test scripts, build collections and…

Read article →
DevOps

GitHub Actions CI/CD: A Complete Guide to Automating Software Builds, Tests and Deployments

Learn GitHub Actions from scratch. Build a CI/CD workflow that runs tests, builds your app and deploys it, with simple…

Read article →