Docsity

SQL Nested Queries & Joins: Scalar & Set-valued Subqueries, Recursive Queries - Prof. Mark, Study notes of Computer Science

Partial preview of the text

Download SQL Nested Queries & Joins: Scalar & Set-valued Subqueries, Recursive Queries - Prof. Mark and more Study notes Computer Science in PDF only on Docsity!

What you should have learned after this lecture ...

‰^ what

nested queries

are

‰^ how different kinds of joins can be explicitly expressed

Nested queries ‰^ In the

where

clause and in the

from

clause of an SQL statement further SQL state-

ments can appear. This is called a

nested query

‰^ In the

where

-clause we differentiate whether the result of a subquery yields a scalar

value or a relation. ‰ scalar subqueries −^ example: Which students with a semester number less than the average arethere?^ select

name, sem from

students where

sem < (

select

avg

(sem)

from

students)

−^ Scalar subqueries in SQL92 are even allowed in the

select

clause of a query. In

Oracle this feature is currently not supported. ‰^ scalar subqueries with

exists

−^ In the

where

clause also subqueries are allowed that yield a boolean value. These are indicated by the keyword

exists

−^ The condition “[

not ]^

exists

” is true if the subquery is not empty

[empty].

‰^ subqueries in the

from

clause

−^ Since an SQL query creates a relation, a query can also be used in the

from

clause. − example: Output the ids of those lectures that are attended by more than 20 stu-dents. select

id from

( select

id, count(*)

as^ number

from

attends

group by

id)

where

number > 20 −^ possible to explicitly use a join operator in SQL92 in the

from

clause by means of

the keywords +^ cross join

for the Cartesian (cross) product,

+^ natural join

for the natural join,

+^ join

or^ inner join

for theta join,

+^ left outer join

,^ right outer join

or^ full outer join

for outer join

analogously to the operators of the relational algebra: also tuples of the left, theright or both relations, which do not fulfil the join, are inserted into the resultrelation + union join

: some kind of full outer join where no comparison is performed. Both schemas are concatenated. Tuples are united and supplemented by null val-ues.

−^ example^ +^

select

*^ from

R ,^1

R where^2

R. A^1

θ^ R^2

. B

can be explicitly formulated as theta join as follows: select

*^ from

R join^1

R on^2

R. A^1

θ^ R^2

. B

join condition is explicitly specified behind the

on^ clause

Null values ‰^ A special value

null

for an attribute in a relation indicates that the value is unknown.

‰^ SQL uses a three-valued logic with the values

true

,^ false

and

unknown

‰^ Logical expressions yield the following results:

not true^

false unknown

unknown false

true

and^

true^

unknown

false

true^

true^

unknown

false

unknown

unknown

unknown

false

false

false

false

false