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:
| Parameter | Type | Description |
|---|---|---|
| GROUP BY | Clause | Collapses rows with identical values into summary rows. |
| HAVING | Clause | Filters groups based on aggregate computations. |
Ready-to-Run Code Example
Executable in CompilraRun 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
SQL Dynamic Transactional CASE WHEN Metrics Query Logic
Implement dynamic transactional business logic and classification metrics in SQL using CASE WHEN expressions.
SQL Relational Set Aggregation Methods vs Raw Cursor Loops Performance
Compare relational set-based aggregation techniques with slow row-by-row procedural cursor loops in SQL.
SQL INNER JOIN and LEFT JOIN: Combining Relational Tables
Combine related data across tables using INNER JOIN and LEFT OUTER JOIN with ON keys.
SQL Online Compiler
Open in Compilra IDE
Run and test SQL on Compilra
Execute this code snippet with pre-supplied standard input (stdin) in Compilra’s cloud compiler.