Sobes.tech
Junior

Mis vahe on SQL-is WHERE ja HAVING lausetel?

sobes.tech AI

Vastus AI-lt

WHERE applies before grouping and filters the rows of the FROM result. HAVING applies after grouping and filters the groups formed with GROUP BY.

Example:

Suppose we have a table orders with columns customer_id, order_date, and amount.

Find all customers whose total order amount exceeds 1000:

SELECT customer_id, SUM(amount)
FROM orders
GROUP BY customer_id
HAVING SUM(amount) > 1000;

Find all orders with an amount greater than 1000:

SELECT customer_id, order_date, amount
FROM orders
WHERE amount > 1000;

Comparison table:

Feature WHERE HAVING
Application On individual rows before grouping On groups of rows after grouping
Uses Columns from FROM Aggregate functions and columns from GROUP BY
Executed Before GROUP BY After GROUP BY
Aggregate functions Cannot be used directly Can be used