Aggregate Functions
Aggregate or GROUP BY
functions are use to perform calculation on a multiples rows of a single column. Some common aggregate functions include: COUNT()
, SUM()
, and AVG()
.
The GROUP BY
clause is use with Aggregate Functions to group the result by one or more columns. The effect of the using the GROUP BY
clause on a results of a Aggregate Functions will include a separate row for each group with the aggregate calculation occurring only for the data related to that group.
COUNT() Function
The COUNT()
function is use to count the number of non-NULL rows for a specify column. If the *
is used in place of the column it will count every row returned.
SELECT COUNT(*) FROM books;
AVG() Function
The AVG()
function will return the mean average of the values of the given column.
SELECT AVG(book_pages) FROM books;
MIN() and MAX() Functions
The MIN()
and MAX()
functions are use to minimum and maximum values of the provide column.
Note
These functions can be used with string values.
SELECT MIN(book_year) FROM books;
SUM() Function
The SUM()
function return the sum of all the matched rows of the provide column.
Note
The SUM()
function only works with columns with a number datatype.
SELECT SUM(book_pages) FROM books;
GROUP BY Clause
The GROUP BY
clause is use with Aggregate Functions to group the result by one or more columns. The effect of the using the GROUP BY
clause on a results of a Aggregate Functions will include a separate row for each group with the aggregate calculation occurring only for the data related to that group.
SELECT category_id, COUNT(*) FROM books GROUP BY category_id;
HAVING Clause
The WHERE
clause is used to filter results BEFORE any grouping occurs. As such, the WHERE
clause cannot be use with aggregate functions. Instead, the HAVING
clause should be used. The HAVING
clause also filter results, but does AFTER grouping occurs and can be use with aggregate functions.
SELECT category_id, COUNT(*)
FROM books
GROUP BY category_id
HAVING COUNT(*) > 15;