Introduction
We use WHERE and HAVING to filter data in a database. WHERE filters rows before grouping, and HAVING filters groups after grouping.
Jump into concepts and practice - no test required
We use WHERE and HAVING to filter data in a database. WHERE filters rows before grouping, and HAVING filters groups after grouping.
SELECT column1, aggregate_function(column2) FROM table_name WHERE condition GROUP BY column1 HAVING aggregate_condition;
WHERE filters rows before grouping.
HAVING filters groups after grouping.
SELECT department, COUNT(*) FROM employees WHERE salary > 50000 GROUP BY department HAVING COUNT(*) > 5;
SELECT category, SUM(sales) FROM sales_data GROUP BY category HAVING SUM(sales) > 10000;
SELECT * FROM products WHERE price < 20;
This example filters sales rows with amount > 60 first, then groups by region, and finally shows only regions with total sales above 200.
CREATE TABLE sales ( product VARCHAR(20), region VARCHAR(20), amount INT ); INSERT INTO sales VALUES ('Pen', 'East', 100), ('Pen', 'West', 150), ('Pencil', 'East', 50), ('Pencil', 'West', 70), ('Notebook', 'East', 200), ('Notebook', 'West', 180); SELECT region, SUM(amount) AS total_sales FROM sales WHERE amount > 60 GROUP BY region HAVING SUM(amount) > 200;
WHERE cannot use aggregate functions like SUM or COUNT.
HAVING is used only with GROUP BY or aggregate functions.
Think of WHERE as a filter on raw data, HAVING as a filter on grouped data.
WHERE filters rows before grouping.
HAVING filters groups after grouping.
Use WHERE for simple conditions, HAVING for conditions on aggregates.
orders(order_id, customer_id, amount), what will this query return?SELECT customer_id, COUNT(*) AS order_count FROM orders WHERE amount > 50 GROUP BY customer_id HAVING order_count > 2;
SELECT department, AVG(salary) FROM employees HAVING AVG(salary) > 50000 WHERE department LIKE 'Sales%' GROUP BY department;