Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between HAVING and WHERE clause in SQL [duplicate]

SELECT column_name, aggregate_function(column_name) 
FROM table_name 
WHERE column_name operator value 
GROUP BY column_name 
HAVING aggregate_function(column_name) operator value

What is the difference between having and where

like image 936
user909058 Avatar asked Dec 07 '22 19:12

user909058


1 Answers

where filters on the select ... from

having filters on the aggregate results from the group by ...

So, looking at your example again:

SELECT column_name, aggregate_function(column_name)
FROM table_name
WHERE column_name operator value
GROUP BY column_name
HAVING aggregate_function(column_name) operator value

Here, WHERE column_name operator value says "Return results for table_name where 'column_name operator value' is true".

Only after all the results from these conditions are found, it groups by column_name.

Then HAVING aggregate_function(column_name) operator value says "For the resulting aggregate groups, run 'aggregate_function(column_name)' and return only results where 'aggregate_function(column_name) operator value' is true."

like image 71
Ben Lee Avatar answered Jan 05 '23 15:01

Ben Lee