0% found this document useful (0 votes)
48 views15 pages

Lab 13 SQL SubQueries With ALL, ANY, EXISTS, SOME

This document provides an overview of SQL subqueries, including their definition, types, and usage. It discusses single-row, multiple-row, and multiple-column subqueries. The document also covers correlated subqueries and provides examples of how to use different operators like IN, ANY, ALL with subqueries.

Uploaded by

Daniyal Ahmed
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
48 views15 pages

Lab 13 SQL SubQueries With ALL, ANY, EXISTS, SOME

This document provides an overview of SQL subqueries, including their definition, types, and usage. It discusses single-row, multiple-row, and multiple-column subqueries. The document also covers correlated subqueries and provides examples of how to use different operators like IN, ANY, ALL with subqueries.

Uploaded by

Daniyal Ahmed
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 15

Lab Manual for Introduction to Database Systems

Lab-13
SQL Sub-Queries
Lab 13: SQL Subqueries

Contents
1. Introduction ..................................................................................................................................................... 2

1.1 Relevant Lecture Material ............................................................................................................................... 2

2. Activity Time boxing ...................................................................................................................................... 2

3. Objective of the experiment ............................................................................................................................ 2

4. Concept Map 4.1.Sub-Query ........................................................................................................................... 2

4.1.1. Subquery Example .......................................................................................................................................... 4

4.1.2. Types of Subqueries ........................................................................................................................................ 4

4.1.2.1. Single-row subqueries ..................................................................................................................................... 4

4.1.2.2. Multiple-row subqueries ................................................................................................................................. 5

4.1.2.3. Multiple-column subqueries ........................................................................................................................... 6

4.1.3. Correlated Subqueries ..................................................................................................................................... 7

5. Homework before Lab .................................................................................................................................... 9

6. Procedure& Tools 6.1.Tools ............................................................................................................................ 9

If we want to find all the employees in each department who are earning more than the average salary with respect to
their department, following query will be used: ........................................................................................... 11

7. Practice Tasks ............................................................................................................................................... 13

7.1. Practice Task 1 [Expected time = 40mins].................................................................................................... 13

8. Evaluation Task (Unseen) [Expected time = 60mins for two tasks] ............................................................. 13

9. Evaluation criteria ......................................................................................................................................... 13

10. Further Reading ............................................................................................................................................ 14

11. REFERENCES: ............................................................................................................................................ 14

Department of Computer Science, Page 1


C.U.S.T.
Lab 13: SQL Subqueries

Lab 13: SQL Sub queries


1. Introduction

You have learnt the basic understanding of subqueries or inner query or nested query. Sub query
is a query within another SQL query. The inner query returns a value that is used by the outer
query. Using the sub query is equivalent to performing two sequential queries and using the
result of the first query as the search value in the second query.

1.1 Relevant Lecture Material

a) Revise Lecture No. 9 and 10


b) Text Book: Java: Text Book: Database Systems, A practical approach to design,
implementation and management by Thomas Connolly, Carolyn Begg, Addison Wesley
, Fifth Edition,
1. Read URL:
i. https://www.tutorialspoint.com/sql/sql-sub-queries.htm
2. Revise the SQL Sub-Queries with ALL, ANY, EXISTS, SOME, With UPDATE

2. Activity Time boxing

Table 1: Activity Time Boxing


Task Activity Name Activity time Total Time
No.
6.2 Setting-up and Setting Up 20mins 20mins
XAMPP (MySQL,
Apache)
6.3 Walkthrough Tasks 30mins 60mins
7 Practice tasks 20 to 30mins for each task 50mins
8 Evaluation Task 40mins for all assigned task 40mins

3. Objective of the experiment

• To get basic understanding of Subquery or Inner query or Nested query is a query within
another SQL query and embedded within the WHERE clause.
• To get basic understanding of Select using subquery.
• To understand the basic concept of Correlated Subquery.
• To get familiar with the basic ALL, ANY, EXISTS, SOME functionality.

4. Concept Map

4.1.Sub-Query
Results of one query can be used in another SQL statement. Subquery is useful if more than one
Department of Computer Science, Page 2
C.U.S.T.
Lab 13: SQL Subqueries

table is involved.

Department of Computer Science, Page 3


C.U.S.T.
Lab 13: SQL Subqueries

A subquery is a SELECT statement that is embedded in a clause of another SELECT statement.


You can build powerful statements out of simple ones by using subqueries. They can be very
useful when you need to select rows from a table with a condition that depends on the data in the
table itself.

You can place the subquery in a number of SQL clauses, including:

• The WHERE clause

• The HAVING clause

• The FROM clause

4.1.1. Subquery Example


Suppose you want to write a query to find out who earns a salary greater than Donald’s salary.
To solve this problem, you need two queries: one to find what Donald earns, and a second query
to find who earns more than that amount.

You can solve this problem by combining the two queries, placing one query inside the other
query.

SELECT * FROM `employees` WHERE SALARY > (SELECT SALARY FROM employees
WHERE first_name='Donald')

4.1.2. Types of Subqueries

A subquery may return a scalar, a single column, a single row, or a table. Therefore, there are
three types of subqueries:
• Single-row subqueries: Queries that return only one row from the inner SELECT
statement

• Multiple-row subqueries: Queries that return more than one row from the inner SELECT
Statement

• Multiple-column subquries: Queries that return more than one cloumns from the inner
SELECT Statement

4.1.2.1. Single-row subqueries


A single-row subquery is one that returns one row from the inner SELECT statement. This type
of subquery uses a single-row operator. Single row operators are: =, >, <, <=, >=, <>
The following example shows the names of the employees that are paid more than ‘Asad Khan’
from employees table.

Department of Computer Science, Page 4


C.U.S.T.
Lab 13: SQL Subqueries

SELECT * FROM employees


WHERE SALARY >
(SELECT SALARY FROM employees WHERE employeename = 'Shelley')

Notice that the subquery must be enclosed in parentheses. You cannot use a scalar subquery
when a literal value is required, such as for an argument in a LIMIT clause. The outer and inner
queries can get data from different tables.

4.1.2.2. Multiple-row subqueries

Subqueries that return more than one row are called multiple-row subqueries. You use a
multiple-row operator, instead of a single-row operator, with a multiple-row subquery. Multiple
row comparison operators are IN, ANY and ALL.

Operator Meaning
IN Equal to any member in the list
ANY Compare value to each value returned by the subquery

ALL Compare value to every value returned by the subquery

For example to find the employees who earn the same salary as the minimum salary for each
department, we will use the following subquery:

SELECT employee_id,first_name, salary,department_id FROM employees WHERE SALARY


IN
(SELECT MIN(salary) FROM employees GROUP BY department_id)

The inner query is executed first, producing a query result. The main query block is then
processed and uses the values returned by the inner query to complete its search condition. The
query will show the following result.

Department of Computer Science, Page 5


C.U.S.T.
Lab 13: SQL Subqueries

Figure 1

The ANY and ALL operators are supported syntax too and the following table summarizes the
equivalents for ANY and ALL:

Operator Meaning
<ANY Less than the highest
>ANY More than the lowest
ANY Not equal to any member in a list
=ANY Equivalent to IN
>ALL More than the highest
<ALL Less than the lowest

The following query will display the employees whose salary is less than the salary of all
employees with a job ID of ‘Sales Rep’ and whose job is not ‘Sales Rep’.

SELECT employee_id, first_name, salary, job_id FROM employees WHERE


SALARY< ANY
(SELECT salary from employees WHERE job_id='SA_REP')
AND job_id <> 'SA_REP';

4.1.2.3. Multiple-column subqueries


So far we have written single-row and multiple-row subqueries where only one column was
compared in the WHERE clause of the SELECT statement. A multiple-column subquery returns
more than one column to the outer query and can be listed in the outer queries FROM, WHERE,
or HAVING clause.
Department of Computer Science, Page 6
C.U.S.T.
Lab 13: SQL Subqueries

For example the following query will display employee_id, first_name, salary and department of
employees whose salary and department match both the salary and department of ‘Julia’.

Figure 2

Another method of writing a multiple column subquery is to use a subquery in the FROM clause
of a SELECT statement. A subquery in the FROM clause of a SELECT statement defines a data
source for that particular SELECT statement, and only that SELECT statement.

For example the following query will print the information of all the employees who are earning more
than average salary in their department.

SELECT a.employee_id, a.first_name, a.SALARY, a.department_id, b.salavg


FROM employees AS a, (SELECT department_id, AVG( SALARY ) AS 'salavg'
FROM employees GROUP BY department_id) AS b
WHERE a.department_id = b.department_id AND a.SALARY > b.salavg;

4.1.3. Correlated Subqueries


Subqueries can be non-correlated or correlated. A non-correlated subquery contains no
references to the outer query and is not dependent on it. As a result, a non-correlated subquery
could be evaluated as a completely separate statement. A correlated subquery contains references
to the values in the outer query and cannot be evaluated independently of it. Let’s take an
example. The query to find the average salary of an office is following:

Department of Computer Science, Page 7


C.U.S.T.
Lab 13: SQL Subqueries

Figure 3

If we want to find all the employees in each department who are earning more than the average
salary with respect to their department, following query will be used:

Figure 4

Department of Computer Science, Page 8


C.U.S.T.
Lab 13: SQL Subqueries

Note how the table qualifiers a and b are used in the example. This is necessary because the columns that are
used to correlate values from the inner and outer queries come from different references to the same table and
thus have the same name.

5. Homework before Lab

You must solve the following problems at home before the lab.

5.1. Problem Solution Modeling

After reading the reference material mentioned in the introduction, now you are ready to perform
homework assigned to you

5.1.1. Problem description:

Describe sub-query and its purpose; submit to lab teacher in soft form.

6. Procedure& Tools

6.1.Tools

In this section tools installation and setup is defined.

6.2. Setting-up and Setting Up XAMPP (MySQL, Apache) [Expected time = 5mins]

Refer to Lab 1 sec 6.2.

6.3. Walkthrough Task [Expected time = 30mins]

This task is designed to guide you the use of different types of sub-queries.

Query to find out who earns salary greater than Donald’s salary is:

Figure 5

Department of Computer Science, Page 9


C.U.S.T.
Lab 13: SQL Subqueries

Query to find the employees who earn the same salary as the minimum salary for each
department is:

Figure 6

Query to display the employees whose salary is less than the salary of all employees with a job
ID of ‘Sales Rep’ and whose job is not ‘Sales Rep’ is:

Department of Computer Science, Page 10


C.U.S.T.
Lab 13: SQL Subqueries

Figure 7

Query to display display employee_id, first_name, salary and department of employees whose salary and
department match both the salary and department of ‘Julia’is:

Figure 8

If we want to find all the employees in each department who are earning more than the average
salary with respect to their department, following query will be used:

Department of Computer Science, Page 11


C.U.S.T.
Lab 13: SQL Subqueries

Figure 9

Department of Computer Science, Page 12


C.U.S.T.
Lab 13: SQL Subqueries

7. Practice Tasks

This section will provide more practice exercises which you need to finish during the lab. You
need to finish the tasks in the required time. When you finish them, put these tasks in the
following folder:
\\fs\assignments$\IDBS\Lab12

7.1. Practice Task 1 [Expected time = 40mins]


Consider the schema given in Lab01 (7.1 Practice Task), write down following SQL queries.
You can use data types of your own choice.

1. Show first name and salary of employees who are receiving salary equal to maximum
salary.
2. Show employee_id and salary of employees having salary more than average salary of all
employees.
3. Show name of countries whose at least one location record exists.
4. Who reports to Shelley?
5. Show the employee’s first_name, department_id, and name of manager for all
employees.
6. Report for each employee, the percentage value of his/her salary as a percentage of the
total salary paid to his/her department. Order the report by department_id and percentage
value of salary in descending order.
7. For countries containing more than one location, show location whose city name starts
with ‘A’.
8. Show name of employees who works in ‘Shipping’ department.
9. Show name of employees whose job’s start date or end date is from 2013.

8. Evaluation Task (Unseen) [Expected time = 60mins for two tasks]

The lab instructor will give you unseen task depending upon the progress of the class.

9. Evaluation criteria

The evaluation criteria for this lab will be based on the completion of the following tasks. Each
task is assigned the marks percentage which will be evaluated by the instructor in the lab whether
the student has finished the complete/partial task(s).

Table 3: Evaluation of the Lab


Sr. No. Task Description Marks
No
1 6 Procedures and Tools 05

Department of Computer Science, Page 13


C.U.S.T.
Lab 13: SQL Subqueries

2 7 Practice tasks and Testing 15


3 8 Evaluation Tasks (Unseen) 80

10. Further Reading

This section provides the references to further polish your skills.

10.1. Text Book


Database Systems, A practical approach to design, implementation and management by Thomas
Connolly, Carolyn Begg, Addison Wesley , Fifth Edition,

10.2. Slides
The slides and reading material can be accessed from the folder of the class instructor available
at \\fs\lectures$

11. REFERENCES:

11.1. SQL-99 Complete, Really, by Peter Gulutzan & Trudy Pelzer.


• More examples for the SELECT command:
http://dev.mysql.com/doc/mysql/en/select.html
• MySQL operators: http://dev.mysql.com/doc/mysql/en/non-
typed_operators.html
• Built-in functions:
http://dev.mysql.com/doc/mysql/en/functions.html
• Joining tables:
http://www.melonfire.com/community/columns/trog/article.php?i
d=148
• Using subqeries:
http://www.melonfire.com/community/columns/trog/article.php?i
d=204
• Using subqeries:
http://www.melonfire.com/community/columns/trog/article.php?id=204

Department of Computer Science, Page 14


C.U.S.T.

You might also like