Junior — Middle
In which parts of an SQL query can aggregate functions be used to limit the result?
sobes.tech AI
Answer from AI
Aggregate functions in SQL (such as COUNT, SUM, AVG, MAX, MIN) can be used in the following parts of a query to limit the result:
- In the SELECT clause to compute aggregates over groups or the entire dataset.
- In the HAVING clause to filter groups after applying aggregate functions.
Important: aggregate functions cannot be used in WHERE, as WHERE filters rows before grouping. To limit results based on aggregates, HAVING is used.
Example:
SELECT department, COUNT(*) AS employee_count
FROM employees
GROUP BY department
HAVING COUNT(*) > 5;
Here, HAVING limits the result to only those departments where there are more than 5 employees.