GROUP BY and HAVING
GROUP BY
GROUP BYclause divide the rows returned fromSELECTstatement into groupsFor each group, you can apply aggregate functions like
COUNT,SUM,MIN,MAXetc.
Syntax
SELECT column1,
AGGREGATE_FUNCTION(column2)
FROM tablename
GROUP BY column1;
Group BY
Group the data in column and pass it to aggregate function
Group BY with count
SELECT
movie_lang,
COUNT(movie_lang) as count
FROM
movies
GROUP BY
movie_lang
ORDER BY
count ASC;
movie_lang | count
------------+-------
Swedish | 1
German | 1
Korean | 1
Spanish | 1
Portuguese | 2
Japanese | 4
Chinese | 5
English | 38Group BY with SUM
Group BY with MIN, MAX
HAVING
We use
HAVINGclause to specify a search condition for a group or an aggregateThe
HAVINGclause is often used with theGROUP BYclause to filter rows based on filter conditioncannot use column alias with having clause because it is evaluated before the
SELECTstatement
HAVING AGGREGATE_FUNCTION(column2) = valueHAVING AGGREGATE_FUNCTION(column2) >= value
HAVING vs WHERE
HAVINGworks on result groupWHEREworks onSELECTcolumns and not on the result group
Last updated
Was this helpful?