Sobes.tech
Junior — Middle

Is it possible to use the WHERE condition in SQL queries with aggregate functions like COUNT, SUM, AVG?

sobes.tech AI

Answer from AI

In SQL, the WHERE condition is used to filter rows before applying aggregate functions (COUNT, SUM, AVG, etc.). That is, WHERE filters the raw data, and then aggregate functions are calculated on the filtered rows.

If you need to filter already aggregated results, the HAVING clause is used.

Example:

-- Select the number of orders for customers from a specific city
SELECT COUNT(*)
FROM orders
WHERE city = 'Moscow';

-- Select customers with more than 5 orders
SELECT customer_id, COUNT(*) as orders_count
FROM orders
GROUP BY customer_id
HAVING COUNT(*) > 5;
Is it possible to use the WHERE condition in SQL… - sobes.tech