Is there a performance difference between HAVING o

2019-07-24 06:50发布

Ok, I'm learning, bit by bit, about what HAVING means.

Now, my question is if these two queries have difference performance characteristics:

Without HAVING

SELECT x + y AS z, t.*  FROM t
WHERE 
x = 1 and
x+y = 2

With HAVING

SELECT x + y AS z, t.*  FROM t
WHERE 
x = 1
HAVING
z = 2

2条回答
不美不萌又怎样
2楼-- · 2019-07-24 07:13

Yes it should be different - (1) is expected to be faster.

Having will ensure that first the main query is run and then the having filter is applied - so it basically works on a the dataset returned by the (query minus having).

The first query should be preferable, since it does not select those records at all.

查看更多
兄弟一词,经得起流年.
3楼-- · 2019-07-24 07:18

HAVING is used for queries that contain GROUP BY or return a single row containg the result of aggregate functions. For example SELECT SUM(scores) FROM t HAVING SUM(scores) > 100 returns either one row, or no row at all.

The second query is considered invalid by the SQL Standard and is not accepted by some database systems.

查看更多
登录 后发表回答