SQL Practice Logo

SQLPractice Online

HAVING Clause: Examples

Module: Aggregate Functions & Grouping

Basic HAVING: Large Departments

basic

Find departments with more than 10 employees

SELECT

department,

COUNT(*) AS employee_count

FROM employees

GROUP BY department

HAVING COUNT(*) > 10

ORDER BY employee_count DESC;

department | employee_count

Engineering | 45

Sales | 30

Finance | 12

HAVING COUNT(*) > 10 filters groups after aggregation. Departments with ≤10 employees are excluded.

All

High-Revenue Customers

intermediate

Find customers with total spending over $5000

SELECT

customer_id,

COUNT(*) AS order_count,

SUM(order_total) AS total_revenue

FROM orders

GROUP BY customer_id

HAVING SUM(order_total) > 5000

ORDER BY total_revenue DESC;

customer_id | order_count | total_revenue

103 | 12 | 8200.00

101 | 8 | 7500.00

HAVING SUM(order_total) > 5000 keeps only high-value customers. WHERE cannot be used because SUM is an aggregate.

All

WHERE vs HAVING

intermediate

Count recent orders per customer, show only active customers

SELECT

customer_id,

COUNT(*) AS recent_orders

FROM orders

WHERE order_date >= '2024-01-01'