4
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

Undo
  • 25,519
  • 37
  • 106
  • 129
user909058
  • 188
  • 1
  • 2
  • 11

2 Answers2

8

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

Ben Lee
  • 52,489
  • 13
  • 125
  • 145
  • 2
    +1 spot on, but `s/is conditions on/filters/g` for precision. I.e., "where filters rows; having filters groups." #pedantic – Ray Toal Sep 12 '11 at 06:11
7
  1. WHERE clause can be used with SELECT,INSERT,DELETE etc statement but the HAVING clause can only be used with SELECT statement.
  2. HAVING clause can only be used with GROUP BY clause
  3. In WHERE clause we can not use any agregate function directly
Kimvais
  • 38,306
  • 16
  • 108
  • 142
Phil Wallach
  • 3,318
  • 20
  • 19