Sobes.tech
Junior — Middle

Mis vahe on WHERE ja HAVING tingimustel SQL-päringute töötamisel?

sobes.tech AI

Vastus AI-lt

In SQL, the conditions WHERE and HAVING are used for filtering data, but they are applied at different stages of query processing:

  • WHERE filters rows before grouping and aggregation. It limits the dataset that will be used in the query.
  • HAVING filters groups after applying aggregate functions (e.g., SUM, COUNT, AVG). It is used to restrict the results of aggregation.

Example:

SELECT department, COUNT(*) as employee_count
FROM employees
WHERE salary > 50000       -- filter employees with salary > 50000
GROUP BY department
HAVING COUNT(*) > 10;        -- select departments with more than 10 employees

Here, WHERE selects employees with salary above 50000, and HAVING filters departments with more than 10 employees.