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?
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.
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.
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With