SQL QUERIES-6
Aggregated Data Using the Group
Functions
What Are Group/AGGREGATE
Functions?
• Group functions operate on sets of rows to give one
result per group.
EMPLOYEES
Maximum salary in
EMPLOYEES table
…
Types of Group Functions
– AVG
– COUNT
– MAX
– MIN
– SUM Group
functions
SELECT column_name, aggregate_function(column_name) FROM table_name WHERE
column_name operator value GROUP BY column_name;
SQL AGGREGATE FUNCTIONS
• SQL aggregate functions return a single value, calculated from
values in a column.Useful aggregate functions:
• AVG() - Returns the average value
• COUNT() - Returns the number of rows
• MAX() - Returns the largest value
• MIN() - Returns the smallest value
• SUM() - Returns the sum
Demo Database
• Consider following Emp table
eid name age salary
401 Anu 22 9000
402 Shane 29 8000
403 Rohan 34 6000
404 Scott 44 10000
405 Tiger 35 8000
• 1) AVG()
• Average returns average value after calculating
from values in a numeric column.
Its general Syntax is,
• SELECT AVG(column_name) from table_name;
• SQL query to find average of salary will be,
• SELECT avg(sal) from Emp;
SELECT round(avg(sal)) from emp
• 2) COUNT()
• Count returns the number of rows present in the
table either based on some condition or without
condition.
SELECT COUNT(column_name) from table-name;
• SELECT COUNT(ename) from Emp where sal >
2000;
• SELECT COUNT(distinct salary) from emp;
• 3) MAX()
• MAX function returns maximum value from selected
column of the table.
Syntax of MAX function is,
• SELECT MAX(column_name) from table-name;
SELECT MAX(sal) from emp;
4.MIN()
• MIN function returns minimum value from a
selected column of the table.
• SELECT MIN(column_name) from table-name;
• SELECT MIN(sal) from emp;
5.SUM()
• SUM function returns total sum of a selected
columns numeric values.
• SELECT SUM(column_name) from table-name;
• SQL query to find sum of salaries will be,
SELECT SUM(sal) from emp;
6. UPPER()
• SELECT UPPER(column_name) from table-name;
• SELECT UPPER(ename) from emp;
7.LOWER()
• SELECT LOWER(column_name) from table-name;
• SELECT LOWER(ename) from emp;
8. SUBSTR()
• SELECT substr(column_name, start, length) from
table-name;
• SQL query will be,
• select substr(ename,2,2) from emp;
9.ROUND()
• ROUND function is used to round a numeric field to
number of nearest integer. It is used on Decimal point
values. Syntax of Round function is,
• SELECT ROUND(column_name, decimals) from table-
name;
• SQL query is,
• SELECT ROUND(sal) from emp;
select round(avg(sal),3) from emp;