Chapter 4 · Lesson 3 of 3

Filtering Groups with HAVING

Filter grouped results with HAVING, learn how it differs from WHERE, and find salespeople with more than one sale using COUNT(*).

WHERE filters individual rows before grouping. HAVING filters the groups after aggregation.

For example, to find salespeople with more than one sale:

SELECT salesperson, COUNT(*) AS sale_count
FROM sales
GROUP BY salesperson
HAVING COUNT(*) > 1

This is useful when you want to keep only groups that meet an aggregate condition.

Sample data

This lesson loads the sales table (8 rows) into DuckDB in your browser with one click, so you can run every example without uploading anything.

Setup SQL for sales
CREATE OR REPLACE TABLE sales (
    id INTEGER,
    salesperson VARCHAR,
    region VARCHAR,
    amount DECIMAL(10,2),
    quantity INTEGER,
    sale_date DATE
  );

INSERT INTO sales VALUES
    (1, 'Alice', 'West', 1200, 3, '2024-01-05'),
    (2, 'Bob', 'East', 850, 2, '2024-01-08'),
    (3, 'Alice', 'West', 640, 1, '2024-01-11'),
    (4, 'Diana', 'South', 430, 5, '2024-01-12'),
    (5, 'Eve', 'West', 1500, 4, '2024-02-01'),
    (6, 'Frank', 'East', 920, 2, '2024-02-03'),
    (7, 'Grace', 'North', 760, 2, '2024-02-07'),
    (8, 'Bob', 'East', 1100, 3, '2024-02-10');

Practice challenge

Find salespeople with more than one sale. Return salesperson and sale_count, ordered by salesperson.

Hint: GROUP BY salesperson, then use HAVING COUNT(*) > 1.

Run your query in the editor and the lesson checks the result automatically.

Open this lesson in the SQL editor

Lessons in DISTINCT and GROUP BY

Remove duplicates with DISTINCT, summarize per category with GROUP BY, and filter grouped results with HAVING.

  1. 01 · Removing Duplicates with DISTINCT
  2. 02 · Summarizing with GROUP BY
  3. 03 · Filtering Groups with HAVING

Related guides