Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL: using WHERE AND instead of HAVING

Tags:

sql

here's an example of a SQL statement where we use HAVING:

select column1 from table1
where condition1
having condition2;

isn't it the same exact thing if we do this:

select column1 from table1
where condition1 AND condition2;

what is the difference between these two?

like image 873
Alex Gordon Avatar asked Jul 01 '10 16:07

Alex Gordon


People also ask

Can you use WHERE instead of HAVING?

In conclusion, the difference between WHERE and HAVING are: WHERE is used to filter records before any groupings take place. HAVING is used to filter values after they have been groups. Only columns or expressions in the group can be included in the HAVING clause's conditions…

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.

What is the difference between HAVING and WHERE in SQL?

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.

Which is better WHERE or HAVING?

Both the statements will be having same performance as SQL Server is smart enough to parse both the same statements into a similar plan. So, it does not matter if you use WHERE or HAVING in your query.


1 Answers

In your example, they should do the same thing. But WHERE gets processed before any GROUP BY, and so it doesn't have access to aggregated values (that is, the results of Min(), Max(), etc. functions). HAVING gets processed after GROUP BY and so can be used to constrain the result set to only those with aggregated values that match a certain predicate.

like image 193
Daniel Pryden Avatar answered Oct 09 '22 08:10

Daniel Pryden