SlideShare a Scribd company logo
International Islamic University H-10, Islamabad, Pakistan
Database Managements Systems
Week 07
Advanced SQL Queries
Engr. Rashid Farid Chishti
http://youtube.com/rfchishti
http://sites.google.com/site/chisht
i
 Understand and apply aggregate functions in SQL
 Use GROUP BY to organize data into groups
 Apply HAVING to filter grouped data
Learning Objectives
 Definition: Functions that perform calculations on a set of values and return a
single value
 Common Aggregate Functions:
 COUNT() : Number of rows
 MAX() : Highest value
 MIN() : Lowest value
 SUM() : Total of numeric values
 AVG() : Average of numeric values
Aggregate Functions Overview
 First make a table
Aggregate Functions Overview
DROP database if exists week_07_db;
create database week_07_db;
use week_07_db;
CREATE TABLE Employee (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(100) NOT NULL,
department VARCHAR(50),
salary DECIMAL(10,2)
);
 Add some data;
Aggregate Functions Overview
INSERT INTO employee (name, department, salary)
VALUES
('Ahmed', 'IT', 60000.00),
('Fatima', 'HR', 50000.00),
('Omar', 'IT', 70000.00),
('Zainab', 'Finance', 55000.00),
('Ali', 'Marketing', 62000.00),
('Ayesha', 'HR', 48000.00),
('Hassan', 'IT', 72000.00),
('Khadija', 'Finance', 53000.00),
('Bilal', 'Marketing', 61000.00),
('Yusuf', 'IT', 65000.00);
 SUM() Example:
 AVG() Example:
 Use Case:
 Calculate total and average salaries for employee data
Using SUM() and AVG()
SELECT SUM(salary) FROM Employee;
SELECT AVG(salary) FROM Employee;
 COUNT() Example:
Using COUNT()
SELECT COUNT(*) FROM Employee
WHERE Department='IT';
SELECT COUNT(*) AS 'Marketing' FROM Employee
WHERE Department='Marketing';
SELECT COUNT(*) AS 'Total Emp' FROM Employee;
 MAX() Example:
 MIN() Example:
Using MAX() and MIN() Functions
SELECT MAX(salary) FROM Employee;
SELECT MAX(salary) FROM Employee
WHERE Department='Marketing';
SELECT MIN(salary) FROM Employee;
SELECT MIN(salary) FROM Employee
WHERE Department='Marketing';
ASC: Ascending Order
DESC: Descending
Order
ORDER BY: Column Name(s)
HAVING: Condition(s)
GROUP BY : Column Name(s)
WHERE: Condition(s)
JOIN: table ON
table.column
FROM: Name of Table(s)
DISTINCT: Name of Table
SELECT: retrieve data from one or more tables in a
database.
Data Query Language (DQL) Command
LIMIT: Number
 Purpose: Groups rows that have the same values into summary rows
 Syntax: SELECT column, COUNT(*) FROM table_name GROUP BY
column;
 Example:
Using GROUP BY Command for Organizing Data
SELECT department, COUNT(*) FROM Employee
GROUP BY department;
SELECT department, COUNT(*) FROM Employee
GROUP BY department ORDER BY department ASC;
SELECT department, COUNT(*)
FROM Employee
GROUP BY department
ORDER BY COUNT(*) DESC, department ASC;
 Purpose: Filters grouped records
 Syntax:
SELECT column, COUNT(*) FROM table_name
GROUP BY column HAVING COUNT(*) > 10;
 Example:
 Difference from WHERE:
 WHERE filters rows before grouping. HAVING filters after grouping
Filtering Groups with HAVING
SELECT department, COUNT(*) FROM Employee
GROUP BY department HAVING COUNT(*) > 2;
SELECT department, COUNT(*) FROM Employee
GROUP BY department HAVING COUNT(*) > 1
ORDER BY department ASC;
 Example:
SELECT category, AVG(price) FROM Products GROUP BY category;
 Use Case:
 Calculate average salary in each department.
Combining GROUP BY and Aggregate Functions
SELECT department, AVG(salary) FROM
Employee
GROUP BY department
ORDER BY AVG(salary) DESC;
 Definition: Query within another query
 Example:
 Use Case: Retrieve employees earning more than the average salary
 Use Case: Retrieve employees earning less than or equal to the average salary
Nested Queries (Subqueries)
SELECT * FROM Employee WHERE salary >
(SELECT AVG(salary) FROM Employee);
SELECT * FROM Employee WHERE salary <=
(SELECT AVG(salary) FROM Employee);
 SELECT Subquery Example:
SELECT name, (SELECT AVG(salary) FROM Employees) AS avg_salary
FROM Employees;
 FROM Subquery Example:
SELECT * FROM (SELECT * FROM Orders WHERE status = 'Pending')
AS PendingOrders;
Subqueries in SELECT and FROM
 Calculate the total number of students in each major
 Retrieve departments where more than 10 employees work
 Find the highest salary in each department
 List all orders with prices above the average order price
Practical Exercises
 Incorrect Grouping: Grouping on columns not in SELECT
 HAVING Misuse: Using HAVING without GROUP BY
 Nested Query Errors: Incorrect subquery syntax
Common Errors in Advanced SQL Queries
 Break down complex queries step by step
 Use aliases for subqueries to improve readability
 Test subqueries individually before integrating them
Best Practices for Advanced Queries
 Aggregate functions allow data summarization
 GROUP BY organizes data, and HAVING filters grouped results
 Subqueries enable more dynamic and complex data retrieval
Best Practices for Advanced Queries

More Related Content

Similar to DBMS: Week 07 - Advanced SQL Queries in MySQL (20)

PDF
Oracle Database Advanced Querying
Zohar Elkayam
 
PPTX
Lecture 8 DML3 aggregate functions in DB.pptx
imranahmadrana28
 
PPT
e computer notes - Aggregating data using group functions
ecomputernotes
 
PDF
advance-sqaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaal.pdf
traphuong2103
 
PPT
Les05
Vijay Kumar
 
PPT
Les04
Achmad Solichin
 
PPT
Les04
Sudharsan S
 
PPT
SQL Queries
Nilt1234
 
PPTX
SQL.pptx
MrHello6
 
PPT
Aggregate Functions,Final
mukesh24pandey
 
PDF
Dynamic websites lec2
Belal Arfa
 
PPTX
Lab3 aggregating data
Balqees Al.Mubarak
 
PPTX
Aggregate Function - Database
Shahadat153031
 
PPTX
12. Basic SQL Queries (2).pptx
SabrinaShanta2
 
PPTX
Subqueries, Backups, Users and Privileges
Ashwin Dinoriya
 
PPT
Sql5
Nargis Ehsan
 
PPT
SQL || overview and detailed information about Sql
gourav kottawar
 
PPT
Introduction to Oracle Functions--(SQL)--Abhishek Sharma
अभिषेक शर्मा
 
PDF
1.Types of SQL Commands for mba students
MrSushilMaurya
 
PPT
SQL5.ppt
ayeshaasmat4
 
Oracle Database Advanced Querying
Zohar Elkayam
 
Lecture 8 DML3 aggregate functions in DB.pptx
imranahmadrana28
 
e computer notes - Aggregating data using group functions
ecomputernotes
 
advance-sqaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaal.pdf
traphuong2103
 
SQL Queries
Nilt1234
 
SQL.pptx
MrHello6
 
Aggregate Functions,Final
mukesh24pandey
 
Dynamic websites lec2
Belal Arfa
 
Lab3 aggregating data
Balqees Al.Mubarak
 
Aggregate Function - Database
Shahadat153031
 
12. Basic SQL Queries (2).pptx
SabrinaShanta2
 
Subqueries, Backups, Users and Privileges
Ashwin Dinoriya
 
SQL || overview and detailed information about Sql
gourav kottawar
 
Introduction to Oracle Functions--(SQL)--Abhishek Sharma
अभिषेक शर्मा
 
1.Types of SQL Commands for mba students
MrSushilMaurya
 
SQL5.ppt
ayeshaasmat4
 

More from RashidFaridChishti (20)

PPTX
DBMS: Week 15 - Database Security and Access Control
RashidFaridChishti
 
PPTX
DBMS: Week 14 - Backup and Recovery in MySQL
RashidFaridChishti
 
PPTX
DBMS: Week 13 - Transactions and Concurrency Control
RashidFaridChishti
 
PPTX
DBMS: Week 12 - Triggers in MySQL Database Server
RashidFaridChishti
 
PPTX
DBMS: Week 11 - Stored Procedures and Functions
RashidFaridChishti
 
PPTX
DBMS: Week 10 - Database Design and Normalization
RashidFaridChishti
 
PPTX
DBMS: Week 09 - SQL Constraints and Indexing
RashidFaridChishti
 
PPTX
DBMS: Week 08 - Joins and Views in MySQL
RashidFaridChishti
 
PPTX
DBMS: Week 06 - SQL - Data Manipulation Language (DML)
RashidFaridChishti
 
PPTX
DBMS: Week 05 - Introduction to SQL Query
RashidFaridChishti
 
PPTX
DBMS: Week 04 - Relational Model in a Database
RashidFaridChishti
 
PPTX
DBMS: Week 03 - Data Models and ER Model
RashidFaridChishti
 
PPTX
DBMS: Week 02 - Database System Architecture
RashidFaridChishti
 
PPTX
DBMS: Week 01 - Introduction to Databases
RashidFaridChishti
 
DOCX
Lab Manual Arduino UNO Microcontrollar.docx
RashidFaridChishti
 
DOCX
Object Oriented Programming OOP Lab Manual.docx
RashidFaridChishti
 
DOCX
Lab Manual Data Structure and Algorithm.docx
RashidFaridChishti
 
PPTX
Data Structures and Agorithm: DS 24 Hash Tables.pptx
RashidFaridChishti
 
PPTX
Data Structures and Agorithm: DS 22 Analysis of Algorithm.pptx
RashidFaridChishti
 
PPTX
Data Structures and Agorithm: DS 21 Graph Theory.pptx
RashidFaridChishti
 
DBMS: Week 15 - Database Security and Access Control
RashidFaridChishti
 
DBMS: Week 14 - Backup and Recovery in MySQL
RashidFaridChishti
 
DBMS: Week 13 - Transactions and Concurrency Control
RashidFaridChishti
 
DBMS: Week 12 - Triggers in MySQL Database Server
RashidFaridChishti
 
DBMS: Week 11 - Stored Procedures and Functions
RashidFaridChishti
 
DBMS: Week 10 - Database Design and Normalization
RashidFaridChishti
 
DBMS: Week 09 - SQL Constraints and Indexing
RashidFaridChishti
 
DBMS: Week 08 - Joins and Views in MySQL
RashidFaridChishti
 
DBMS: Week 06 - SQL - Data Manipulation Language (DML)
RashidFaridChishti
 
DBMS: Week 05 - Introduction to SQL Query
RashidFaridChishti
 
DBMS: Week 04 - Relational Model in a Database
RashidFaridChishti
 
DBMS: Week 03 - Data Models and ER Model
RashidFaridChishti
 
DBMS: Week 02 - Database System Architecture
RashidFaridChishti
 
DBMS: Week 01 - Introduction to Databases
RashidFaridChishti
 
Lab Manual Arduino UNO Microcontrollar.docx
RashidFaridChishti
 
Object Oriented Programming OOP Lab Manual.docx
RashidFaridChishti
 
Lab Manual Data Structure and Algorithm.docx
RashidFaridChishti
 
Data Structures and Agorithm: DS 24 Hash Tables.pptx
RashidFaridChishti
 
Data Structures and Agorithm: DS 22 Analysis of Algorithm.pptx
RashidFaridChishti
 
Data Structures and Agorithm: DS 21 Graph Theory.pptx
RashidFaridChishti
 
Ad

Recently uploaded (20)

PDF
Submit Your Papers-International Journal on Cybernetics & Informatics ( IJCI)
IJCI JOURNAL
 
PPTX
Introduction to Internal Combustion Engines - Types, Working and Camparison.pptx
UtkarshPatil98
 
PDF
SERVERLESS PERSONAL TO-DO LIST APPLICATION
anushaashraf20
 
PPTX
Final Major project a b c d e f g h i j k l m
bharathpsnab
 
PDF
Electrical Machines and Their Protection.pdf
Nabajyoti Banik
 
PPTX
MODULE 03 - CLOUD COMPUTING AND SECURITY.pptx
Alvas Institute of Engineering and technology, Moodabidri
 
PDF
aAn_Introduction_to_Arcadia_20150115.pdf
henriqueltorres1
 
PPTX
美国电子版毕业证南卡罗莱纳大学上州分校水印成绩单USC学费发票定做学位证书编号怎么查
Taqyea
 
PDF
Basic_Concepts_in_Clinical_Biochemistry_2018كيمياء_عملي.pdf
AdelLoin
 
PDF
20ES1152 Programming for Problem Solving Lab Manual VRSEC.pdf
Ashutosh Satapathy
 
PPTX
OCS353 DATA SCIENCE FUNDAMENTALS- Unit 1 Introduction to Data Science
A R SIVANESH M.E., (Ph.D)
 
PPTX
What is Shot Peening | Shot Peening is a Surface Treatment Process
Vibra Finish
 
PPTX
Knowledge Representation : Semantic Networks
Amity University, Patna
 
PDF
Electrical Engineer operation Supervisor
ssaruntatapower143
 
PPTX
Numerical-Solutions-of-Ordinary-Differential-Equations.pptx
SAMUKTHAARM
 
PPT
Testing and final inspection of a solar PV system
MuhammadSanni2
 
PDF
Data structures notes for unit 2 in computer science.pdf
sshubhamsingh265
 
PDF
Viol_Alessandro_Presentazione_prelaurea.pdf
dsecqyvhbowrzxshhf
 
PPT
Footbinding.pptmnmkjkjkknmnnjkkkkkkkkkkkkkk
mamadoundiaye42742
 
PDF
Reasons for the succes of MENARD PRESSUREMETER.pdf
majdiamz
 
Submit Your Papers-International Journal on Cybernetics & Informatics ( IJCI)
IJCI JOURNAL
 
Introduction to Internal Combustion Engines - Types, Working and Camparison.pptx
UtkarshPatil98
 
SERVERLESS PERSONAL TO-DO LIST APPLICATION
anushaashraf20
 
Final Major project a b c d e f g h i j k l m
bharathpsnab
 
Electrical Machines and Their Protection.pdf
Nabajyoti Banik
 
MODULE 03 - CLOUD COMPUTING AND SECURITY.pptx
Alvas Institute of Engineering and technology, Moodabidri
 
aAn_Introduction_to_Arcadia_20150115.pdf
henriqueltorres1
 
美国电子版毕业证南卡罗莱纳大学上州分校水印成绩单USC学费发票定做学位证书编号怎么查
Taqyea
 
Basic_Concepts_in_Clinical_Biochemistry_2018كيمياء_عملي.pdf
AdelLoin
 
20ES1152 Programming for Problem Solving Lab Manual VRSEC.pdf
Ashutosh Satapathy
 
OCS353 DATA SCIENCE FUNDAMENTALS- Unit 1 Introduction to Data Science
A R SIVANESH M.E., (Ph.D)
 
What is Shot Peening | Shot Peening is a Surface Treatment Process
Vibra Finish
 
Knowledge Representation : Semantic Networks
Amity University, Patna
 
Electrical Engineer operation Supervisor
ssaruntatapower143
 
Numerical-Solutions-of-Ordinary-Differential-Equations.pptx
SAMUKTHAARM
 
Testing and final inspection of a solar PV system
MuhammadSanni2
 
Data structures notes for unit 2 in computer science.pdf
sshubhamsingh265
 
Viol_Alessandro_Presentazione_prelaurea.pdf
dsecqyvhbowrzxshhf
 
Footbinding.pptmnmkjkjkknmnnjkkkkkkkkkkkkkk
mamadoundiaye42742
 
Reasons for the succes of MENARD PRESSUREMETER.pdf
majdiamz
 
Ad

DBMS: Week 07 - Advanced SQL Queries in MySQL

  • 1. International Islamic University H-10, Islamabad, Pakistan Database Managements Systems Week 07 Advanced SQL Queries Engr. Rashid Farid Chishti http://youtube.com/rfchishti http://sites.google.com/site/chisht i
  • 2.  Understand and apply aggregate functions in SQL  Use GROUP BY to organize data into groups  Apply HAVING to filter grouped data Learning Objectives
  • 3.  Definition: Functions that perform calculations on a set of values and return a single value  Common Aggregate Functions:  COUNT() : Number of rows  MAX() : Highest value  MIN() : Lowest value  SUM() : Total of numeric values  AVG() : Average of numeric values Aggregate Functions Overview
  • 4.  First make a table Aggregate Functions Overview DROP database if exists week_07_db; create database week_07_db; use week_07_db; CREATE TABLE Employee ( id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(100) NOT NULL, department VARCHAR(50), salary DECIMAL(10,2) );
  • 5.  Add some data; Aggregate Functions Overview INSERT INTO employee (name, department, salary) VALUES ('Ahmed', 'IT', 60000.00), ('Fatima', 'HR', 50000.00), ('Omar', 'IT', 70000.00), ('Zainab', 'Finance', 55000.00), ('Ali', 'Marketing', 62000.00), ('Ayesha', 'HR', 48000.00), ('Hassan', 'IT', 72000.00), ('Khadija', 'Finance', 53000.00), ('Bilal', 'Marketing', 61000.00), ('Yusuf', 'IT', 65000.00);
  • 6.  SUM() Example:  AVG() Example:  Use Case:  Calculate total and average salaries for employee data Using SUM() and AVG() SELECT SUM(salary) FROM Employee; SELECT AVG(salary) FROM Employee;
  • 7.  COUNT() Example: Using COUNT() SELECT COUNT(*) FROM Employee WHERE Department='IT'; SELECT COUNT(*) AS 'Marketing' FROM Employee WHERE Department='Marketing'; SELECT COUNT(*) AS 'Total Emp' FROM Employee;
  • 8.  MAX() Example:  MIN() Example: Using MAX() and MIN() Functions SELECT MAX(salary) FROM Employee; SELECT MAX(salary) FROM Employee WHERE Department='Marketing'; SELECT MIN(salary) FROM Employee; SELECT MIN(salary) FROM Employee WHERE Department='Marketing';
  • 9. ASC: Ascending Order DESC: Descending Order ORDER BY: Column Name(s) HAVING: Condition(s) GROUP BY : Column Name(s) WHERE: Condition(s) JOIN: table ON table.column FROM: Name of Table(s) DISTINCT: Name of Table SELECT: retrieve data from one or more tables in a database. Data Query Language (DQL) Command LIMIT: Number
  • 10.  Purpose: Groups rows that have the same values into summary rows  Syntax: SELECT column, COUNT(*) FROM table_name GROUP BY column;  Example: Using GROUP BY Command for Organizing Data SELECT department, COUNT(*) FROM Employee GROUP BY department; SELECT department, COUNT(*) FROM Employee GROUP BY department ORDER BY department ASC; SELECT department, COUNT(*) FROM Employee GROUP BY department ORDER BY COUNT(*) DESC, department ASC;
  • 11.  Purpose: Filters grouped records  Syntax: SELECT column, COUNT(*) FROM table_name GROUP BY column HAVING COUNT(*) > 10;  Example:  Difference from WHERE:  WHERE filters rows before grouping. HAVING filters after grouping Filtering Groups with HAVING SELECT department, COUNT(*) FROM Employee GROUP BY department HAVING COUNT(*) > 2; SELECT department, COUNT(*) FROM Employee GROUP BY department HAVING COUNT(*) > 1 ORDER BY department ASC;
  • 12.  Example: SELECT category, AVG(price) FROM Products GROUP BY category;  Use Case:  Calculate average salary in each department. Combining GROUP BY and Aggregate Functions SELECT department, AVG(salary) FROM Employee GROUP BY department ORDER BY AVG(salary) DESC;
  • 13.  Definition: Query within another query  Example:  Use Case: Retrieve employees earning more than the average salary  Use Case: Retrieve employees earning less than or equal to the average salary Nested Queries (Subqueries) SELECT * FROM Employee WHERE salary > (SELECT AVG(salary) FROM Employee); SELECT * FROM Employee WHERE salary <= (SELECT AVG(salary) FROM Employee);
  • 14.  SELECT Subquery Example: SELECT name, (SELECT AVG(salary) FROM Employees) AS avg_salary FROM Employees;  FROM Subquery Example: SELECT * FROM (SELECT * FROM Orders WHERE status = 'Pending') AS PendingOrders; Subqueries in SELECT and FROM
  • 15.  Calculate the total number of students in each major  Retrieve departments where more than 10 employees work  Find the highest salary in each department  List all orders with prices above the average order price Practical Exercises
  • 16.  Incorrect Grouping: Grouping on columns not in SELECT  HAVING Misuse: Using HAVING without GROUP BY  Nested Query Errors: Incorrect subquery syntax Common Errors in Advanced SQL Queries
  • 17.  Break down complex queries step by step  Use aliases for subqueries to improve readability  Test subqueries individually before integrating them Best Practices for Advanced Queries
  • 18.  Aggregate functions allow data summarization  GROUP BY organizes data, and HAVING filters grouped results  Subqueries enable more dynamic and complex data retrieval Best Practices for Advanced Queries