SQL:SQL GROUP BY and HAVING: Grouping and Post-Filter Aggregation
SQL•Grouping

SQL GROUP BY and HAVING: Grouping and Post-Filter Aggregation

Learn how GROUP BY partitions rows for aggregation and why HAVING filters after grouping (unlike WHERE).

Syntax

SELECT category, COUNT(*) FROM table GROUP BY category HAVING COUNT(*) > 1;

Parameters & Values

Key components and acceptable values for this structure:

ParameterTypeDescription
GROUP BYClauseCollapses rows with identical values into summary rows.
HAVINGClauseFilters groups based on aggregate computations.

Ready-to-Run Code Example

Executable in Compilra

Run this complete, working example directly without installing SQL locally:

CREATE TABLE orders (
    id INTEGER PRIMARY KEY,
    category TEXT,
    revenue REAL
);

INSERT INTO orders VALUES
    (1, 'Hardware', 300.00),
    (2, 'Software', 150.00),
    (3, 'Hardware', 450.00),
    (4, 'Hardware', 200.00),
    (5, 'Software', 80.00),
    (6, 'Consulting', 500.00);

-- Group by category and filter groups with total revenue > $300
SELECT 
    category,
    COUNT(*) AS total_orders,
    SUM(revenue) AS category_revenue
FROM orders
GROUP BY category
HAVING SUM(revenue) > 300.00
ORDER BY category_revenue DESC;
Expected Output:
category    total_orders  category_revenue
----------  ------------  ----------------
Hardware    3             950.0           
Consulting  1             500.0           

How It Works: Step-by-Step

  • Lines 7-13: Inserts orders across Hardware, Software, and Consulting.
  • Lines 16-22: GROUP BY partitions by category; HAVING excludes groups <= $300.

Key Concepts

  • WHERE filters rows BEFORE grouping; HAVING filters groups AFTER grouping.
  • You cannot use aggregate functions inside the WHERE clause.

Common Mistake: Using aggregate functions inside the WHERE clause

WHERE filters individual rows before aggregation occurs. Put aggregate checks in HAVING.

❌ Incorrect
WHERE SUM(revenue) > 300 // Syntax Error!
✅ Correct
HAVING SUM(revenue) > 300

Related SQL Tutorials & Compiler

Run and test SQL on Compilra

Execute this code snippet with pre-supplied standard input (stdin) in Compilra’s cloud compiler.

SQL Online Compiler