SQL

SQL Functions

SQL Functions

This page covers SQL Functions.

Similarly to other programming languages, SQL allows the use of functions.

Functions perform operations on values and return the result. We cover only some basic SQL built-in functions in this section.

For more details functions here.

This tutorial encompasses:

  • min and max
  • average
  • sum
  • count

Let’s use the table “student_info” from the previous tutorials.

idfirstNamelastNameage
1JohnSmith21
2PatrickCasey26
3SamAdams19
4MikeGarciaNULL
5PatrickDumont21

Min and Max

These functions are very straightforward.

The “min” function returns the smallest value in a column, and the “max” returns the largest value in a column.

SELECT MIN(age) FROM student_info;
-- Output: 19
SELECT MAX(age) FROM student_info;
-- Output: 26

We have students with the ages of 21, 26, 19, NULL, and 21. NULL is empty. Therefore the smallest is 19 and the largest 26.

Average

The “average” function does what it says.

This function returns the average value from a selected column.

Below is an example.

SELECT AVG(age) FROM student_info;
-- Output: 21

The average can be found by adding up all numbers and then dividing by the count of numbers.

Sum

The “sum” function returns the total sum in a column.

The following is an example of “sum”.

SELECT SUM(age) FROM student_info;
-- Output: 87

The ages are 21, 26, 19, NULL, and 21. NULL is empty. We add up all numbers and get the total number of 87.

Count

The “count” function the number of elements in a column.

Below is an example.

SELECT COUNT(age) FROM student_info;
-- Output: 4

There are 5 cells in the “age” column. But NULL refers to an empty cell. Therefore, the count of all ages is 4.


Next: SQL Operators