Sie sind auf Seite 1von 42

2

3
4
5
7
The query which is enclosed is called Inner query
The query which encloses another query is called Outer query
8
Sub-queries:
A sub-query is a query within a query. A sub-query answers the queries that have multiple
parts; the sub-query answers one part of the question, and the parent query answers the
other part. When you nest many sub-queries, the innermost query is evaluated first.
SubQueries can be used in SELECT , FROM, WHERE and HAVING clauses.
For e.g :
Select all sales reps who have a higher quota than sales rep 101.
We need to analyze this query and understand how to break it into sub problems
1. First we need to find out what is the quota of sales rep 101
2. Based on this info, we need to select sales reps who have a higher quota than this value
3. So, the inner query will find the quota of sales rep 101 and the outer query will extract
sales reps exceeding this quota value. The solution would look like:
SELECT Rep
FROMSalesReps
WHERE Quota >
SELECT Quota
FROMSalesReps
WHERE Empl_Num = 101;
9
10
11
12
13
14
You can reduce the three level sub query by joining Customer and CustomerPurchase of
first and second query.
(left as an exercise)
15
16
17
Note:
The column names in the parent queries are available for reference in sub-queries. The column names from the tables in the sub-
query cannot be used in the parent queries. The scope is only the current query level and its sub-queries.
18
Note:
The column names in the parent queries are available for reference in sub-queries. The column names from the tables in the sub-
query cannot be used in the parent queries. The scope is only the current query level and its sub-queries.
19
Note:
The column names in the parent queries are available for reference in sub-queries. The column names from the tables in the sub-
query cannot be used in the parent queries. The scope is only the current query level and its sub-queries.
20
Note:
The column names in the parent queries are available for reference in sub-queries. The column names from the tables in the sub-
query cannot be used in the parent queries. The scope is only the current query level and its sub-queries.
21
Constant can be used in the LHS of where clause
22
24
EXISTS:
The EXISTS operator is always followed by a sub-query in parentheses. EXISTS evaluates
to TRUE if the sub-query returns at least one row.
25
26
27
28
29
30
31
32
33
34
35
36
37
38
A not exists checks for the opposite condition than an Exists. It checks for the non-existence of a condition.
39
40
41
42

Das könnte Ihnen auch gefallen