SlideShare a Scribd company logo
AGGREGATE FUNCTIONS
Prof. Sin-Min Lee
Surya Bhagvat
CS 157A – Fall 2005
Aggregate Functions
 What is an aggregate function?
An aggregate function summarizes the results
of an expression over a number of rows,
returning a single value. The general syntax for
most of the aggregate functions is as follows:
aggregate_function ([DISTINCT|ALL]
expression)
Commonly used Aggregate
functions
Some of the commonly used aggregate functions
are :
• SUM
• COUNT
• AVG
• MIN
• MAX
Examples
Consider the following Employee table:
EMPLOYEE ( EMP_ID, NAME, DEPT_NAME, SALARY)
CREATE TABLE EMPLOYEE
(
EMP_ID NUMBER,
NAME VARCHAR2(50),
DEPT_NAME VARCHAR2(50),
SALARY NUMBER
);
Employee Table (Contd….)
Run the following script to insert the records in the table
INSERT INTO EMPLOYEE VALUES (100,'ABC','ENG',50000);
INSERT INTO EMPLOYEE VALUES (101,'DEF','ENG',60000);
INSERT INTO EMPLOYEE VALUES (102,'GHI','PS',50000);
INSERT INTO EMPLOYEE VALUES (103,'JKL','PS',70000);
INSERT INTO EMPLOYEE VALUES (104,'MNO','SALES',75000);
INSERT INTO EMPLOYEE VALUES (105,'PQR','MKTG',70000);
INSERT INTO EMPLOYEE VALUES (106,‘STU','SALES',null);
COMMIT;
Select on Employee Table
After the insert when we query the Employee table we get the
following results:
Select * from Employee;
Performing SUM
Query 1: To find the sum of all salaries in the organization:
SELECT SUM(SALARY) FROM EMPLOYEE;
375000
Query 2: To find the sum of the salaries grouped by dept
SELECT SUM(SALARY) FROM EMPLOYEE GROUP BY
DEPT_NAME
SUM (Continued)
If we take a look at the previous query the information won’t
tell us what’s the sum for a particular department. So to include that
information we add DEPT_NAME in the SELECT
SELECT DEPT_NAME,SUM(SALARY) FROM EMPLOYEE
GROUP BY DEPT_NAME;
SUM (Continued…..)
The query in the previous slide lists the information for all the
departments. What if we want the information to be restricted only
for a particular department like Engg
Is this query correct?
SELECT DEPT_NAME,SUM(SALARY) FROM EMPLOYEE
GROUP BY
DEPT_NAME
WHERE DEPT_NAME = 'ENG';
SUM (Continued….)
No, the query would result in the sql error (in Oracle)
ORA-00933: SQL Command not properly ended
Remember : If we use the aggregate functions then you cannot use
the WHERE clause. In order to get the result what we need to use is
the HAVING clause. So the query would be
SELECT DEPT_NAME,SUM(SALARY) FROM EMPLOYEE
GROUP BY
DEPT_NAME
HAVING DEPT_NAME = 'ENG';
AVG Function
Query 1: If we want to calculate the AVG of all the salaries in
the organization the SQL would be
SELECT AVG(SALARY) FROM EMPLOYEE
62,500
Is this what we expect????
Employee table has 7 records and the salaries are
50,000+60,000+50,000+70,000+75,000+70,000+null/7 = 53571
But we obtained 62500 from the query? Why is this so????
AVG (Continued….)
Remember : COUNT(*) is the only function which won’t ignore
Nulls. Other functions like SUM,AVG,MIN,MAX they ignore
Nulls. What it means is in the previous query the salary value for
a particular employee was NULL. So the query
SELECT AVG(SALARY) FROM EMPLOYEE
would ignore nulls and the way the average is calculated then would
be
50,000+60,000+50,000+70,000+75,000+70,000/6 = 62500
AVG (Continued….)
From the information given in the previous slide what do you think
would be the output of the following query
Select COUNT(*),COUNT(SALARY) FROM EMPLOYEE;
It would be
COUNT(*) COUNT(SALARY)
7 6
Because COUNT(*) is not going to ignore the Nulls in the result
whereas COUNT(SALARY) is going to ignore the Nulls.
AVG (Continued…..)
SELECT student_name,avg(mark) FROM student,enrolment
WHERE student.student_id=enrolment.student_id;
Which one of the following is correct for the query?
(a) The query is not legal
(b) The query retrieves for each student enrolled,his/her name and their
average mark
(c) The query retrieves for each student enrolled,his/her name and the clas
average mark
(d) The query retrieves for each student enrolled,his/her name and the
mark in each subject
Is the answer (a) or (b)??????
AVG (Continued….)
If option 1 is not given then the correct answer would be option 2.
//Script begin
Drop table student;
Drop table enrolment;
create table Student
(student_name varchar2(100),
student_id varchar2(50)
);
create table enrolment
(student_id varchar2(50),
mark number);
AVG (Continued….)
//Script Continued
insert into student values ('A','1');
insert into student values ('B','2');
insert into student values ('C','3');
insert into enrolment values ('1',10);
insert into enrolment values ('1',20);
insert into enrolment values ('1',30);
insert into enrolment values ('2',40);
insert into enrolment values ('2',50);
insert into enrolment values ('2',60);
insert into enrolment values ('3',70);
insert into enrolment values ('3',60);
insert into enrolment values ('3',50);
commit;
AVG (Continued….)
If we try to execute the query given in the question
SELECT student_name,avg(mark) FROM student,enrolment
WHERE student.student_id=enrolment.student_id;
We would get the following error in Oracle
ORA-00937:not a single-group group function
Why is it so????
AVG (Continued….)
Remember : When we use any of the aggregate functions in SQL
all the columns listed in the SELECT need to be part of the
GROUP BY Clause. In the previous SQL
SELECT student_name,avg(mark) FROM student,enrolment
WHERE student.student_id=enrolment.student_id;
student_name, avg(mark) are the columns included in the select.
avg is the aggregate function. So if we leave that one out then
the column which needs to part of the group by clause would be
student_name.
AVG (Final SQL)
The final SQL then would be
SELECT student_name,avg(mark)
FROM student,enrolment
WHERE student.student_id=enrolment.student_id
group by student_name;
Which would give out the desired output
Using MIN AND MAX
Query 1: To find the minimum salary within a particular
department
SELECT MIN(SALARY),NAME FROM EMPLOYEE
GROUP BY NAME;
Query 2: To find the maximum salary within a particular
department
SELECT MAX(SALARY),NAME FROM EMPLOYEE
GROUP BY NAME;

More Related Content

What's hot

Create table
Create tableCreate table
Create table
Nitesh Singh
 
Interface in java
Interface in javaInterface in java
Interface in java
PhD Research Scholar
 
SQL Joins.pptx
SQL Joins.pptxSQL Joins.pptx
SQL Joins.pptx
Ankit Rai
 
SQL Functions
SQL FunctionsSQL Functions
SQL Functions
ammarbrohi
 
introdution to SQL and SQL functions
introdution to SQL and SQL functionsintrodution to SQL and SQL functions
introdution to SQL and SQL functions
farwa waqar
 
DATABASE CONSTRAINTS
DATABASE CONSTRAINTSDATABASE CONSTRAINTS
DATABASE CONSTRAINTS
sunanditaAnand
 
Sql queries presentation
Sql queries presentationSql queries presentation
Sql queries presentation
NITISH KUMAR
 
Types Of Join In Sql Server - Join With Example In Sql Server
Types Of Join In Sql Server - Join With Example In Sql ServerTypes Of Join In Sql Server - Join With Example In Sql Server
Types Of Join In Sql Server - Join With Example In Sql Server
programmings guru
 
Nested Queries Lecture
Nested Queries LectureNested Queries Lecture
Nested Queries Lecture
Felipe Costa
 
SQL Queries
SQL QueriesSQL Queries
SQL Queries
Nilt1234
 
SQL Basics
SQL BasicsSQL Basics
SQL Basics
Hammad Rasheed
 
SQL
SQLSQL
Java Exception handling
Java Exception handlingJava Exception handling
Java Exception handling
kamal kotecha
 
Introduction of sql server indexing
Introduction of sql server indexingIntroduction of sql server indexing
Introduction of sql server indexing
Mahabubur Rahaman
 
joins in database
 joins in database joins in database
joins in database
Sultan Arshad
 
Introduction to SQL
Introduction to SQLIntroduction to SQL
Introduction to SQL
Ehsan Hamzei
 

What's hot (20)

Create table
Create tableCreate table
Create table
 
Interface in java
Interface in javaInterface in java
Interface in java
 
SQL Joins.pptx
SQL Joins.pptxSQL Joins.pptx
SQL Joins.pptx
 
SQL Views
SQL ViewsSQL Views
SQL Views
 
SQL Functions
SQL FunctionsSQL Functions
SQL Functions
 
Sql select
Sql select Sql select
Sql select
 
introdution to SQL and SQL functions
introdution to SQL and SQL functionsintrodution to SQL and SQL functions
introdution to SQL and SQL functions
 
DATABASE CONSTRAINTS
DATABASE CONSTRAINTSDATABASE CONSTRAINTS
DATABASE CONSTRAINTS
 
Sql queries presentation
Sql queries presentationSql queries presentation
Sql queries presentation
 
Types Of Join In Sql Server - Join With Example In Sql Server
Types Of Join In Sql Server - Join With Example In Sql ServerTypes Of Join In Sql Server - Join With Example In Sql Server
Types Of Join In Sql Server - Join With Example In Sql Server
 
Nested Queries Lecture
Nested Queries LectureNested Queries Lecture
Nested Queries Lecture
 
SQL Queries
SQL QueriesSQL Queries
SQL Queries
 
SQL Basics
SQL BasicsSQL Basics
SQL Basics
 
Mysql joins
Mysql joinsMysql joins
Mysql joins
 
SQL
SQLSQL
SQL
 
Set operators
Set  operatorsSet  operators
Set operators
 
Java Exception handling
Java Exception handlingJava Exception handling
Java Exception handling
 
Introduction of sql server indexing
Introduction of sql server indexingIntroduction of sql server indexing
Introduction of sql server indexing
 
joins in database
 joins in database joins in database
joins in database
 
Introduction to SQL
Introduction to SQLIntroduction to SQL
Introduction to SQL
 

Viewers also liked

Aggregate Functions,Final
Aggregate Functions,FinalAggregate Functions,Final
Aggregate Functions,Final
mukesh24pandey
 
Agreggates i
Agreggates iAgreggates i
Agreggates i
Claudia Gomez
 
Aggregating Data Using Group Functions
Aggregating Data Using Group FunctionsAggregating Data Using Group Functions
Aggregating Data Using Group Functions
Salman Memon
 
Aggregate Function - Database
Aggregate Function - DatabaseAggregate Function - Database
Aggregate Function - Database
Shahadat153031
 
SQL JOIN
SQL JOINSQL JOIN
SQL JOIN
Ritwik Das
 
Structured Query Language (SQL) - Lecture 5 - Introduction to Databases (1007...
Structured Query Language (SQL) - Lecture 5 - Introduction to Databases (1007...Structured Query Language (SQL) - Lecture 5 - Introduction to Databases (1007...
Structured Query Language (SQL) - Lecture 5 - Introduction to Databases (1007...
Beat Signer
 
Consultas de tablas con comando de SQL
Consultas de tablas  con comando de SQLConsultas de tablas  con comando de SQL
Consultas de tablas con comando de SQL
Yarquiri Claudio
 
Ejercicios sql
Ejercicios sqlEjercicios sql
Ejercicios sql
Mauro Jiménez
 
Cellular Telephone Networks 2008
Cellular Telephone Networks 2008Cellular Telephone Networks 2008
Cellular Telephone Networks 2008
Francisco Villegas
 
namecard
namecardnamecard
namecard? ?
 
Bases de Datos Cap-V SQL: Manipulación de datos
Bases de Datos Cap-V SQL: Manipulación de datosBases de Datos Cap-V SQL: Manipulación de datos
Bases de Datos Cap-V SQL: Manipulación de datos
Videoconferencias UTPL
 
sql statement
sql statementsql statement
sql statement
zx25 zx25
 
Complete Sql Server querries
Complete Sql Server querriesComplete Sql Server querries
Complete Sql Server querriesIbrahim Jutt
 
SQL querys in detail || Sql query slides
SQL querys in detail || Sql query slidesSQL querys in detail || Sql query slides
SQL querys in detail || Sql query slides
gourav kottawar
 
Sql Basics And Advanced
Sql Basics And AdvancedSql Basics And Advanced
Sql Basics And Advanced
rainynovember12
 
Cellular Telephone Systems
Cellular Telephone SystemsCellular Telephone Systems
Cellular Telephone Systems
Shantanu Krishna
 
PostgreSQL - Lección 4 - Usando funciones para manipular grupos de datos
PostgreSQL - Lección 4 - Usando funciones para manipular grupos de datosPostgreSQL - Lección 4 - Usando funciones para manipular grupos de datos
PostgreSQL - Lección 4 - Usando funciones para manipular grupos de datosNicola Strappazzon C.
 

Viewers also liked (20)

Aggregate Functions,Final
Aggregate Functions,FinalAggregate Functions,Final
Aggregate Functions,Final
 
Agreggates i
Agreggates iAgreggates i
Agreggates i
 
Aggregating Data Using Group Functions
Aggregating Data Using Group FunctionsAggregating Data Using Group Functions
Aggregating Data Using Group Functions
 
Aggregate Function - Database
Aggregate Function - DatabaseAggregate Function - Database
Aggregate Function - Database
 
SQL JOIN
SQL JOINSQL JOIN
SQL JOIN
 
Structured Query Language (SQL) - Lecture 5 - Introduction to Databases (1007...
Structured Query Language (SQL) - Lecture 5 - Introduction to Databases (1007...Structured Query Language (SQL) - Lecture 5 - Introduction to Databases (1007...
Structured Query Language (SQL) - Lecture 5 - Introduction to Databases (1007...
 
consultas en sql server
consultas en sql serverconsultas en sql server
consultas en sql server
 
Consultas de tablas con comando de SQL
Consultas de tablas  con comando de SQLConsultas de tablas  con comando de SQL
Consultas de tablas con comando de SQL
 
Ejercicios sql
Ejercicios sqlEjercicios sql
Ejercicios sql
 
Cellular Telephone Networks 2008
Cellular Telephone Networks 2008Cellular Telephone Networks 2008
Cellular Telephone Networks 2008
 
namecard
namecardnamecard
namecard
 
Bases de Datos Cap-V SQL: Manipulación de datos
Bases de Datos Cap-V SQL: Manipulación de datosBases de Datos Cap-V SQL: Manipulación de datos
Bases de Datos Cap-V SQL: Manipulación de datos
 
sql statement
sql statementsql statement
sql statement
 
Complete Sql Server querries
Complete Sql Server querriesComplete Sql Server querries
Complete Sql Server querries
 
SQL BASIC QUERIES
SQL  BASIC QUERIES SQL  BASIC QUERIES
SQL BASIC QUERIES
 
SQL querys in detail || Sql query slides
SQL querys in detail || Sql query slidesSQL querys in detail || Sql query slides
SQL querys in detail || Sql query slides
 
Sql Basics And Advanced
Sql Basics And AdvancedSql Basics And Advanced
Sql Basics And Advanced
 
Cellular Telephone Systems
Cellular Telephone SystemsCellular Telephone Systems
Cellular Telephone Systems
 
Ch 17
Ch 17Ch 17
Ch 17
 
PostgreSQL - Lección 4 - Usando funciones para manipular grupos de datos
PostgreSQL - Lección 4 - Usando funciones para manipular grupos de datosPostgreSQL - Lección 4 - Usando funciones para manipular grupos de datos
PostgreSQL - Lección 4 - Usando funciones para manipular grupos de datos
 

Similar to Aggregate functions

MYSQL Aggregate Functions
MYSQL Aggregate FunctionsMYSQL Aggregate Functions
MYSQL Aggregate Functions
Leroy Blair
 
Aggregate functions
Aggregate functionsAggregate functions
Aggregate functions
Soumyajit Dutta
 
PHP mysql Aggregate functions
PHP mysql Aggregate functionsPHP mysql Aggregate functions
PHP mysql Aggregate functions
Mudasir Syed
 
Dump Answers
Dump AnswersDump Answers
Dump Answers
sailesh kushwaha
 
Les06
Les06Les06
Les06 (using subqueries to solve queries)
Les06 (using subqueries to solve queries)Les06 (using subqueries to solve queries)
Les06 (using subqueries to solve queries)
Achmad Solichin
 
DOODB_LAB.pptx
DOODB_LAB.pptxDOODB_LAB.pptx
DOODB_LAB.pptx
FilestreamFilestream
 
Oracle OCP 1Z0-007题库
Oracle OCP 1Z0-007题库Oracle OCP 1Z0-007题库
Oracle OCP 1Z0-007题库
renguzi
 
Complex Queries using MYSQL00123211.pptx
Complex Queries using MYSQL00123211.pptxComplex Queries using MYSQL00123211.pptx
Complex Queries using MYSQL00123211.pptx
metriohanzel
 
Plsql task answers
Plsql task answersPlsql task answers
Plsql task answersNawaz Sk
 
12. Basic SQL Queries (2).pptx
12. Basic SQL Queries  (2).pptx12. Basic SQL Queries  (2).pptx
12. Basic SQL Queries (2).pptx
SabrinaShanta2
 
Les04
Les04Les04
MSCD650 Final Exam feedback FormMSCD650 Final Exam Grading For.docx
MSCD650 Final Exam feedback FormMSCD650 Final Exam Grading For.docxMSCD650 Final Exam feedback FormMSCD650 Final Exam Grading For.docx
MSCD650 Final Exam feedback FormMSCD650 Final Exam Grading For.docx
gilpinleeanna
 
Les04
Les04Les04
Oracle - Program with PL/SQL - Lession 09
Oracle - Program with PL/SQL - Lession 09Oracle - Program with PL/SQL - Lession 09
Oracle - Program with PL/SQL - Lession 09
Thuan Nguyen
 
Plsql lab mannual
Plsql lab mannualPlsql lab mannual
Plsql lab mannual
Harish Khodke
 
Structured query language functions
Structured query language functionsStructured query language functions
Structured query language functions
Vineeta Garg
 

Similar to Aggregate functions (20)

MYSQL Aggregate Functions
MYSQL Aggregate FunctionsMYSQL Aggregate Functions
MYSQL Aggregate Functions
 
Aggregate functions
Aggregate functionsAggregate functions
Aggregate functions
 
PHP mysql Aggregate functions
PHP mysql Aggregate functionsPHP mysql Aggregate functions
PHP mysql Aggregate functions
 
Dump Answers
Dump AnswersDump Answers
Dump Answers
 
Les06
Les06Les06
Les06
 
Les06 (using subqueries to solve queries)
Les06 (using subqueries to solve queries)Les06 (using subqueries to solve queries)
Les06 (using subqueries to solve queries)
 
DOODB_LAB.pptx
DOODB_LAB.pptxDOODB_LAB.pptx
DOODB_LAB.pptx
 
Oracle OCP 1Z0-007题库
Oracle OCP 1Z0-007题库Oracle OCP 1Z0-007题库
Oracle OCP 1Z0-007题库
 
Les06
Les06Les06
Les06
 
Complex Queries using MYSQL00123211.pptx
Complex Queries using MYSQL00123211.pptxComplex Queries using MYSQL00123211.pptx
Complex Queries using MYSQL00123211.pptx
 
Clauses
ClausesClauses
Clauses
 
Plsql task answers
Plsql task answersPlsql task answers
Plsql task answers
 
SQl
SQlSQl
SQl
 
12. Basic SQL Queries (2).pptx
12. Basic SQL Queries  (2).pptx12. Basic SQL Queries  (2).pptx
12. Basic SQL Queries (2).pptx
 
Les04
Les04Les04
Les04
 
MSCD650 Final Exam feedback FormMSCD650 Final Exam Grading For.docx
MSCD650 Final Exam feedback FormMSCD650 Final Exam Grading For.docxMSCD650 Final Exam feedback FormMSCD650 Final Exam Grading For.docx
MSCD650 Final Exam feedback FormMSCD650 Final Exam Grading For.docx
 
Les04
Les04Les04
Les04
 
Oracle - Program with PL/SQL - Lession 09
Oracle - Program with PL/SQL - Lession 09Oracle - Program with PL/SQL - Lession 09
Oracle - Program with PL/SQL - Lession 09
 
Plsql lab mannual
Plsql lab mannualPlsql lab mannual
Plsql lab mannual
 
Structured query language functions
Structured query language functionsStructured query language functions
Structured query language functions
 

Recently uploaded

The approach at University of Liverpool.pptx
The approach at University of Liverpool.pptxThe approach at University of Liverpool.pptx
The approach at University of Liverpool.pptx
Jisc
 
Model Attribute Check Company Auto Property
Model Attribute  Check Company Auto PropertyModel Attribute  Check Company Auto Property
Model Attribute Check Company Auto Property
Celine George
 
Lapbook sobre os Regimes Totalitários.pdf
Lapbook sobre os Regimes Totalitários.pdfLapbook sobre os Regimes Totalitários.pdf
Lapbook sobre os Regimes Totalitários.pdf
Jean Carlos Nunes Paixão
 
How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...
Jisc
 
Synthetic Fiber Construction in lab .pptx
Synthetic Fiber Construction in lab .pptxSynthetic Fiber Construction in lab .pptx
Synthetic Fiber Construction in lab .pptx
Pavel ( NSTU)
 
Chapter 3 - Islamic Banking Products and Services.pptx
Chapter 3 - Islamic Banking Products and Services.pptxChapter 3 - Islamic Banking Products and Services.pptx
Chapter 3 - Islamic Banking Products and Services.pptx
Mohd Adib Abd Muin, Senior Lecturer at Universiti Utara Malaysia
 
Introduction to AI for Nonprofits with Tapp Network
Introduction to AI for Nonprofits with Tapp NetworkIntroduction to AI for Nonprofits with Tapp Network
Introduction to AI for Nonprofits with Tapp Network
TechSoup
 
Instructions for Submissions thorugh G- Classroom.pptx
Instructions for Submissions thorugh G- Classroom.pptxInstructions for Submissions thorugh G- Classroom.pptx
Instructions for Submissions thorugh G- Classroom.pptx
Jheel Barad
 
678020731-Sumas-y-Restas-Para-Colorear.pdf
678020731-Sumas-y-Restas-Para-Colorear.pdf678020731-Sumas-y-Restas-Para-Colorear.pdf
678020731-Sumas-y-Restas-Para-Colorear.pdf
CarlosHernanMontoyab2
 
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdf
Welcome to TechSoup   New Member Orientation and Q&A (May 2024).pdfWelcome to TechSoup   New Member Orientation and Q&A (May 2024).pdf
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdf
TechSoup
 
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
MysoreMuleSoftMeetup
 
Acetabularia Information For Class 9 .docx
Acetabularia Information For Class 9  .docxAcetabularia Information For Class 9  .docx
Acetabularia Information For Class 9 .docx
vaibhavrinwa19
 
CACJapan - GROUP Presentation 1- Wk 4.pdf
CACJapan - GROUP Presentation 1- Wk 4.pdfCACJapan - GROUP Presentation 1- Wk 4.pdf
CACJapan - GROUP Presentation 1- Wk 4.pdf
camakaiclarkmusic
 
Thesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.pptThesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.ppt
EverAndrsGuerraGuerr
 
Language Across the Curriculm LAC B.Ed.
Language Across the  Curriculm LAC B.Ed.Language Across the  Curriculm LAC B.Ed.
Language Across the Curriculm LAC B.Ed.
Atul Kumar Singh
 
Guidance_and_Counselling.pdf B.Ed. 4th Semester
Guidance_and_Counselling.pdf B.Ed. 4th SemesterGuidance_and_Counselling.pdf B.Ed. 4th Semester
Guidance_and_Counselling.pdf B.Ed. 4th Semester
Atul Kumar Singh
 
Sha'Carri Richardson Presentation 202345
Sha'Carri Richardson Presentation 202345Sha'Carri Richardson Presentation 202345
Sha'Carri Richardson Presentation 202345
beazzy04
 
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXXPhrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
MIRIAMSALINAS13
 
Operation Blue Star - Saka Neela Tara
Operation Blue Star   -  Saka Neela TaraOperation Blue Star   -  Saka Neela Tara
Operation Blue Star - Saka Neela Tara
Balvir Singh
 
TESDA TM1 REVIEWER FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
TESDA TM1 REVIEWER  FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...TESDA TM1 REVIEWER  FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
TESDA TM1 REVIEWER FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
EugeneSaldivar
 

Recently uploaded (20)

The approach at University of Liverpool.pptx
The approach at University of Liverpool.pptxThe approach at University of Liverpool.pptx
The approach at University of Liverpool.pptx
 
Model Attribute Check Company Auto Property
Model Attribute  Check Company Auto PropertyModel Attribute  Check Company Auto Property
Model Attribute Check Company Auto Property
 
Lapbook sobre os Regimes Totalitários.pdf
Lapbook sobre os Regimes Totalitários.pdfLapbook sobre os Regimes Totalitários.pdf
Lapbook sobre os Regimes Totalitários.pdf
 
How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...
 
Synthetic Fiber Construction in lab .pptx
Synthetic Fiber Construction in lab .pptxSynthetic Fiber Construction in lab .pptx
Synthetic Fiber Construction in lab .pptx
 
Chapter 3 - Islamic Banking Products and Services.pptx
Chapter 3 - Islamic Banking Products and Services.pptxChapter 3 - Islamic Banking Products and Services.pptx
Chapter 3 - Islamic Banking Products and Services.pptx
 
Introduction to AI for Nonprofits with Tapp Network
Introduction to AI for Nonprofits with Tapp NetworkIntroduction to AI for Nonprofits with Tapp Network
Introduction to AI for Nonprofits with Tapp Network
 
Instructions for Submissions thorugh G- Classroom.pptx
Instructions for Submissions thorugh G- Classroom.pptxInstructions for Submissions thorugh G- Classroom.pptx
Instructions for Submissions thorugh G- Classroom.pptx
 
678020731-Sumas-y-Restas-Para-Colorear.pdf
678020731-Sumas-y-Restas-Para-Colorear.pdf678020731-Sumas-y-Restas-Para-Colorear.pdf
678020731-Sumas-y-Restas-Para-Colorear.pdf
 
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdf
Welcome to TechSoup   New Member Orientation and Q&A (May 2024).pdfWelcome to TechSoup   New Member Orientation and Q&A (May 2024).pdf
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdf
 
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
 
Acetabularia Information For Class 9 .docx
Acetabularia Information For Class 9  .docxAcetabularia Information For Class 9  .docx
Acetabularia Information For Class 9 .docx
 
CACJapan - GROUP Presentation 1- Wk 4.pdf
CACJapan - GROUP Presentation 1- Wk 4.pdfCACJapan - GROUP Presentation 1- Wk 4.pdf
CACJapan - GROUP Presentation 1- Wk 4.pdf
 
Thesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.pptThesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.ppt
 
Language Across the Curriculm LAC B.Ed.
Language Across the  Curriculm LAC B.Ed.Language Across the  Curriculm LAC B.Ed.
Language Across the Curriculm LAC B.Ed.
 
Guidance_and_Counselling.pdf B.Ed. 4th Semester
Guidance_and_Counselling.pdf B.Ed. 4th SemesterGuidance_and_Counselling.pdf B.Ed. 4th Semester
Guidance_and_Counselling.pdf B.Ed. 4th Semester
 
Sha'Carri Richardson Presentation 202345
Sha'Carri Richardson Presentation 202345Sha'Carri Richardson Presentation 202345
Sha'Carri Richardson Presentation 202345
 
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXXPhrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
 
Operation Blue Star - Saka Neela Tara
Operation Blue Star   -  Saka Neela TaraOperation Blue Star   -  Saka Neela Tara
Operation Blue Star - Saka Neela Tara
 
TESDA TM1 REVIEWER FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
TESDA TM1 REVIEWER  FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...TESDA TM1 REVIEWER  FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
TESDA TM1 REVIEWER FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
 

Aggregate functions

  • 1. AGGREGATE FUNCTIONS Prof. Sin-Min Lee Surya Bhagvat CS 157A – Fall 2005
  • 2. Aggregate Functions  What is an aggregate function? An aggregate function summarizes the results of an expression over a number of rows, returning a single value. The general syntax for most of the aggregate functions is as follows: aggregate_function ([DISTINCT|ALL] expression)
  • 3. Commonly used Aggregate functions Some of the commonly used aggregate functions are : • SUM • COUNT • AVG • MIN • MAX
  • 4. Examples Consider the following Employee table: EMPLOYEE ( EMP_ID, NAME, DEPT_NAME, SALARY) CREATE TABLE EMPLOYEE ( EMP_ID NUMBER, NAME VARCHAR2(50), DEPT_NAME VARCHAR2(50), SALARY NUMBER );
  • 5. Employee Table (Contd….) Run the following script to insert the records in the table INSERT INTO EMPLOYEE VALUES (100,'ABC','ENG',50000); INSERT INTO EMPLOYEE VALUES (101,'DEF','ENG',60000); INSERT INTO EMPLOYEE VALUES (102,'GHI','PS',50000); INSERT INTO EMPLOYEE VALUES (103,'JKL','PS',70000); INSERT INTO EMPLOYEE VALUES (104,'MNO','SALES',75000); INSERT INTO EMPLOYEE VALUES (105,'PQR','MKTG',70000); INSERT INTO EMPLOYEE VALUES (106,‘STU','SALES',null); COMMIT;
  • 6. Select on Employee Table After the insert when we query the Employee table we get the following results: Select * from Employee;
  • 7. Performing SUM Query 1: To find the sum of all salaries in the organization: SELECT SUM(SALARY) FROM EMPLOYEE; 375000 Query 2: To find the sum of the salaries grouped by dept SELECT SUM(SALARY) FROM EMPLOYEE GROUP BY DEPT_NAME
  • 8. SUM (Continued) If we take a look at the previous query the information won’t tell us what’s the sum for a particular department. So to include that information we add DEPT_NAME in the SELECT SELECT DEPT_NAME,SUM(SALARY) FROM EMPLOYEE GROUP BY DEPT_NAME;
  • 9. SUM (Continued…..) The query in the previous slide lists the information for all the departments. What if we want the information to be restricted only for a particular department like Engg Is this query correct? SELECT DEPT_NAME,SUM(SALARY) FROM EMPLOYEE GROUP BY DEPT_NAME WHERE DEPT_NAME = 'ENG';
  • 10. SUM (Continued….) No, the query would result in the sql error (in Oracle) ORA-00933: SQL Command not properly ended Remember : If we use the aggregate functions then you cannot use the WHERE clause. In order to get the result what we need to use is the HAVING clause. So the query would be SELECT DEPT_NAME,SUM(SALARY) FROM EMPLOYEE GROUP BY DEPT_NAME HAVING DEPT_NAME = 'ENG';
  • 11. AVG Function Query 1: If we want to calculate the AVG of all the salaries in the organization the SQL would be SELECT AVG(SALARY) FROM EMPLOYEE 62,500 Is this what we expect???? Employee table has 7 records and the salaries are 50,000+60,000+50,000+70,000+75,000+70,000+null/7 = 53571 But we obtained 62500 from the query? Why is this so????
  • 12. AVG (Continued….) Remember : COUNT(*) is the only function which won’t ignore Nulls. Other functions like SUM,AVG,MIN,MAX they ignore Nulls. What it means is in the previous query the salary value for a particular employee was NULL. So the query SELECT AVG(SALARY) FROM EMPLOYEE would ignore nulls and the way the average is calculated then would be 50,000+60,000+50,000+70,000+75,000+70,000/6 = 62500
  • 13. AVG (Continued….) From the information given in the previous slide what do you think would be the output of the following query Select COUNT(*),COUNT(SALARY) FROM EMPLOYEE; It would be COUNT(*) COUNT(SALARY) 7 6 Because COUNT(*) is not going to ignore the Nulls in the result whereas COUNT(SALARY) is going to ignore the Nulls.
  • 14. AVG (Continued…..) SELECT student_name,avg(mark) FROM student,enrolment WHERE student.student_id=enrolment.student_id; Which one of the following is correct for the query? (a) The query is not legal (b) The query retrieves for each student enrolled,his/her name and their average mark (c) The query retrieves for each student enrolled,his/her name and the clas average mark (d) The query retrieves for each student enrolled,his/her name and the mark in each subject Is the answer (a) or (b)??????
  • 15. AVG (Continued….) If option 1 is not given then the correct answer would be option 2. //Script begin Drop table student; Drop table enrolment; create table Student (student_name varchar2(100), student_id varchar2(50) ); create table enrolment (student_id varchar2(50), mark number);
  • 16. AVG (Continued….) //Script Continued insert into student values ('A','1'); insert into student values ('B','2'); insert into student values ('C','3'); insert into enrolment values ('1',10); insert into enrolment values ('1',20); insert into enrolment values ('1',30); insert into enrolment values ('2',40); insert into enrolment values ('2',50); insert into enrolment values ('2',60); insert into enrolment values ('3',70); insert into enrolment values ('3',60); insert into enrolment values ('3',50); commit;
  • 17. AVG (Continued….) If we try to execute the query given in the question SELECT student_name,avg(mark) FROM student,enrolment WHERE student.student_id=enrolment.student_id; We would get the following error in Oracle ORA-00937:not a single-group group function Why is it so????
  • 18. AVG (Continued….) Remember : When we use any of the aggregate functions in SQL all the columns listed in the SELECT need to be part of the GROUP BY Clause. In the previous SQL SELECT student_name,avg(mark) FROM student,enrolment WHERE student.student_id=enrolment.student_id; student_name, avg(mark) are the columns included in the select. avg is the aggregate function. So if we leave that one out then the column which needs to part of the group by clause would be student_name.
  • 19. AVG (Final SQL) The final SQL then would be SELECT student_name,avg(mark) FROM student,enrolment WHERE student.student_id=enrolment.student_id group by student_name; Which would give out the desired output
  • 20. Using MIN AND MAX Query 1: To find the minimum salary within a particular department SELECT MIN(SALARY),NAME FROM EMPLOYEE GROUP BY NAME; Query 2: To find the maximum salary within a particular department SELECT MAX(SALARY),NAME FROM EMPLOYEE GROUP BY NAME;