What's the difference between HAVING and WHERE

2019-01-01 16:27发布

I must be googling in the wrong way or I'm having a stupid moment in time.

What's the difference between HAVING and WHERE in an SQL SELECT statement?

EDIT: I've marked Steven's answer as the correct one as it contained the key bit of information on the link:

When GROUP BY is not used, HAVING behaves like a WHERE clause

The situation I had seen the WHERE in did not have GROUP BY and is where my confusion started. Of course, until you know this you can't specify it in the question.

Many thanks for all the answers which were very enlightening.

标签: sql where having
18条回答
闭嘴吧你
2楼-- · 2019-01-01 17:04

In an Aggregate query, (Any query Where an aggregate function is used) Predicates in a where clause are evaluated before the aggregated intermediate result set is generated,

Predicates in a Having clause are applied to the aggregate result set AFTER it has been generated. That's why predicate conditions on aggregate values must be placed in Having clause, not in the Where clause, and why you can use aliases defined in the Select clause in a Having Clause, but not in a Where Clause.

查看更多
一个人的天荒地老
3楼-- · 2019-01-01 17:07

HAVING is used when you are using an aggregate such as GROUP BY.

SELECT edc_country, COUNT(*)
FROM Ed_Centers
GROUP BY edc_country
HAVING COUNT(*) > 1
ORDER BY edc_country;
查看更多
后来的你喜欢了谁
4楼-- · 2019-01-01 17:08

One way to think of it is that the having clause is an additional filter to the where clause.

A WHERE clause is used filters records from a result. The filter occurs before any groupings are made. A HAVING clause is used to filter values from a group

查看更多
牵手、夕阳
5楼-- · 2019-01-01 17:10

I use HAVING for constraining a query based on the results of an aggregate function. E.G. select * in blahblahblah group by SOMETHING having count(SOMETHING)>0

查看更多
低头抚发
6楼-- · 2019-01-01 17:12

HAVING specifies a search condition for a group or an aggregate function used in SELECT statement.

Source

查看更多
刘海飞了
7楼-- · 2019-01-01 17:14

When GROUP BY is not used, the WHERE and HAVING clauses are essentially equivalent.

However, when GROUP BY is used:

  • The WHERE clause is used to filter records from a result. The filtering occurs before any groupings are made.
  • The HAVING clause is used to filter values from a group (i.e., to check conditions after aggregation into groups has been performed).

Resource from Here

查看更多
登录 后发表回答