Member-only story
In SQL, both the WHERE
and HAVING
clauses are used to filter data, but they are used in different contexts and with different purposes.
I. WHERE
Clause:
- The
WHERE
clause is used with theSELECT
,UPDATE
,DELETE
, andINSERT
statements to filter rows based on a specified condition. - It is primarily used for filtering rows before they are grouped and aggregated.
- It operates on individual rows before any grouping or aggregation takes place.
- Commonly used for conditions involving columns present in the individual rows.
SELECT column1, column2
FROM table_name
WHERE condition;
II. HAVING
Clause:
- The
HAVING
clause is used with theSELECT
statement and is specifically used with aggregate functions likeCOUNT
,SUM
,AVG
, etc. - It is used to filter the results of a grouped query, specifying conditions on the result of aggregate functions.
- It operates on grouped rows, after the
GROUP BY
clause, and filters the result set based on aggregated values. - Commonly used for conditions involving the result of aggregate functions.
SELECT column1, column2, aggregate_function(column3)
FROM…