Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySql - HAVING vs WHERE [duplicate]

Tags:

mysql

What is the difference between these 2 queries?

SELECT f.name,         u.name,         u.id  FROM   families f         JOIN units u           ON f.unit_id = u.id  HAVING u.id IN( 43, 413, 22 ) 

And:

SELECT f.name,         u.name,         u.id  FROM   families f         JOIN units u           ON f.unit_id = u.id  WHERE  u.id IN( 43, 413, 22 ) 

The result of these 2 queries is exactly the same. So where is the difference?

like image 837
Noam B. Avatar asked Apr 22 '13 20:04

Noam B.


People also ask

What is the difference between WHERE and HAVING in MySQL?

What is the Difference between Where and Having Clause in SQL? If “Where” clause is used to filter the records from a table that is based on a specified condition, then the “Having” clause is used to filter the record from the groups based on the specified condition.

What is the difference between HAVING and WHERE `?

WHERE Clause is used to filter the records from the table based on the specified condition. HAVING Clause is used to filter record from the groups based on the specified condition.

Is HAVING faster than WHERE SQL?

The theory (by theory I mean SQL Standard) says that WHERE restricts the result set before returning rows and HAVING restricts the result set after bringing all the rows. So WHERE is faster.

What is difference between HAVING and WHERE clause?

A HAVING clause is like a WHERE clause, but applies only to groups as a whole (that is, to the rows in the result set representing groups), whereas the WHERE clause applies to individual rows. A query can contain both a WHERE clause and a HAVING clause.


2 Answers

WHERE is used to select data in the original tables being processed.

HAVING is used to filter data in the result set that was produced by the query. This means it can reference aggregate values and aliases in the SELECT clause.

For instance, can write:

SELECT t1.val - t2.val diff FROM t1 JOIN t2 ON (some expression) HAVING diff > 10 

This wouldn't work using WHERE because diff is an alias, not one of the original table columns. You could write instead:

SELECT t1.val - t2.val diff FROM t1 JOIN t2 ON (some expression) WHERE t1.val - t2.val > 10 

but then it may have to do all the subtractions twice: once for selecting, and again to produce the result set.

like image 126
Barmar Avatar answered Sep 19 '22 02:09

Barmar


Difference between the having and where clause in sql is that the where clause can not be used with aggregates, but the having clause can. One way to think of it is that the having clause is an additional filter to the where clause.

Which is better : click

like image 32
Ramesh Rajendran Avatar answered Sep 23 '22 02:09

Ramesh Rajendran