These are three of the most common aggregate functions in SQL.
COUNT() FunctionThe COUNT() function returns the number of rows that matches a specified criterion.
COUNT() SyntaxSELECT COUNT(column_name)
FROM table_name
WHERE condition;
COUNT(*) returns the total number of records in a table. COUNT(column_name) returns the number of non-NULL values in that column.
SUM() FunctionThe SUM() function returns the total sum of a numeric column.
SUM() SyntaxSELECT SUM(column_name)
FROM table_name
WHERE condition;
AVG() FunctionThe AVG() function returns the average value of a numeric column.
AVG() SyntaxSELECT AVG(column_name)
FROM table_name
WHERE condition;
Below is a selection from the Orders table:
Orders Table:
| OrderID | CustomerID | OrderDate |
|---|---|---|
| 10308 | 2 | 1996-09-18 |
| 10309 | 37 | 1996-09-19 |
| 10310 | 77 | 1996-09-20 |
COUNT()The following SQL statement finds the total number of orders in the Orders table.
SELECT COUNT(OrderID) FROM Orders;
SUM()The following SQL statement finds the sum of the "CustomerID" fields for all orders.
SELECT SUM(CustomerID) FROM Orders;
AVG()The following SQL statement finds the average CustomerID for all orders.
SELECT AVG(CustomerID) FROM Orders;