where, group by, having

时间:2024-07-16 20:33:20

where vs having

当一个sql语句中存在where子句,会先执行where,然后执行group by,然后执行having.
一般来说,only use 'having' when you use 'group by'
Always use 'having' with aggregate function.

下面的例子,虽然执行后的结果集一样,但是执行的步骤不同,前者先filter,再group by,后者先group by,然后filter,显然前者更好,而后者浪费了计算资源。

SELECT state, COUNT(*)
FROM Test
WHERE state IN ('CA', 'LA')
GROUP BY state
ORDER BY state

SELECT state, COUNT(*)
FROM Test
GROUP BY state
HAVING state IN ('CA', 'LA')
ORDER BY state