0% found this document useful (0 votes)
3 views

Nested Queries

The document provides an overview of database indexing, explaining how it improves query performance by creating pointers to data. It also discusses SQL subqueries, including their types (single-row, multiple-row, multiple-column) and the differences between operators like UNION and UNION ALL, as well as ANY, ALL, and IN. Additionally, it covers the concept of correlated subqueries, which depend on outer query values and are executed for each row selected by the outer query.

Uploaded by

MAJID
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Nested Queries

The document provides an overview of database indexing, explaining how it improves query performance by creating pointers to data. It also discusses SQL subqueries, including their types (single-row, multiple-row, multiple-column) and the differences between operators like UNION and UNION ALL, as well as ANY, ALL, and IN. Additionally, it covers the concept of correlated subqueries, which depend on outer query values and are executed for each row selected by the outer query.

Uploaded by

MAJID
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 42

08:2

Database Systems
SUBQUERY/NESTED
QUERY

Database Systems
What is Indexing?
• Indexing makes columns faster to query by creating
pointers to where data is stored within a database.
What is Indexing?

This took 3 comparisons to find the right answer instead of 8 in the


unindexed data.
Clustered Indexes
The clustered index will be automatically created when the primary key is defined:
CREATE TABLE friends (id INT PRIMARY KEY, name VARCHAR, city VARCHAR);
Non-clustered Indexes
CREATE INDEX friends_name_asc ON friends(name ASC);
What is the difference between
UNION and UNION ALL
• UNION and UNION ALL are SQL operators used to
concatenate 2 or more result sets. This allows us to
write multiple SELECT statements, retrieve the
desired results, then combine them together into a
final, unified set.
• The main difference between UNION and UNION
ALL is that:
• UNION: only keeps unique records
• UNION ALL: keeps all records, including duplicates
UNION
UNION ALL
• If we were to now perform the UNION ALL on the
same data set, the query would skip the
deduplication step and return the results shown.
Retrieve The Department With The
Largest Number of Employees
• SELECT department_id, department_name
FROM departments WHERE department_id =
( SELECT department_id FROM employees
GROUP BY department_id ORDER BY
COUNT(*) DESC LIMIT 1 );
Limit
Set comparison operators (IN,
ALL, ANY).
• ANY
• OR
• IN
If the teacher's age is greater than all student's ages, the corresponding row
of the Teachers table is selected.
Get employees whose salary is greater than all
employees in the IT department (department ID
6).
• SELECT * FROM employees WHERE salary >
ALL ( SELECT salary FROM employees WHERE
department_id = 6 );
Here, the SQL command selects rows if age in the outer query is less than
any age in a subquery.
Find employees whose salary is higher than any
employee in department ID 3 (Purchasing).
• SELECT * FROM employees WHERE salary >
ANY ( SELECT salary FROM employees WHERE
department_id = 3 );
Get employees who work in departments located in London
or Oxford.

• SELECT * FROM employees WHERE


department_id IN ( SELECT department_id
FROM departments WHERE location_id IN
( SELECT location_id FROM locations WHERE
city IN ('London', 'Oxford') ) );
Key Differences
1.ANY vs ALL
•ANY checks if at least one condition is met.
•ALL checks if all values meet the condition.
2.IN vs ANY
•IN is a direct match operator.
•ANY is used with comparison operators (=, >,
<, >=, <=, <>) and checks against at least one
value.
3.ALL vs IN
•ALL requires the condition to be true for every
value in the subquery.
•IN simply checks for presence in a set.
Database Systems
Subquery/Nested query

Database Systems
SUBQUERY

• A subquery is a query within a query.


• Subqueries enable you to write queries that
select data rows for criteria that are actually
developed while the query is executing at run
time.
What is SQL Sub query?

A sub query is a SQL query nested


inside a larger query.
Where Sub query occurs?
A subquery may occurs in:
• A SELECT clause
• A WHERE clause
• The sub query can be nested inside a SELECT,
INSERT, UPDATE, or DELETE statement or inside
another sub query.
• A sub query 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, or ALL.
SUBQUERY SYNTAX

• The subquery (inner query) executes before the main


query(outer query).
• The result of the subquery is used by the main query.
SUBQUERIES (2/5)

A) Single-row (and single-column)


Types B) Multiple-row (and single-column)
C) Multiple-column

 who works in the same department as Clark?

SELECT … WHERE dep = (SELECT dep FROM … WHERE name = ‘CLARK’);


 who works in the same department as Clark OR Blake?

SELECT … WHERE dep IN (SELECT dep


FROM …
WHERE name =‘CLARK’ or name = ‘BLAKE’);
 who works in the same department(s) AND under the same boss as Clark?

SELECT … WHERE (dep, mgr) = (SELECT dep, mgr


FROM …
WHERE name = ‘CLARK’)
TYPE OF SUBQUERIES
• Single row subquery : Returns zero or one
row.

• Multiple row subquery : Returns one or more


rows.

• Multiple column subqueries : Returns one or


more columns.
1. SINGLE ROW SUBQUERIES
• The single row subquery returns one row. The single row query
uses any operator in the query i.e. (=,<=, >=, <>, <, > ).
• EXAMPLE:

• department table

Employee table
• Suppose you want to find out the ename, job,sal of the
employees whose salaries are less than that of an employee
whose empno= 7876 from EMP table. Now you need to perform
two queries in order to get the desired result.
1. We will find out the salary of the employee whose
empno=7876. the query is as under:

2. Now in second query we will apply the condition from which


we will find the ename, job and sal. We will use the query as
under:
• The above two queries can be used as single query by
using the concept of subquery. It will combine the result
into a single query as under:
Aggregate Functions and Comparison
Operators
• The aggregate functions (AVG, SUM, MAX, MIN, and
COUNT) always return a scalar result table.
• Thus, a subquery with an aggregate function as the object
of a comparison operator will always execute provided you
have formulated the query properly.
Aggregate Functions and Comparison
Operators
SELECT emp_last_name "Last Name",
emp_first_name "First Name",
emp_salary "Salary"
FROM employee
WHERE emp_salary >
(SELECT AVG(emp_salary)
FROM employee);

Last Name First Name Salary


--------------- --------------- ----------
Bordoloi Bijoy $55,000
Joyner Suzanne $43,000
Zhu Waiman $43,000
Joshi Dinesh $38,000
2. MULTIPLE ROW SUBQUERY
• Returns sets of rows. Query uses the set comparison
operators (IN, ALL, ANY). if u use a multirow subquery
with the equals comparison operators, the database will
return an error if more than one row is returned.

SYMBOL MEANING

IN Equal to any member in a list.

ANY Return rows that match any value on a list.

ALL Return rows that match all the values in a list.


IN Operator
• The IN operator returns true if the comparison value is contained
in the list.
• The following statement finds the employee whose salary
is the same as the minimum salary of the employees in
the department.
ANY Operator
• The ANY operator return true if the comparison value
matches any of the values in the list.
• Display the employees whose salary is more than the
minimum salary of the employees in any department.
ALL Operator
• Returns true only if the comparison value matches all the
values in the list.
• Display the employee detail with salary less than those
whose job is ‘MANAGER’.
3.MULTIPLE COLUMN SUBQUERY
• A subquery that compares more than one column between
the parent query and subquery is called the multiple column
subqueries.
• List the employees that makes the same salary as other
employee with empno=7521 with the same job also.
CORRELATED SUBQUERIES

 A correlated subquery is one where the


inner query depends on values provided
by the outer query.

 This means the inner query is executed


repeatedly, once for each row that
might be selected by the outer
query.
CORRELATED SUBQUERIES
 A correlated subquery is a subquery that is
evaluated FOR EACH ROW produced by the parent
query.
 Which employees receive more than the average
EMP_ID DEPT_ID LAST_NAME SALARY
------ ------- ---------- ------

salary
SELECT of their
e.emp_id, department?
e.dept_id,
201
114
20 Hartstein
30 Raphaely
13000
11000
e.last_name, e.salary 123 50 Vollman 6500
122 50 Kaufling 7900
FROM employees e 120 50 Weiss 8000
WHERE e.salary > (SELECT avg(i.salary) 121 50 Fripp 8200
103 60 Hunold 9000
FROM employees i 147 80 Errazuriz 12000
WHERE e.dept_id = i.dept_id) 146 80 Partners 13500
145 80 Russell 14000
100 90 King 24000
108 100 Greenberg 12000

 In this case, the correlated subquery specifically


computes, for each employee, the average salary
for the employee’s department

You might also like