0% found this document useful (0 votes)
2 views27 pages

Wk7_sub Queries & Query Expressions

This document discusses the concept of sub-queries in SQL, which are queries nested within other queries, allowing for more complex data retrieval. It covers the syntax, usage, and differences between sub-queries and joins, as well as various types of sub-query search conditions. The document also highlights the advantages and disadvantages of using sub-queries in database management.

Uploaded by

ummahhh20
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)
2 views27 pages

Wk7_sub Queries & Query Expressions

This document discusses the concept of sub-queries in SQL, which are queries nested within other queries, allowing for more complex data retrieval. It covers the syntax, usage, and differences between sub-queries and joins, as well as various types of sub-query search conditions. The document also highlights the advantages and disadvantages of using sub-queries in database management.

Uploaded by

ummahhh20
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/ 27

DATABASE MANAGEMENT II

Dr. Bilkisu L. Muhammad-Bello

Week 7 Database Management II


1
SUB QUERIES

Week 7 Database Management II


2
Introduction
The sub-query feature in SQL permits the use of the result of one query
in another query.
The SQL sub-query feature plays an important role in SQL because sub-
queries make it easier to write SELECT statements as it allows you to
break down a query in to bits and then put the bits back together.
Sub-queries are oftentimes the most natural way to express a query
because it’s close to the English language description of the query most
times. There are also queries that cannot be expressed in SQL without
the use of sub-queries.
The sub-query feature is however less popular as against the join
features.

3
Week 7 Database Management II
Learning Outcomes/Objectives

At the end of this topic, you should be able to:


Define a sub-query and describe how they are used in SQL
statements.
Describe sub-query search conditions.
Compare and contrast sub-queries and joins.
Describe and use nested sub-queries.
Discuss correlated sub-queries.

4
Week 7 Database Management II
What is a Sub-query?

A sub-query is a query within a query.


A sub-query can also be defined as a group of nested SELECT
statements inside a SELECT, INSERT, UPDATE or DELETE
statement.
A sub-query must be enclosed within parentheses and cannot use
the ORDER BY clause.
The inner query is evaluated first by the DBMS and the result is
returned to the outer query for the final result set.

5
Week 7 Database Management II
Using Sub-queries

Sub-queries can be used to retrieve data from multiple tables in a


database as an alternative to a join.
A DBMS uses the results of a sub-query to determine the results
of the higher-level (outer) query that contains the sub-query.
Sub-queries are used inside the WHERE or HAVING clause of the
outer SELECT statement.

6
Week 7 Database Management II
Sub-query Basic Syntax
SELECT ALL|DISTINCT sub-query_select_list
FROM table_name(s)
[WHERE] search_condition
[GROUP BY] column_name(s)
[HAVING] search_condition

❖ The WHERE, GROUP BY and HAVING clauses are optional in


sub-queries.
❖ These clauses perform their normal functions when used within
sub-queries.

7
Week 7 Database Management II
Features of Subqueries
Subquery – one select statement inside another
Used in the WHERE clause
Subqueries can return many rows.
Subqueries can only return 1 column.
Subqueries can be used as a replacement for view or self-join.
Some programmers see them as easier to understand than other options.
The main drawback is that they can be much slower than self-join or view.

8
Week 7 Database Management II
Simple Example
Who in the database is older than Jim Smith?

SELECT dob FROM driver WHERE name = ‘Jim Smith’;

Dob
11 Jan 1980

SELECT name FROM driver WHERE dob > ’11 Jan 1980’;

name
Bob Smith
Bob Jones

10
Week 7 Database Management II
With a subquery…
Combined together:

SELECT name
FROM driver
WHERE dob > (SELECT dob
FROM driver
WHERE name = ‘Jim Smith’);

This query will only work if there is only 1 Jim Smith.

11
Week 7 Database Management II
ANY and ALL
To support subqueries which return more than 1 row we need some additional
operators… ANY and ALL.
ANY – changes the rule so that it must be true for at least one of the rows
returned from the subquery.
ALL – changes the rule so that it must be true for each and every row
returned from the subquery.

The ANY or ALL operator goes immediately before the open bracket of the
subquery.

12
Week 7 Database Management II
Example 1
What cars are the same colour as a car owned by Jim Smith?
Jim owns 2 cars, one is RED and the other BLUE. We are looking for cars which
are either RED or BLUE.

SELECT regno FROM car


WHERE colour = ANY ( SELECT colour
FROM car
WHERE owner = ‘Jim Smith’
)

13
Week 7 Database Management II
Example 2
List the drivers younger than all the people who own a blue car.
We are looking for the age of drivers who own a BLUE car, and listing drivers
who are younger than all of those ages.

SELECT name,dob FROM driver


WHERE dob < ALL (
SELECT dob
FROM car JOIN driver ON (owner=name)
WHERE colour = ‘BLUE’
);

14
Week 7 Database Management II
IN and NOT IN
We earlier saw IN working for sets like (‘A’,’B’).
A subquery itself returns its result as a set.
Therefore we can use IN and NOT IN on subqueries.

Question: Which cars are the same colour as one of Jim Smith’s cars?

SELECT regno FROM car


WHERE colour IN (SELECT colour FROM car
WHERE owner = ‘Jim Smith’)
;

15
Week 7 Database Management II
Example of NOT IN

Question: Which cars DO NOT have the same colour as one of Jim
Smith’s cars?

SELECT regno FROM car


WHERE colour NOT IN (SELECT colour FROM car
WHERE owner = ‘Jim Smith’)
;

16
Week 7 Database Management II
Differences between an actual SELECT statement and a
sub-query
A sub-query produces a single column of data as its query result. This
implies that most times, a sub-query has a single select item as it’s sub-
query select list in a SELECT clause.
As you must have observed from the syntax, the ORDER BY clause
cannot be used in a sub-query. This is because the sub-query result is
never visible to the user but rather used internally by the main query.
Column names that may appear in a sub-query may refer to columns of
the table in the main (outer) query.
Only a single SELECT statement is allowed in most implementation of
sub-queries. A UNION of several SELECT statements is not allowed.

19
Week 7 Database Management II
Outer References

Within the body of the sub-query, a column name that does not
refer to any of the tables named in the FROM clause but is rather
from the table named in the FROM clause of the main (outer)
query is called an outer reference.

20
Week 7 Database Management II
Sub-query Search Conditions
Recall that a sub-query usually appears in the WHERE or HAVING
clause as part of the search condition of a query. Most SQL
products offer the following sub-query search conditions:
Sub-query comparison test
Sub-query set membership test
Existence test
Quantified comparison test

21
Week 7 Database Management II
The Sub-query Comparison Test (=, <>, <, >,
<=, >=)

This is a modified version of the simple comparison test but very


similar to the simple comparison test as it compares the value of
an expression to a single value produced by the sub-query.
This test compares a value of the row being tested to a single
value produced by the sub-query and then returns a TRUE if the
result of the comparison is true.
The sub-query is only allowed on the right side of the comparison
operator as specified by the SQL1 standard.
That is; Q < (sub-query) is allowed, but (sub-query) < Q is not
allowed.

22
Week 7 Database Management II
Syntax for the Comparison Test
SELECT select_list
FROM table_name(s)
WHERE expression{=,<>,<,>,<=,>=} (sub-query)

23
Week 7 Database Management II
The Set Membership Test

This is also a modified version of the simple set membership test.


The sub-query version of the set membership test (IN) matches a
test value to the set of values returned by a sub-query. The syntax
is as follows:
SELECT select_list
FROM table_name(s)
WHERE test_expression [NOT] IN (sub-query)

24
Week 7 Database Management II
The Existence Test

The existence test checks whether a sub-query returns any value.


The syntax is as follows:
SELECT select_list
FROM table_name(s)
WHERE [NOT] EXISTS (sub-query)

25
Week 7 Database Management II
Quantified Test

The quantified test (ANY and ALL) use one of the simple
comparison operators to compare a test value to all of the values
returned by a sub-query, checking to see whether the comparison
holds for some or all of the values.
The syntax is as follows:
SELECT select_list
FROM table_name(s)
WHERE test_expression {=,<>,<,>,<=,>=}[ANY|ALL]
(sub-query)

26
Week 7 Database Management II
Sub-Queries and Joins

In some cases, queries written as sub queries could also be


written as multi-table queries or joins.
SQL gives you the liberty to choose how to write the query either
way.
Oftentimes, queries written with sub-queries or joins will yield the
same result.
Therefore there is no right or wrong way of writing queries
however; many people find the use of sub-queries a more natural
way of writing queries.

27
Week 7 Database Management II
Nested Sub-queries

A nested sub-query contains more than one sub-query.


A sub-query can be used inside a sub-query in a similar way a
sub-query is used inside a main query.
For example, in a three-level query, we have the main query, a
sub-query, and a sub-subquery.

28
Week 7 Database Management II
Correlated Sub-queries

Correlated sub-queries depend on the outer query for their


evaluation.
This is because the sub-query produces the same result for every
row of the main query.
In correlated sub-queries, the WHERE clause of the sub-query
references a table in the FROM clause of the outer query.

29
Week 7 Database Management II
Sub-queries in the HAVING Clause
Many sub-queries are often found in the WHERE clause of the
SELECT statement.
They can however be used in the HAVING clause of a query.
When a sub-query appears in the HAVING clause, the results of
the sub-query are used to select rows groups that contribute data
to the query results.

30
Week 7 Database Management II

You might also like