Sobes.tech
Middle

В чем различия между операторами WHERE и HAVING в SQL?

sobes.tech AI

Answer from AI

WHERE filters rows before grouping (GROUP BY), while HAVING filters groups after grouping. WHERE can use columns that are not in SELECT, HAVING usually uses aggregate functions or columns present in GROUP BY.

Example:

SELECT
    category,
    COUNT(*) as total_items
FROM
    products
WHERE
    price > 10 // Filter products before grouping by category
GROUP BY
    category
HAVING
    COUNT(*) > 5; // Filter category groups with more than 5 products

Comparison:

Operator Purpose Applies to Can use aggregate functions Execution order relative to GROUP BY
WHERE Row filtering Individual rows No Before
HAVING Group filtering Groups of rows Yes After
В чем различия между операторами WHERE и HAVING в… - sobes.tech