SlideShare une entreprise Scribd logo
1  sur  20
AGGREGATE FUNCTIONS
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;

Contenu connexe

Tendances (20)

SQL Commands
SQL Commands SQL Commands
SQL Commands
 
oracle Sql constraint
oracle  Sql constraint oracle  Sql constraint
oracle Sql constraint
 
Sql select
Sql select Sql select
Sql select
 
Sql operator
Sql operatorSql operator
Sql operator
 
SQL commands
SQL commandsSQL commands
SQL commands
 
PL/SQL TRIGGERS
PL/SQL TRIGGERSPL/SQL TRIGGERS
PL/SQL TRIGGERS
 
Introduction to structured query language (sql)
Introduction to structured query language (sql)Introduction to structured query language (sql)
Introduction to structured query language (sql)
 
Chapter 4 Structured Query Language
Chapter 4 Structured Query LanguageChapter 4 Structured Query Language
Chapter 4 Structured Query Language
 
Joins in SQL
Joins in SQLJoins in SQL
Joins in SQL
 
Joins And Its Types
Joins And Its TypesJoins And Its Types
Joins And Its Types
 
SQL
SQLSQL
SQL
 
Aggregate functions in SQL.pptx
Aggregate functions in SQL.pptxAggregate functions in SQL.pptx
Aggregate functions in SQL.pptx
 
SQL Views
SQL ViewsSQL Views
SQL Views
 
Constraints In Sql
Constraints In SqlConstraints In Sql
Constraints In Sql
 
sql function(ppt)
sql function(ppt)sql function(ppt)
sql function(ppt)
 
1 - Introduction to PL/SQL
1 - Introduction to PL/SQL1 - Introduction to PL/SQL
1 - Introduction to PL/SQL
 
SQL(DDL & DML)
SQL(DDL & DML)SQL(DDL & DML)
SQL(DDL & DML)
 
Database Triggers
Database TriggersDatabase Triggers
Database Triggers
 
SQL Queries Information
SQL Queries InformationSQL Queries Information
SQL Queries Information
 
Sql and Sql commands
Sql and Sql commandsSql and Sql commands
Sql and Sql commands
 

En vedette

Sql Authorization
Sql AuthorizationSql Authorization
Sql AuthorizationFhuy
 
DBMS : Relational Algebra
DBMS : Relational Algebra DBMS : Relational Algebra
DBMS : Relational Algebra Sridhar Baithi
 
Data integrity Dbms presentation 12 cs 18
Data integrity Dbms presentation 12 cs 18Data integrity Dbms presentation 12 cs 18
Data integrity Dbms presentation 12 cs 18Engr Imran Ashraf
 
Nested Queries Lecture
Nested Queries LectureNested Queries Lecture
Nested Queries LectureFelipe Costa
 
FUNCTION DEPENDENCY AND TYPES & EXAMPLE
FUNCTION DEPENDENCY  AND TYPES & EXAMPLEFUNCTION DEPENDENCY  AND TYPES & EXAMPLE
FUNCTION DEPENDENCY AND TYPES & EXAMPLEVraj Patel
 
3 data modeling using the entity-relationship (er) model
3 data modeling using the entity-relationship (er) model3 data modeling using the entity-relationship (er) model
3 data modeling using the entity-relationship (er) modelKumar
 
Dbms ii mca-ch5-ch6-relational algebra-2013
Dbms ii mca-ch5-ch6-relational algebra-2013Dbms ii mca-ch5-ch6-relational algebra-2013
Dbms ii mca-ch5-ch6-relational algebra-2013Prosanta Ghosh
 
Enhanced Entity-Relationship (EER) Modeling
Enhanced Entity-Relationship (EER) ModelingEnhanced Entity-Relationship (EER) Modeling
Enhanced Entity-Relationship (EER) Modelingsontumax
 
Er & eer to relational mapping
Er & eer to relational mappingEr & eer to relational mapping
Er & eer to relational mappingsaurabhshertukde
 

En vedette (20)

介绍 MySQL
介绍 MySQL介绍 MySQL
介绍 MySQL
 
Commands
CommandsCommands
Commands
 
Sql Authorization
Sql AuthorizationSql Authorization
Sql Authorization
 
DBMS : Relational Algebra
DBMS : Relational Algebra DBMS : Relational Algebra
DBMS : Relational Algebra
 
From crash to testcase
From crash to testcaseFrom crash to testcase
From crash to testcase
 
Data integrity Dbms presentation 12 cs 18
Data integrity Dbms presentation 12 cs 18Data integrity Dbms presentation 12 cs 18
Data integrity Dbms presentation 12 cs 18
 
Nested Queries Lecture
Nested Queries LectureNested Queries Lecture
Nested Queries Lecture
 
FUNCTION DEPENDENCY AND TYPES & EXAMPLE
FUNCTION DEPENDENCY  AND TYPES & EXAMPLEFUNCTION DEPENDENCY  AND TYPES & EXAMPLE
FUNCTION DEPENDENCY AND TYPES & EXAMPLE
 
3 data modeling using the entity-relationship (er) model
3 data modeling using the entity-relationship (er) model3 data modeling using the entity-relationship (er) model
3 data modeling using the entity-relationship (er) model
 
Data model and entity relationship
Data model and entity relationshipData model and entity relationship
Data model and entity relationship
 
Dbms ii mca-ch5-ch6-relational algebra-2013
Dbms ii mca-ch5-ch6-relational algebra-2013Dbms ii mca-ch5-ch6-relational algebra-2013
Dbms ii mca-ch5-ch6-relational algebra-2013
 
SQL Data Manipulation
SQL Data ManipulationSQL Data Manipulation
SQL Data Manipulation
 
Enhanced Entity-Relationship (EER) Modeling
Enhanced Entity-Relationship (EER) ModelingEnhanced Entity-Relationship (EER) Modeling
Enhanced Entity-Relationship (EER) Modeling
 
T-SQL Overview
T-SQL OverviewT-SQL Overview
T-SQL Overview
 
trigger dbms
trigger dbmstrigger dbms
trigger dbms
 
SQL Views
SQL ViewsSQL Views
SQL Views
 
Er & eer to relational mapping
Er & eer to relational mappingEr & eer to relational mapping
Er & eer to relational mapping
 
ER Model in DBMS
ER Model in DBMSER Model in DBMS
ER Model in DBMS
 
Advanced DBMS presentation
Advanced DBMS presentationAdvanced DBMS presentation
Advanced DBMS presentation
 
Acid properties
Acid propertiesAcid properties
Acid properties
 

Similaire à MYSQL Aggregate Functions

Aggregate Functions,Final
Aggregate Functions,FinalAggregate Functions,Final
Aggregate Functions,Finalmukesh24pandey
 
PHP mysql Aggregate functions
PHP mysql Aggregate functionsPHP mysql Aggregate functions
PHP mysql Aggregate functionsMudasir Syed
 
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
 
Complex Queries using MYSQL00123211.pptx
Complex Queries using MYSQL00123211.pptxComplex Queries using MYSQL00123211.pptx
Complex Queries using MYSQL00123211.pptxmetriohanzel
 
Oracle OCP 1Z0-007题库
Oracle OCP 1Z0-007题库Oracle OCP 1Z0-007题库
Oracle OCP 1Z0-007题库renguzi
 
12. Basic SQL Queries (2).pptx
12. Basic SQL Queries  (2).pptx12. Basic SQL Queries  (2).pptx
12. Basic SQL Queries (2).pptxSabrinaShanta2
 
Plsql task answers
Plsql task answersPlsql task answers
Plsql task answersNawaz Sk
 
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.docxgilpinleeanna
 
Structured query language functions
Structured query language functionsStructured query language functions
Structured query language functionsVineeta Garg
 
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 09Thuan Nguyen
 
Developer Experience i TypeScript. Najbardziej ikoniczne duo
Developer Experience i TypeScript. Najbardziej ikoniczne duoDeveloper Experience i TypeScript. Najbardziej ikoniczne duo
Developer Experience i TypeScript. Najbardziej ikoniczne duoThe Software House
 

Similaire à MYSQL Aggregate Functions (20)

Aggregate Functions,Final
Aggregate Functions,FinalAggregate Functions,Final
Aggregate Functions,Final
 
PHP mysql Aggregate functions
PHP mysql Aggregate functionsPHP mysql Aggregate functions
PHP mysql Aggregate functions
 
Dump Answers
Dump AnswersDump Answers
Dump Answers
 
Clauses
ClausesClauses
Clauses
 
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
 
Complex Queries using MYSQL00123211.pptx
Complex Queries using MYSQL00123211.pptxComplex Queries using MYSQL00123211.pptx
Complex Queries using MYSQL00123211.pptx
 
Oracle OCP 1Z0-007题库
Oracle OCP 1Z0-007题库Oracle OCP 1Z0-007题库
Oracle OCP 1Z0-007题库
 
Les06
Les06Les06
Les06
 
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
 
Plsql task answers
Plsql task answersPlsql task answers
Plsql task answers
 
Les04
Les04Les04
Les04
 
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
 
Structured query language functions
Structured query language functionsStructured query language functions
Structured query language functions
 
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
 
Les04
Les04Les04
Les04
 
Developer Experience i TypeScript. Najbardziej ikoniczne duo
Developer Experience i TypeScript. Najbardziej ikoniczne duoDeveloper Experience i TypeScript. Najbardziej ikoniczne duo
Developer Experience i TypeScript. Najbardziej ikoniczne duo
 

Dernier

Python Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxPython Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxRamakrishna Reddy Bijjam
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdfQucHHunhnh
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxheathfieldcps1
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxAreebaZafar22
 
Google Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptxGoogle Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptxDr. Sarita Anand
 
How to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POSHow to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POSCeline George
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfAdmir Softic
 
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptxSKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptxAmanpreet Kaur
 
Unit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptxUnit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptxVishalSingh1417
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfagholdier
 
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptxMaritesTamaniVerdade
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxVishalSingh1417
 
Spellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please PractiseSpellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please PractiseAnaAcapella
 
FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024Elizabeth Walsh
 
SOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning PresentationSOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning Presentationcamerronhm
 
ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.MaryamAhmad92
 
Graduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - EnglishGraduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - Englishneillewis46
 
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17  How to Extend Models Using Mixin ClassesMixin Classes in Odoo 17  How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17 How to Extend Models Using Mixin ClassesCeline George
 
Single or Multiple melodic lines structure
Single or Multiple melodic lines structureSingle or Multiple melodic lines structure
Single or Multiple melodic lines structuredhanjurrannsibayan2
 
Fostering Friendships - Enhancing Social Bonds in the Classroom
Fostering Friendships - Enhancing Social Bonds  in the ClassroomFostering Friendships - Enhancing Social Bonds  in the Classroom
Fostering Friendships - Enhancing Social Bonds in the ClassroomPooky Knightsmith
 

Dernier (20)

Python Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxPython Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docx
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptx
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptx
 
Google Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptxGoogle Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptx
 
How to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POSHow to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POS
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdf
 
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptxSKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
 
Unit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptxUnit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptx
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdf
 
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptx
 
Spellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please PractiseSpellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please Practise
 
FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024
 
SOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning PresentationSOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning Presentation
 
ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.
 
Graduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - EnglishGraduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - English
 
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17  How to Extend Models Using Mixin ClassesMixin Classes in Odoo 17  How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
 
Single or Multiple melodic lines structure
Single or Multiple melodic lines structureSingle or Multiple melodic lines structure
Single or Multiple melodic lines structure
 
Fostering Friendships - Enhancing Social Bonds in the Classroom
Fostering Friendships - Enhancing Social Bonds  in the ClassroomFostering Friendships - Enhancing Social Bonds  in the Classroom
Fostering Friendships - Enhancing Social Bonds in the Classroom
 

MYSQL Aggregate Functions

  • 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;