You are on page 1of 43

WEEK-10,11

Sub Queries in MYSQL


DEPARTMENT OF SOFTWARE ENGINERING
UNIVERSITY OF CENTRAL PUNJAB, LAHORE.
Contents
• Simple Nested Query using where attribute
• IN/NOT IN (Query) clause, Any and All.
• Co-related Nested Query using Exists and Not Exists.
Introduction to the MySQL Subquery

• A MySQL subquery is a query nested within another query. Also, a subquery can be
nested within another subquery.

• A MySQL subquery is called an inner query while the query that contains the
subquery is called an outer query. A subquery can be used anywhere that
expression is used and must be closed in parentheses.

• A subquery may occur in:


 A SELECT clause
 A FROM clause
 A WHERE clause
Introduction to the MySQL Subquery

• In MySQL subquery can be nested inside a SELECT, INSERT, UPDATE, DELETE, SET,
or DO statement or inside another subquery.
• A subquery is usually added within the WHERE Clause of another SQL SELECT
statement.
• You can use the comparison operators, such as >, <, or =. The comparison
operator can also be a multiple-row operator, such as IN, ANY, SOME, or ALL.
• A subquery can be treated as an inner query, which is a SQL query placed as a
part of another query called as outer query.
• The inner query executes first before its parent query so that the results of the
inner query can be passed to the outer query.
Rules for Sub Queries
The following are the rules to use subqueries:
• Subqueries should always use in parentheses.
• If the main query does not have multiple columns for subquery, then
a subquery can have only one column in the SELECT command.
• We can use various comparison operators with the subquery, such as
>, <, =, IN, ANY, SOME, and ALL. A multiple-row operator is very useful
when the subquery returns more than one row.
• We cannot use the ORDER BY clause in a subquery, although it can be
used inside the main query.
Advantages of Using Subqueries
The following are the advantages of using subqueries:
• The subqueries make the queries in a structured form that allows us to isolate
each part of a statement.

• The subqueries provide alternative ways to query the data from the table;
otherwise, we need to use complex joins and unions.

• The subqueries are more readable than complex join or union statements.
MySQL Subquery Syntax

• Basic Syntax

SELECT column_list (s) FROM  table_name  
WHERE  column_name OPERATOR  
(SELECT column_list (s)  FROM table_name [WHERE])  
Example
• We have employee table containing empid, ename, salary, etc.
• We need a report of all employees who’s salary is greater than
empid=123. But how we know the salary of employee 123?
• We can easily handle this in a sub query as:

SELECT empid, ename, salary from employee


WHERE salary > (SELECT salary from employee WHERE empid=123)
Types of Subqueries
We will discuss following types of subqueries.
• Comparisons using Subqueries
• Subqueries with IN, NOT IN, ALL, ANY
• Subqueries with EXISTS or NOT EXISTS
• Correlated Subqueries
MySQL Subqueries: Using Comparisons
• A subquery can be used before or after any of the comparison
operators. The subquery can return at most one value.
• The value can be the result of an arithmetic expression or a column
function.
• SQL then compares the value that results from the subquery with the
value on the other side of the comparison operator.
• You can use the following comparison operators:
MySQL Subqueries: Using Comparisons
Operator Description

= Equal to

> Greater than

>= Greater than or equal to

< Less than

<= Less than or equal to

!= Not equal to

<> Not equal to

<=> NULL-safe equal to operator


Example
• For example: suppose you want to find the employee id, first_name,
last_name, and salaries for employees whose average salary is higher
than the average salary throughout the company.
MySQL Subqueries with IN and NOT IN
• If a subquery returns more than one value, you can use other
operators such as IN or NOT IN operator in the WHERE clause.
• Consider the following example tables
EXAMPLE
For example, you can use a subquery with NOT IN operator to find the
customers who have not placed any orders as follows:

SELECT customerName
FROM customers
WHERE customerNumber NOT IN(
SELECT DISTINCT customerNumber
FROM orders);
PRACTICE
• See the practice questions on slide 41
MySQL Subqueries with ANY
• The ANY operator compares the value to each value returned by the
subquery.
• Therefore ANY keyword (which must follow a comparison operator)
returns TRUE if the comparison is TRUE for ANY of the values in the
column that the subquery returns.
• Note:
• returns a boolean value as a result
• returns TRUE if ANY of the subquery values meet the
condition
Syntax of ANY
SELECT column_name(s)
FROM table_name
WHERE column_name operator ANY
  (SELECT column_name
  FROM table_name
  WHERE condition);

Note: The operator must be a standard comparison


operator (=, <>, !=, >, >=, <, or <=).
Examples of ANY
Consider following tables: Products and OrderDetails
Examples of ANY
1. Write a query that statement lists the ProductName if
it finds ANY records in the OrderDetails table has
Quantity equal to 10

SELECT ProductName
FROM Products
WHERE ProductID = ANY
(SELECT ProductID
FROM OrderDetails
WHERE Quantity = 10);
Examples of ANY
2. Write a query that lists the ProductName if it finds ANY
records in the OrderDetails table has Quantity larger than
99.

SELECT ProductName
FROM Products
WHERE ProductID = ANY
  (SELECT ProductID
  FROM OrderDetails
  WHERE Quantity > 99);
Examples of ANY
3. Write a query that lists the ProductName if it finds ANY
records in the OrderDetails table has Quantity larger than
1000.
SELECT ProductName
FROM Products
WHERE ProductID = ANY
  (SELECT ProductID
  FROM OrderDetails
  WHERE Quantity > 1000);
MySQL Subqueries with ALL

• ALL means that the condition will be true only if the


operation is true for all values in the range. 
• returns a boolean value as a result
• returns TRUE if ALL of the subquery values meet the condition
• is used with SELECT, WHERE and HAVING statements
SYNTAX OF ALL

SELECT column_name(s)
FROM table_name
WHERE column_name operator ALL
  (SELECT column_name
  FROM table_name
  WHERE condition);
Note: The operator must be a standard comparison
operator (=, <>, !=, >, >=, <, or <=).
Examples of ALL
Consider following tables: Products and OrderDetails
EXAMPLES OF ALL
• The following SQL statement lists the ProductName if ALL
the records in the OrderDetails table has Quantity equal to
10. This will of course return FALSE because the Quantity
column has many different values (not only the value of 10)

SELECT ProductName
FROM Products
WHERE ProductID = ALL
  (SELECT ProductID
  FROM OrderDetails
  WHERE Quantity = 10);
PRACTICE
• See the practice questions on slide 42-43
Co-related Nested Query

• Correlated subqueries are used for row-by-row processing. Each


subquery is executed once for every row of the outer query.

qualify
Co-related Nested Query

• A correlated subquery is evaluated once for each row processed by the


parent statement. The parent statement can be a SELECT, UPDATE,
or DELETE statement.
• Synatx:
SELECT column1, column2, .... FROM table1 outer
WHERE column1 operator (SELECT column1, column2 FROM table2
WHERE expr1 = outer.expr2);
Co-related Nested Query

• A correlated subquery is one way of reading every row in a table and


comparing values in each row against related data.
• It is used whenever a subquery must return a different result or set of
results for each candidate row considered by the main query.
• In other words, you can use a correlated subquery to answer a
multipart question whose answer depends on the value in each row
processed by the parent statement. 
Nested Subqueries Versus Correlated Subqueries

• With a normal nested subquery, the inner SELECT query runs first


and executes once, returning values to be used by the main query. A
correlated subquery, however, executes once for each candidate row
considered by the outer query. In other words, the inner query is
driven by the outer query.
• NOTE: You can also use the ANY and ALL operator in a correlated
subquery. 
EXAMPLES of Correlated Subqueries : 
1. Find all the employees who earn more than the average salary in
their department.

SELECT last_name, salary, department_id FROM employees outer


WHERE salary >
(SELECT AVG(salary) FROM employees WHERE department_id =
outer.department_id group by department_id);
CORRELATED UPDATE
• Syntax

UPDATE table1 alias1 SET column =


(SELECT expression FROM table2 alias2 WHERE alias1.column =
alias2.column);
CORRELATED DELETE

• Syntax
DELETE FROM table1 alias1 WHERE column1 operator
(SELECT expression FROM table2 alias2 WHERE alias1.column =
alias2.column);
Using the EXISTS Operator
• The EXISTS operator tests for existence of rows in the results set of
the subquery.
• If a subquery row value is found the condition is flagged TRUE and
the search does not continue in the inner query, and if it is not found
then the condition is flagged FALSE and the search continues in the
inner query.
Examples of EXISTS
1. Find employees who have at least one person reporting to them.

SELECT employee_id, last_name, job_id, department_id FROM


employees outer WHERE EXISTS
( SELECT * FROM employees WHERE manager_id =
outer.employee_id);
EXAMPLE of using NOT EXIST
2. Find all departments that do not have any employees.

SELECT department_id, department_name FROM departments d


WHERE NOT EXISTS
(SELECT * FROM employees WHERE department_id =
d.department_id);
PRACTICE QUESTIONS
Consider the table: employees
EMPLOYEE_ID FIRST_NAME LAST_NAME EMAIL PHONE_NUMBER HIRE_DATE JOB_ID SALARY COMMISSION_PCT MANAGER_ID DEPARTMENT_ID
100 Steven King SKING 515.123.4567 17-06-87 AD_PRES 24000 0 0 90
101 Neena Kochhar NKOCHHAR 515.123.4568 18-06-87 AD_VP 17000 0 100 90
102 Lex De Haan LDEHAAN 515.123.4569 19-06-87 AD_VP 17000 0 100 90
103 Alexander Hunold AHUNOLD 590.423.4567 20-06-87 IT_PROG 9000 0 102 60
104 Bruce Ernst BERNST 590.423.4568 21-06-87 IT_PROG 6000 0 103 60
105 David Austin DAUSTIN 590.423.4569 22-06-87 IT_PROG 4800 0 103 60
106 Valli Pataballa VPATABAL 590.423.4560 23-06-87 IT_PROG 4800 0 103 60
107 Diana Lorentz DLORENTZ 590.423.5567 24-06-87 IT_PROG 4200 0 103 60
108 Nancy Greenberg NGREENBE 515.124.4569 25-06-87 FI_MGR 12000 0 101 100
109 Daniel Faviet DFAVIET 515.124.4169 26-06-87 FI_ACCOUNT 9000 0 108 100
110 John Chen JCHEN 515.124.4269 27-06-87 FI_ACCOUNT 8200 0 108 100
111 Ismael Sciarra ISCIARRA 515.124.4369 28-06-87 FI_ACCOUNT 7700 0 108 100
112 Jose Manuel Urman JMURMAN 515.124.4469 29-06-87 FI_ACCOUNT 7800 0 108 100
113 Luis Popp LPOPP 515.124.4567 30-06-87 FI_ACCOUNT 6900 0 108 100
114 Den Raphaely DRAPHEAL 515.127.4561 01-07-87 PU_MAN 11000 0 100 30
115 Alexander Khoo AKHOO 515.127.4562 02-07-87 PU_CLERK 3100 0 114 30
116 Shelli Baida SBAIDA 515.127.4563 03-07-87 PU_CLERK 2900 0 114 30
117 Sigal Tobias STOBIAS 515.127.4564 04-07-87 PU_CLERK 2800 0 114 30
118 Guy Himuro GHIMURO 515.127.4565 05-07-87 PU_CLERK 2600 0 114 30
119 Karen Colmenares KCOLMENA 515.127.4566 06-07-87 PU_CLERK 2500 0 114 30
120 Matthew Weiss MWEISS 650.123.1234 07-07-87 ST_MAN 8000 0 100 50
121 Adam Fripp AFRIPP 650.123.2234 08-07-87 ST_MAN 8200 0 100 50
122 Payam Kaufling PKAUFLIN 650.123.3234 09-07-87 ST_MAN 7900 0 100 50
123 Shanta Vollman SVOLLMAN 650.123.4234 10-07-87 ST_MAN 6500 0 100 50
124 Kevin Mourgos KMOURGOS 650.123.5234 11-07-87 ST_MAN 5800 0 100 50
125 Julia Nayer JNAYER 650.124.1214 12-07-87 ST_CLERK 3200 0 120 50
PRACTICE QUESTIONS
Consider the table: departments
DEPARTMENT_ID DEPARTMENT_NAME MANAGER_ID ATION_ID
10 Administration 200 1700
20 Marketing 201 1800
30 Purchasing 114 1700

40 Human Resources 203 2400

50 Shipping 121 1500


60 IT 103 1400
70 Public Relations 204 2700
80 Sales 145 2500
90 Executive 100 1700
100 Finance 108 1700
110 Accounting 205 1700
120 Treasury 0 1700
130 Corporate Tax 0 1700

140 Control And Credit 0 1700

150 Shareholder Services 0 1700


PRACTICE QUESTIONS
Consider the table: locations
location_id street_address postal_code city state_province country_id
1000 1297 Via Cola di Rie 989 Roma   IT
1100 93091 Calle della Te 10934 Venice   IT
1200 2017 Shinjuku-ku 1689 Tokyo Tokyo Prefectu JP
1300 9450 Kamiya-cho 6823 Hiroshima   JP
1400 2014 Jabberwocky Rd 26192 Southlake Texas US
1500 2011 Interiors Blvd 99236 South San California US
1600 2007 Zagora St 50090 South Brun New Jersey US
1700 2004 Charade Rd 98199 Seattle Washington US
1800 147 Spadina Ave M5V 2L7 Toronto Ontario CA
1900 6092 Boxwood St YSW 9T2 Whitehorse Yukon CA
2000 40-5-12 Laogianggen 190518 Beijing   CN
2100 1298 Vileparle (E) 490231 Bombay Maharashtra IN
2200 12-98 Victoria Stree 2901 Sydney New South Wale AU
2300 198 Clementi North 540198 Singapore   SG
2400 8204 Arthur St   London   UK
2500 Magdalen Centre, The OX9 9ZB Oxford Oxford UK
2600 9702 Chester Road 9629850293 Stretford Manchester UK
2700 Schwanthalerstr. 703 80925 Munich Bavaria DE
2800 Rua Frei Caneca 1360 01307-002 Sao Paulo Sao Paulo BR
2900 20 Rue des Corps-Sai 1730 Geneva Geneve CH
3000 Murtenstrasse 921 3095 Bern BE CH
3100 Pieter Breughelstraa 3029SK Utrecht Utrecht NL
3200 Mariano Escobedo 999 11932 Mexico Cit Distrito Feder MX
PRACTICE QUESTIONS
Consider the table: jobs
JOB_ID JOB_TITLE MIN_SALARY MAX_SALARY
AD_PRES President 20000 40000
AD_VP Administration Vice President 15000 30000
AD_ASST Administration Assistant 3000 6000
FI_MGR Finance Manager 8200 16000
FI_ACCOUNT Accountant 4200 9000
AC_MGR Accounting Manager 8200 16000
AC_ACCOUNT Public Accountant 4200 9000
SA_MAN Sales Manager 10000 20000
SA_REP Sales Representative 6000 12000
PU_MAN Purchasing Manager 8000 15000
PU_CLERK Purchasing Clerk 2500 5500
ST_MAN Stock Manager 5500 8500
ST_CLERK Stock Clerk 2000 5000
SH_CLERK Shipping Clerk 2500 5500
IT_PROG Programmer 4000 10000
MK_MAN Marketing Manager 9000 15000
MK_REP Marketing Representative 4000 9000
HR_REP Human Resources Representative 4000 9000
PR_REP Public Relations Representative 4500 10500
PRACTICE QUESTIONS
1. Write a query to find the name (first_name, last_name) and the salary of the
employees who have a higher salary than the employee whose last_name=‘Bull’
2. Write a query to find the name (first_name, last_name) of all employees who works in
the IT department.
3. Write a query to find the name (first_name, last_name) of the employees who have a
manager and worked in a USA based department.
4. Write a SQL query to find those employees who earn more than the average salary.
Return employee ID, first name, last name.
5. write a SQL query to find those employees whose department is located at ‘Toronto’.
Return first name, last name, employee ID, job ID.
6. Write a SQL query to find those employees who report to that manager whose first
name is ‘Payam’. Return first name, last name, employee ID and salary
PRACTICE QUESTIONS
7. Write a SQL query to find all those departments where at least one employee is employed.
Return department name
8. write a SQL query to find those employees who do not work in the departments where
managers’ IDs are between 100 and 200 (Begin and end values are included.). Return all the
fields of the employees
9. From the following table, write a SQL query to find those employees whose salary matches
the lowest salary of any of the departments. Return first name, last name and department ID.
10. Write a query to find the name (first_name, last_name) of the employees who are managers.
11. write a SQL query to find those employees whose salary is lower than that of employees
whose job title is "MK_MAN". Exclude employees of Job title ‘MK_MAN’. Return employee ID,
first name, last name, job ID
12. Write a query to find the name (first_name, last_name), and salary of the employees whose
salary is greater than the average salary.
PRACTICE QUESTIONS
13. Write a query to find the name (first_name, last_name), and salary of the employees
whose salary is equal to the minimum salary for their job grade.
14. Write a query to find the name (first_name, last_name), and salary of the employees
who earns more than the average salary and works in any of the IT departments.
15. Write a query to find the name (first_name, last_name), and salary of the
employees who earns more than the earning of Mr. Bell.
16. Write a query to find the name (first_name, last_name), and salary of the employees
who earn the same salary as the minimum salary for all departments. 
17. Write a query to find the name (first_name, last_name), and salary of the employees
whose salary is greater than the average salary of all departments.
18. Write a query to find the 3rd maximum salary in the employees table.

You might also like