Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the difference between HAVING and WHERE in MySQL Query?

I have a view (viewX) based on joins of some tables:

When I use WHERE, the query is delayed, processor usage goes to 50% and finally I need to close mysqld.exe service and restart to try to solve the problem again.

When I use HAVING, the query executes perfectly and quickly, I get the results and all is ready.

The query is similar to this:

SELECT * FROM viewX WHERE column_of_view = 'foo'

SELECT * FROM viewX HAVING column_of_view = 'foo'

What is happening?

The solution I found is to do something like this:

SELECT * FROM (SELECT * FROM viewX) as T WHERE column_of_view = 'foo'

SELECT * FROM (SELECT * FROM viewX) as T HAVING column_of_view = 'foo'

BOTH QUERIES WORKS FINE, BUT, I think this is BAD! (SELECT * FROM (...viewX)????)

like image 946
CRISHK Corporation Avatar asked Sep 16 '11 03:09

CRISHK Corporation


People also ask

What is the difference between WHERE and HAVING in mysql?

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.

How is HAVING different than WHERE in SQL?

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.

Which is better HAVING or WHERE?

When to use WHERE and HAVING clauses? Though both are used to exclude rows from the result set, you should use the WHERE clause to filter rows before grouping and use the HAVING clause to filter rows after grouping.

Why HAVING is used instead of WHERE?

Well, the main distinction between the two clauses is that HAVING can be applied for subsets of aggregated groups, while in the WHERE block, this is forbidden. In simpler words, after HAVING, we can have a condition with an aggregate function, while WHERE cannot use aggregate functions within its conditions.


1 Answers

WHERE is for filtering query results based on condition.

HAVING is for applying a filter on results of an aggregate function. In absence of aggregate function it functions same as WHERE.

http://blog.sqlauthority.com/2007/07/04/sql-server-definition-comparison-and-difference-between-having-and-where-clause/

like image 143
Muhammad Hasan Khan Avatar answered Sep 27 '22 16:09

Muhammad Hasan Khan