The difference between WHERE and HAVING

本文介绍了在SQL查询中使用WHERE和HAVING子句的区别,并通过具体示例解释了它们如何影响查询性能。WHERE用于过滤行,而HAVING则用于过滤聚合后的结果。了解这些差异有助于优化查询效率。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

WHERE

在单表查询中,在query执行开始时处理。我们过去认为它决定了查询将返回哪些行,但这并不准确:

WHERE determines which rows will be processed by the query.

当我们使用group by时,区别会变得很明显。

HAVING

在单表查询中,在query执行结束时处理。

After all rows have been processed, HAVING determines which of rows will be sent to the client.

The differences

SELECT department_id, count(*) AS employees_no FROM employee WHERE gender = 'F' GROUP BY department_id HAVING employees_no < 10;

  • WHERE excludes non-female employees. Those rows are not read at all by the query.
  • GROUP BY groups (or aggregates) the found rows, producing only one row for each distinct .department_id
  • HAVING eliminates the aggregated rows where is less than 10.employees_no

注意:

  • WHERE employees_no < 10 would fail with an error, because that value doesn’t exist before aggregation.
  • HAVING gender = 'F' would fail with an error, because the gender column doesn’t exist in the aggregated rows (or, if you prefer, in the clause).SELECT

Query performance

SELECT * FROM employee WHERE date_of_birth > '2000-01-01';

HAVING读取所有行,返回符合条件的行

WHERE只读取符合条件的行,如果有索引则使用索引。

Note that some DBMSs are smart enough to translate an unnecessary HAVING clause into a WHERE clause.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值