Yes. The difference is the HAVING
clause is evaluated after the aggregation, and the WHERE
clause before.
This usually results in a performance increase by using WHERE
, but this is not 100% always the case. For example, take the following:
create table foo(type int, data int);
create index bar on foo(id);
insert into foo values(1,3);
insert into foo values(2,3);
insert into foo values(2,3);
insert into foo values(2,3);
insert into foo values(2,3);
insert into foo values(2,3);
insert into foo values(3,3);
insert into foo values(5,3);
This query is better as a WHERE
:
select type, sum(data)
from foo
where type = 5
group by type;
ID SELECT_TYPE TABLE TYPE POSSIBLE_KEYS KEY KEY_LEN REF ROWS FILTERED EXTRA
1 SIMPLE foo ref bar bar 5 const 1 100 Using where
select type, sum(data)
from foo
group by type
having type = 5;
ID SELECT_TYPE TABLE TYPE POSSIBLE_KEYS KEY KEY_LEN REF ROWS FILTERED EXTRA
1 SIMPLE foo index bar 5 8 100
But this query is actually better-performaning as a HAVING
, because the value type=2
is not selective enough:
select type, sum(data)
from foo
where type = 2
group by type;
ID SELECT_TYPE TABLE TYPE POSSIBLE_KEYS KEY KEY_LEN REF ROWS FILTERED EXTRA
1 SIMPLE foo ALL bar 8 62.5 Using where
select type, sum(data)
from foo
group by type
having type = 2;
ID SELECT_TYPE TABLE TYPE POSSIBLE_KEYS KEY KEY_LEN REF ROWS FILTERED EXTRA
1 SIMPLE foo index bar 5 8 100