Functions in SQL
A Function is a block of code or a set of instructions that is used to perform a specific task.
Types of Functions
- User-Defined Function (UDF)
- Built-in (Predefined) Function
Built-in functions are further divided into two types:
- Single Row Function
- Multi-Row Function
Single Row Function
A Single Row Function works on one row at a time. It takes one input from each row, executes the function, and returns one output for each row.
If a table contains n rows, the function is executed n times, and it returns n outputs.
Multi-Row Function
A Multi-Row Function takes all the input values in one shot, executes them together, and returns a single output.
Get Rishil Aman’s stories in your inbox
Join Medium for free to get updates from this writer.
If you pass n number of input values to a multi-row function, it returns only one output.
Types of Multi-Row Functions
- MAX()
- MIN()
- SUM()
- AVG()
- COUNT()
MAX()
The MAX() function is used to return the maximum value from a column.
Syntax
SELECT MAX(column_name)
FROM table_name;
Example
SELECT MAX(Salary)
FROM Employee;
MIN()
The MIN() function is used to return the minimum value from a column.
Syntax
SELECT MIN(column_name)
FROM table_name;
Example
SELECT MIN(Salary)
FROM Employee;
SUM()
The SUM() function is used to return the sum of all values in a numeric column.
Syntax
SELECT SUM(column_name)
FROM table_name;
Example
SELECT SUM(Salary)
FROM Employee;
AVG()
The AVG() function is used to return the average value of a numeric column.
Syntax
SELECT AVG(column_name)
FROM table_name;
Example
SELECT AVG(Salary)
FROM Employee;
COUNT()
The COUNT() function is used to count the number of records.
Syntax
SELECT COUNT(column_name)
FROM table_name;
or
SELECT COUNT(*)
FROM table_name;
Example
SELECT COUNT(Employee_ID)
FROM Employee;
Important Notes
- A Multi-Row Function can accept only one argument, which can be a column name or an expression.
- Along with a Multi-Row Function, we are not supposed to use any other column name in the SELECT clause.
- Multi-Row Functions ignore NULL values.
- We cannot use Multi-Row Functions in the WHERE clause.
- COUNT() is the only Multi-Row Function that can accept a string as an argument.





