SlideShare a Scribd company logo
1 of 19
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

Programming with GUTs
Programming with GUTsProgramming with GUTs
Programming with GUTsKevlin Henney
 
Forecast stock prices python
Forecast stock prices pythonForecast stock prices python
Forecast stock prices pythonUtkarsh Asthana
 
Phoenix for laravel developers
Phoenix for laravel developersPhoenix for laravel developers
Phoenix for laravel developersLuiz Messias
 
LINQ Internals - STLDODN
LINQ Internals - STLDODNLINQ Internals - STLDODN
LINQ Internals - STLDODNKeith Dahlby
 
Practical Class 12th (c++programs+sql queries and output)
Practical Class 12th (c++programs+sql queries and output) Practical Class 12th (c++programs+sql queries and output)
Practical Class 12th (c++programs+sql queries and output) Aman Deep
 
COMPUTER SCIENCE CLASS 12 PRACTICAL FILE
COMPUTER SCIENCE CLASS 12 PRACTICAL FILECOMPUTER SCIENCE CLASS 12 PRACTICAL FILE
COMPUTER SCIENCE CLASS 12 PRACTICAL FILEAnushka Rai
 
Oops practical file
Oops practical fileOops practical file
Oops practical fileAnkit Dixit
 
Print input-presentation
Print input-presentationPrint input-presentation
Print input-presentationMartin McBride
 
Tweaking the interactive grid
Tweaking the interactive gridTweaking the interactive grid
Tweaking the interactive gridRoel Hartman
 
Closure, Higher-order function in Swift
Closure, Higher-order function in SwiftClosure, Higher-order function in Swift
Closure, Higher-order function in SwiftSeongGyu Jo
 
Forms in AngularJS
Forms in AngularJSForms in AngularJS
Forms in AngularJSEyal Vardi
 
Computer Science Practical Science C++ with SQL commands
Computer Science Practical Science C++ with SQL commandsComputer Science Practical Science C++ with SQL commands
Computer Science Practical Science C++ with SQL commandsVishvjeet Yadav
 
C Programming Language Part 4
C Programming Language Part 4C Programming Language Part 4
C Programming Language Part 4Rumman Ansari
 
Chapter 8 c solution
Chapter 8 c solutionChapter 8 c solution
Chapter 8 c solutionAzhar Javed
 

What's hot (20)

Programming with GUTs
Programming with GUTsProgramming with GUTs
Programming with GUTs
 
Forecast stock prices python
Forecast stock prices pythonForecast stock prices python
Forecast stock prices python
 
Phoenix for laravel developers
Phoenix for laravel developersPhoenix for laravel developers
Phoenix for laravel developers
 
Excell vba
Excell vbaExcell vba
Excell vba
 
LINQ Internals - STLDODN
LINQ Internals - STLDODNLINQ Internals - STLDODN
LINQ Internals - STLDODN
 
Practical Class 12th (c++programs+sql queries and output)
Practical Class 12th (c++programs+sql queries and output) Practical Class 12th (c++programs+sql queries and output)
Practical Class 12th (c++programs+sql queries and output)
 
COMPUTER SCIENCE CLASS 12 PRACTICAL FILE
COMPUTER SCIENCE CLASS 12 PRACTICAL FILECOMPUTER SCIENCE CLASS 12 PRACTICAL FILE
COMPUTER SCIENCE CLASS 12 PRACTICAL FILE
 
Oops practical file
Oops practical fileOops practical file
Oops practical file
 
Neo4 J
Neo4 J Neo4 J
Neo4 J
 
Print input-presentation
Print input-presentationPrint input-presentation
Print input-presentation
 
Tweaking the interactive grid
Tweaking the interactive gridTweaking the interactive grid
Tweaking the interactive grid
 
Closure, Higher-order function in Swift
Closure, Higher-order function in SwiftClosure, Higher-order function in Swift
Closure, Higher-order function in Swift
 
Clojure functions examples
Clojure functions examplesClojure functions examples
Clojure functions examples
 
Forms in AngularJS
Forms in AngularJSForms in AngularJS
Forms in AngularJS
 
Computer Science Practical Science C++ with SQL commands
Computer Science Practical Science C++ with SQL commandsComputer Science Practical Science C++ with SQL commands
Computer Science Practical Science C++ with SQL commands
 
C Programming Language Part 4
C Programming Language Part 4C Programming Language Part 4
C Programming Language Part 4
 
3. chapter ii
3. chapter ii3. chapter ii
3. chapter ii
 
Plsql lab mannual
Plsql lab mannualPlsql lab mannual
Plsql lab mannual
 
Stl algorithm-Basic types
Stl algorithm-Basic typesStl algorithm-Basic types
Stl algorithm-Basic types
 
Chapter 8 c solution
Chapter 8 c solutionChapter 8 c solution
Chapter 8 c solution
 

Similar to Aggregate functions

Aggregate Functions,Final
Aggregate Functions,FinalAggregate Functions,Final
Aggregate Functions,Finalmukesh24pandey
 
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
 
Structured query language functions
Structured query language functionsStructured query language functions
Structured query language functionsVineeta Garg
 
Sql (Introduction to Structured Query language)
Sql (Introduction to Structured Query language)Sql (Introduction to Structured Query language)
Sql (Introduction to Structured Query language)Mohd Tousif
 
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
 
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
 
Basic Sql Handouts
Basic Sql HandoutsBasic Sql Handouts
Basic Sql Handoutsjhe04
 
Programming Fundamentals Arrays and Strings
Programming Fundamentals   Arrays and Strings Programming Fundamentals   Arrays and Strings
Programming Fundamentals Arrays and Strings imtiazalijoono
 
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
 

Similar to Aggregate functions (20)

Aggregate Functions,Final
Aggregate Functions,FinalAggregate Functions,Final
Aggregate Functions,Final
 
Clauses
ClausesClauses
Clauses
 
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)
 
Complex Queries using MYSQL00123211.pptx
Complex Queries using MYSQL00123211.pptxComplex Queries using MYSQL00123211.pptx
Complex Queries using MYSQL00123211.pptx
 
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
 
12. Basic SQL Queries (2).pptx
12. Basic SQL Queries  (2).pptx12. Basic SQL Queries  (2).pptx
12. Basic SQL Queries (2).pptx
 
SQl
SQlSQl
SQl
 
Les04
Les04Les04
Les04
 
Les04
Les04Les04
Les04
 
Structured query language functions
Structured query language functionsStructured query language functions
Structured query language functions
 
Sql (Introduction to Structured Query language)
Sql (Introduction to Structured Query language)Sql (Introduction to Structured Query language)
Sql (Introduction to Structured Query language)
 
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
 
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
 
Basic Sql Handouts
Basic Sql HandoutsBasic Sql Handouts
Basic Sql Handouts
 
Programming Fundamentals Arrays and Strings
Programming Fundamentals   Arrays and Strings Programming Fundamentals   Arrays and Strings
Programming Fundamentals Arrays and Strings
 
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
 

More from Soumyajit Dutta

More from Soumyajit Dutta (8)

Normalisation
NormalisationNormalisation
Normalisation
 
Er model
Er modelEr model
Er model
 
Concurrency control
Concurrency controlConcurrency control
Concurrency control
 
Transaction processing
Transaction processingTransaction processing
Transaction processing
 
Single row functions
Single row functionsSingle row functions
Single row functions
 
Chapter 4
Chapter 4Chapter 4
Chapter 4
 
Chapter 2
Chapter 2Chapter 2
Chapter 2
 
Computer Organisation Design
Computer Organisation DesignComputer Organisation Design
Computer Organisation Design
 

Recently uploaded

Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxNirmalaLoungPoorunde1
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdfssuser54595a
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxpboyjonauth
 
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...JhezDiaz1
 
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTiammrhaywood
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxSayali Powar
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxOH TEIK BIN
 
Pharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdfPharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdfMahmoud M. Sallam
 
Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...Jisc
 
Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Celine George
 
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdfLike-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdfMr Bounab Samir
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...Marc Dusseiller Dusjagr
 
Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17Celine George
 
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfEnzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfSumit Tiwari
 
CELL CYCLE Division Science 8 quarter IV.pptx
CELL CYCLE Division Science 8 quarter IV.pptxCELL CYCLE Division Science 8 quarter IV.pptx
CELL CYCLE Division Science 8 quarter IV.pptxJiesonDelaCerna
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxmanuelaromero2013
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
MARGINALIZATION (Different learners in Marginalized Group
MARGINALIZATION (Different learners in Marginalized GroupMARGINALIZATION (Different learners in Marginalized Group
MARGINALIZATION (Different learners in Marginalized GroupJonathanParaisoCruz
 

Recently uploaded (20)

Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptx
 
OS-operating systems- ch04 (Threads) ...
OS-operating systems- ch04 (Threads) ...OS-operating systems- ch04 (Threads) ...
OS-operating systems- ch04 (Threads) ...
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptx
 
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
 
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
 
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptx
 
Pharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdfPharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdf
 
Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...
 
Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17
 
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdfLike-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
 
Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17
 
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfEnzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
 
CELL CYCLE Division Science 8 quarter IV.pptx
CELL CYCLE Division Science 8 quarter IV.pptxCELL CYCLE Division Science 8 quarter IV.pptx
CELL CYCLE Division Science 8 quarter IV.pptx
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptx
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
 
MARGINALIZATION (Different learners in Marginalized Group
MARGINALIZATION (Different learners in Marginalized GroupMARGINALIZATION (Different learners in Marginalized Group
MARGINALIZATION (Different learners in Marginalized Group
 

Aggregate functions

  • 1. 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)
  • 2. Commonly used Aggregate functions Some of the commonly used aggregate functions are : • SUM • COUNT • AVG • MIN • MAX
  • 3. 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 );
  • 4. 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;
  • 5. Select on Employee Table After the insert when we query the Employee table we get the following results: Select * from Employee;
  • 6. 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
  • 7. 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;
  • 8. 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';
  • 9. 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';
  • 10. 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????
  • 11. 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
  • 12. 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.
  • 13. 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)??????
  • 14. 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);
  • 15. 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;
  • 16. 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????
  • 17. 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.
  • 18. 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
  • 19. 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;