SQL Aggregate Functions: COUNT, SUM, MIN, MAX, AVG
Classified in Computers
Written at on English with a size of 12.36 KB.
Aggregations
Consider the case of sports tournaments like cricket. Players' performances are analyzed based on their batting average, the maximum number of sixes hit, the lowest score in a tournament, etc.
In such scenarios, we perform aggregations to combine multiple values into a single value, i.e., individual scores into an average score.
Let's learn more about aggregations to perform insightful analysis using the following database.
Database: The database consists of a player_match_details table that stores information about players' details in a match, such as name, match, score, year, and the number of fours and sixes scored.
Schema
Aggregation Functions
Combining multiple values into a single value is called aggregation. Following are the functions provided by SQL to perform aggregations on the given data:
Aggregate Functions | Description |
---|---|
COUNT | Counts the number of values |
SUM | Adds all the values |
MIN | Returns the minimum value |
MAX | Returns the maximum value |
AVG | Calculates the average of the values |
Syntax
Examples
- Get the total runs scored by "Ram" from the player_match_details table.

Output
SUM(score) |
---|
221 |
- Get the highest and lowest scores among all the matches that happened in the year 2011.
Output
MAX(score) | MIN(score) |
---|---|
75 | 62 |
COUNT Variants
- Calculate the total number of matches played in the tournament.
Variant 1
Variant 2
Variant 3
Output of Variant 1, Variant 2 and Variant 3
All the variants, i.e., Variant 1, Variant 2 and Variant 3 give the same result: 18
Special Cases
- When the SUM function is applied to non-numeric data types like strings, date, time, datetime, etc., the SQLite DBMS returns 0.0, and the PostgreSQL DBMS returns None.
Aggregate functions on strings and their outputs:
Aggregate Functions Output MIN, MAX Based on lexicographic ordering SUM, AVG 0 (depends on DBMS) COUNT Default behavior - NULL values are ignored while computing the aggregation values.
When aggregate functions are applied to only NULL values:
Aggregate Functions Output MIN NULL MAX NULL SUM NULL COUNT 0 AVG NULL
Alias
Using the keyword AS, we can provide alternate temporary names to the columns in the output.
Syntax
FROMtable_name;
Examples
- Get all the names of players with the column name as "player_name".
Output
player_name |
---|
Ram |
Joseph |
--- |
- Get the average score of players as "avg_score".
Output
avg_score |
---|
60 |
Try it Yourself!
- Get the average score of "Ram" in the year 2011.
- Get the lowest score among all the matches.
- Get the highest score among the scores of all players in 2014.
- Get the total number of sixes hit as sixes_hit