Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which SQL statement is faster? (HAVING vs. WHERE...)

SELECT NR_DZIALU, COUNT (NR_DZIALU) AS LICZ_PRAC_DZIALU     FROM  PRACOWNICY     GROUP BY NR_DZIALU     HAVING NR_DZIALU = 30 

or

SELECT NR_DZIALU, COUNT (NR_DZIALU) AS LICZ_PRAC_DZIALU     FROM PRACOWNICY     WHERE NR_DZIALU = 30     GROUP BY NR_DZIALU 
like image 218
M_1 Avatar asked Nov 30 '08 08:11

M_1


People also ask

Is HAVING better than WHERE SQL?

The difference between the having and where clause in SQL is that the where clause cannot be used with aggregates, but the having clause can. The where clause works on row's data, not on aggregated data.

Does WHERE clause make query faster?

A where clause will generally increase the performance of the database. Generally, it is more expensive to return data and filter in the application. The database can optimize the query, using indexes and partitions. The database may be running in parallel, executing the query in parallel.

Which query is faster in SQL?

Use CASE instead of UPDATE UPDATE statement takes longer than CASE statement due to logging. On the other hand, CASE statement determines what needs to be updated and makes your SQL queries faster.

When would you use a HAVING clause versus a WHERE clause?

1. 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.


2 Answers

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. On SQL Standard compliant DBMSs in this regard, only use HAVING where you cannot put the condition on a WHERE (like computed columns in some RDBMSs.)

You can just see the execution plan for both and check for yourself, nothing will beat that (measurement for your specific query in your specific environment with your data.)

like image 148
Vinko Vrsalovic Avatar answered Oct 21 '22 21:10

Vinko Vrsalovic


It might depend on the engine. MySQL for example, applies HAVING almost last in the chain, meaning there is almost no room for optimization. From the manual:

The HAVING clause is applied nearly last, just before items are sent to the client, with no optimization. (LIMIT is applied after HAVING.)

I believe this behavior is the same in most SQL database engines, but I can't guarantee it.

like image 34
Eran Galperin Avatar answered Oct 21 '22 20:10

Eran Galperin