SQL Functions


SQL has a lot of built-in functions for counting and calculations.


Function Syntax

The syntax for built-in SQL functions is:

SELECT function(column) FROM table


Original Table (used in the examples)

Name Age
Hansen, Ola 34
Svendson, Tove 45
Pettersen, Kari 19


Function AVG(column)

The AVG function returns the average value of a column in a selection. NULL values are not included in the calculation.

Example

This example returns the average age of the persons in the "Persons" table:

SELECT AVG(Age) FROM Persons

Result

32.67

Example

This example returns the average age for persons that are older than 20 years:

SELECT AVG(Age) FROM Persons where Age>20

Result

39.5


Function MAX(column)

The MAX function returns the highest value in a column. NULL values are not included in the calculation.

Example

SELECT MAX(Age) FROM Persons

Result:

45


Function MIN(column)

The MIN function returns the lowest value in a column. NULL values are not included in the calculation.

Example

SELECT MIN(Age) FROM Persons

Result:

19

Note: The MIN and MAX functions can also be used on text columns, to find the highest or lowest value in alphabetical order.


Function SUM(column)

The SUM function returns the total sum of a column in a given selection. NULL values are not included in the calculation.

Example

This example returns the sum of all ages in the "person" table:

SELECT SUM(Age) FROM Persons

Result:

98

Example

This example returns the sum of ages for persons that are more than 20 years old:

SELECT SUM(Age) FROM Persons where Age>20

Result:

79