SQL Functions
SQL Functions:
Aggregate Functions:
In SQL, there are several aggregate functions that allow you to perform calculations on set of values.
These functions operate on group of rows and return a single value.
- SUM():
SUM functions returns the sum of all values.
Syntax:
SELECT SUM(column_name)
From table_name;
Example 1:
Find the total salary of all employees from Each Department:
SELECT Dept_ID, SUM(Salary)
From Employee
GROUP BY Dept_ID;
Use an alias:
Give a summarized Column a name by using AS keyword.
SELECT SUM(Salary) As TotalSalary
From Employee;
COUNT() :
This function returns the number of rows that matches the specified condition.
Syntax:
SELECT COUNT(Column_name) From table_name;
Example:
SELECT COUNT(EmpID) As NumberOfEmployees
From Employee;
Example 2:
Find the number of employee where salary is higher than 20000
SELECT COUNT(EmpID)
From Employee
Where salary > 20000;
MAX() AND MIN():
MAX() function returns the largest value of selected column
MIN() function returns the smallest value of selected column.
Syntax for Max():
SELECT MAX(Column_name)
From table_name;
Example:
SELECT MAX(Salary)
From Employee;
Syntax for MIN():
SELECT MIN(Column_name)
From table_name;
Example:
SELECT MIN(Salary)
From Employee;
AVG():
This function returns the average value of numeric column.
Syntax:
SELECT AVG(Column_name)
FROM table_name;
Example:
SELECT AVG(salary)
FROM Employee;
Use an alias:
SELECT AVG(salary) as AveragePrice
From Employee;