Calculating Average, Min, and Max with SQL
SQL provides several mathematical operators that allow you to aggregate data and perform various mathematical calculations. Here's a table of some of the most commonly supported methods:
In this lesson, we'll focus on the most commonly used ones in more depth: MIN, MAX, and AVG.
MIN
The MIN operator returns the minimum value of a set of values.
SQLSELECT MIN(column_name) FROM table_name;
Example
Consider the following table of student grades called grades:
To find the minimum grade in the table, we could use the following SQL query:
SQLSELECT MIN(grade) FROM grades;
The result of this query would be:
MAX
The MAX operator returns the maximum value of a set of values.
SQLSELECT MAX(column_name) FROM table_name;
Example
Consider the students table from the previous example. To find the maximum grade in the students table, we use the following SQL query:
SQLSELECT MAX(grade) FROM grades;
The result of this query is:
AVG
The AVG operator returns the average value of a set of values.
SQLSELECT AVG(column_name) FROM table_name;
Example
Consider the students table from the previous example. To find the average grade in the students table, we use the following SQL query:
SQLSELECT AVG(grade) FROM grades;
The result of this query is:
Try it yourself
Given a table of orders with quantity and price columns, find the average order total.