CRISHK Corporation
CRISHK Corporation

Reputation: 3008

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)????)

Upvotes: 5

Views: 3225

Answers (4)

Mohammedshafeek C S
Mohammedshafeek C S

Reputation: 1943

Having is used for aggregate functions like sum,avg so on and it can be using only in select statement.where clause won't work in aggregate conditions eg: where sum(mark) > 300 // its not true

Upvotes: 1

AMIB
AMIB

Reputation: 3430

WHERE is used while listing and no ALIAS names are available yet

HAVING filters rows after listing all possible rows so ALIAS names are generated

There should be a problem while filtering rows inline.

Upvotes: 0

Muhammad Hasan Khan
Muhammad Hasan Khan

Reputation: 35126

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/

Upvotes: 5

Lee
Lee

Reputation: 345

It depends on the definition of the view - having clause should only apply to an aggregate query and its applied after the grouping. Have you looked at the two query plans (with explain)?

Upvotes: 0

Related Questions