Docsity

relational algebra and sql cheat sheet, Cheat Sheet of Database Management Systems (DBMS)

Toggle sidebar
bg1
1
1
Relational Algebra and SQL
Chapter 5
2
Relational Query Languages
•
Languages for describing queries on a
relational database
•
•
Structured Query Language
Structured Query Language
(SQL)
Predominant application
-
level query language
Declarative
•
•
Relational Algebra
Relational Algebra
Intermediate language used within DBMS
Procedural
Cheat Sheet
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13
pf14
pf15
pf16
pf17
pf18
pf19
pf1a
pf1b
pf1c
pf1d
pf1e
pf1f
pf20
pf21
pf22
pf23

Partial preview of the text

Download relational algebra and sql cheat sheet and more Cheat Sheet Database Management Systems (DBMS) in PDF only on Docsity!

1

Relational Algebra and SQL

Chapter 5

2

Relational Query Languages

  • Languages for describing queries on a

relational database

Structured Query Language

Structured Query Language (SQL)

  • Predominant application-level query language
  • Declarative

Relational Algebra

Relational Algebra

  • Intermediate language used within DBMS
  • Procedural

3

What is an Algebra?

  • A language based on operators and a domain of values
  • Operators map values taken from the domain into

other domain values

  • Hence, an expression involving operators and

arguments produces a value in the domain

  • When the domain is a set of all relations (and the

operators are as described later), we get the relationalrelational

algebra algebra

  • We refer to the expression as a query

query and the value

produced as the queryquery resultresult

4

Relational Algebra

Domain

: set of relations

  • Basic operators : selectselect, projectproject, unionunion, setset

difference

difference, Cartesian

Cartesian product

product

Derived operators

set intersection

set intersection, division

division, join

join

  • Procedural : Relational expression specifies query

by describing an algorithm (the sequence in which

operators are applied) for determining the result of

an expression

7

Selection Condition

  • Operators: <,
  • Simple selection condition:

attribute

operator

constant

  • < attribute > operator < attribute >
  • < condition > AND < condition >
  • <

condition

OR

condition

• NOT

< condition >

8

Selection Condition - Examples

  • σ

Id> 3000

OR Hobby=‘ hiking’

(PersonPerson)

  • σ

Id> 3000

AND Id < 3999

(PersonPerson)

  • σ

NOT( Hobby=‘ hiking’)

Person

Person)

  • σ

Hobby ≠ ‘ hiking’

(PersonPerson)

9

Project Operator

  • Produces table containing subset of columns

of argument table

π

attribute list

relation

  • Example:

PersonPerson π

Name,Hobby

(PersonPerson)

1123 John 123 Main stamps

1123 John 123 Main coins

5556 Mary 7 Lake Dr hiking

9876 Bart 5 Pine St stamps

John stamps

John coins

Mary hiking

Bart stamps

Id Name Address Hobby Name Hobby

10

Project Operator

1123 John 123 Main stamps

1123 John 123 Main coins

5556 Mary 7 Lake Dr hiking

9876 Bart 5 Pine St stamps

John 123 Main

Mary 7 Lake Dr

Bart 5 Pine St

Result is a table (no duplicates); can have fewer tuples

than the original

Id Name Address Hobby Name Address

  • Example:

PersonPerson π

Name,Address

(PersonPerson)

13

Union Compatible Relations

  • Two relations are

union compatible

union compatible if

  • Both have same number of columns
  • Names of attributes are the same in both
  • Attributes with the same name in both relations

have the same domain

  • Union compatible relations can be

combined using unionunion , intersectionintersection , and setset

difference difference

14

Example

Tables:

Person

Person ( SSN, Name, Address, Hobby )

Professor Professor ( Id, Name, Office, Phone )

are not union compatible.

But

π

Name

Person

Person) and π

Name

Professor

Professor)

are union compatible so

π

Name

(PersonPerson) - π

Name

(ProfessorProfessor)

makes sense.

15

Cartesian Product

  • If R

R and S

S are two relations, R

R ×

S

S is the set of all

concatenated tuples , where x is a tuple in R

R

and y is a tuple in S

S

  • – RR and SS need not be union compatible
  • • RR × SS is expensive to compute:
  • Factor of two in the size of each row
  • Quadratic in the number of rows

A B C D A B C D

x1 x2 y1 y2 x1 x2 y1 y

x3 x4 y3 y4 x1 x2 y3 y

x3 x4 y1 y

R

R

S

S x3 x4 y3 y

R R

× SS

16

Renaming

  • Result of expression evaluation is a relation
  • Attributes of relation must have distinct names.

This is not guaranteed with Cartesian product

  • e.g., suppose in previous example a and c have the

same name

  • Renaming operator tidies this up. To assign the

names A

1

, A

2

,… A

n

to the attributes of the n

column relation produced by expression expr use

expr [ A

1

, A

2

, … A

n

]

19

Join and Renaming

  • Problem : R and S might have attributes with the

same name – in which case the Cartesian

product is not defined

  • Solutions :
    1. Rename attributes prior to forming the product and

use new names in join-condition ´.

  1. Qualify common attribute names with relation names

(thereby disambiguating the names). For instance:

Transcript.Transcript. CrsCode

CrsCode or Teaching.Teaching. CrsCode

CrsCode

  • This solution is nice, but doesn’t always work: consider

R

R

join_condition

R

R

In RR.A , how do we know which R is meant?

20

Theta Join – Example

Employee(

Employee( Name,Id,MngrId,Salary

Name,Id,MngrId,Salary )

Manager(

Manager( Name,Id,Salary

Name,Id,Salary )

Output the names of all employees that earn

more than their managers.

π

EmployeeEmployee .Name

EmployeeEmployee

MngrId=Id

AND Salary>Salary

ManagerManager

The join yields a table with attributes:

EmployeeEmployee. Name , EmployeeEmployee. Id , EmployeeEmployee. Salary , MngrId

Manager

Manager. Name , Manager

Manager. Id , Manager

Manager. Salary

21

Equijoin Join - Example

π

Name,CrsCode

(StudentStudent

Id=StudId

σ

Grade=‘A’

Transcript

Transcript))

Id Name Addr Status

111 John ….. …..

222 Mary ….. …..

333 Bill ….. …..

444 Joe ….. …..

StudId CrsCode Sem Grade

111 CSE305 S00 B

222 CSE306 S99 A

333 CSE304 F99 A

Mary CSE

Bill CSE

The equijoin is used very

frequently since it combines

related data in different relations.

Student

Student

Transcript

Transcript

Equijoin

Equijoin : Join condition is a conjunction of equalities.

22

Natural Join

  • Special case of equijoin:
    • join condition equates all and only those attributes with the

same name (condition doesn’t have to be explicitly stated)

  • duplicate columns eliminated from the result

TranscriptTranscript ( StudId, CrsCode, Sem, Grade )

Teaching (

Teaching ( ProfId, CrsCode, Sem )

Transcript

Transcript Teaching

Teaching =

π

StudId, Transcript.CrsCode, Transcript.Sem, Grade, ProfId

Transcript

Transcript

CrsCode=CrsCode AND Sem=SemSem

Teaching

Teaching )

[

StudId, CrsCode, Sem, Grade, ProfId

]

25

Division

  • Goal: Produce the tuples in one relation, r,

that match all tuples in another relation, s

  • – rr (A

1

, …A

n

, B

1

, …B

m

s

s (B

1

…B

m

r

r/ s

s , with attributes A

1

, …A

n

, is the set of all tuples

__ such that for every tuple in s

_s, _ is

in rr

  • Can be expressed in terms of projection, set

difference, and cross-product

26

Division (cont’d)

27

Division - Example

  • List the Ids of students who have passed

all

courses that were taught in spring 2000

  • Numerator :
    • StudId and CrsCode for every course passed by

every student:

π

StudId, CrsCode

( σ

Grade ≠

‘F’

(TranscriptTranscript) )

  • Denominator :

CrsCode

of all courses taught in spring 2000

π

CrsCode

( σ

Semester=‘S2000’

Teaching

Teaching) )

  • Result is numerator/denominator

28

Schema for Student Registration System

Student

Student ( Id, Name, Addr, Status )

Professor

Professor ( Id, Name, DeptId )

Course Course ( DeptId, CrsCode, CrsName, Descr )

Transcript Transcript ( StudId, CrsCode, Semester, Grade )

Teaching Teaching ( ProfId, CrsCode, Semester )

Department

Department ( DeptId, Name )

31

Correspondence Between SQL and

Relational Algebra

SELECT C. CrsName

FROM CourseCourse C, TeachingTeaching T

WHERE C. CrsCode = T. CrsCode AND T. Semester = ‘S2000’

Also equivalent to:

π

CrsName

σ

C CrsCode=T_CrsCode AND Semester=‘_ S2000’

(CourseCourse [ C_CrsCode, DeptId, CrsName, Desc ]

× TeachingTeaching

[

ProfId, T_CrsCode, Semester

])

  • This is the simplest evaluation algorithm for SELECT.
  • Relational algebra expressions are procedural.

Which of the two equivalent expressions is more easily evaluated?

32

Self-join Queries

Find Ids of all professors who taught at least two

courses in the same semester:

SELECT T1. ProfId

FROM Teaching

Teaching T1, Teaching

Teaching T

WHERE T1. ProfId = T2. ProfId

AND T1. Semester = T2. Semester

AND T1. CrsCode <> T2. CrsCode

Tuple variables are essential in this query!

Equivalent to:

π

ProfId

( σ

T1.CrsCode ≠

T2.CrsCode

( Teaching

Teaching[ ProfId, T1.CrsCode, Semester ]

Teaching

Teaching[ ProfId, T2.CrsCode, Semester ]))

33

Duplicates

  • Duplicate rows not allowed in a relation
  • However, duplicate elimination from query

result is costly and not done by default;

must be explicitly requested:

SELECT DISTINCT …..

FROM …..

34

Equality and comparison operators apply to

strings (based on lexical ordering)

WHERE S. Name < ‘P’

Use of Expressions

Concatenate operator applies to strings

WHERE

S.

Name

|| ‘--’ || S.

Address

Expressions can also be used in SELECT clause:

SELECT S. Name || ‘--’ || S. Address AS NmAdd

FROM Student

Student S

37

Correlated Nested Queries

Output a row < prof, dept > if prof has taught a course

in dept.

(SELECT T.ProfId -- subquery

FROM TeachingTeaching T, CourseCourse C

WHERE T. CrsCode =C. CrsCode AND

C. DeptId =D. DeptId -- correlation

)

SELECT P. Name , D. Name -- outer query

FROM ProfessorProfessor P, DepartmentDepartment D

WHERE P. Id IN

-- set of all ProfId’s who have taught a course in D.DeptId

38

Correlated Nested Queries (con’t )

  • Tuple variables T and C are local to subquery
  • Tuple variables P and D are global to subquery

Correlation

Correlation : subquery uses a global variable, D

  • The value of D. DeptId parameterizes an evaluation of

the subquery

  • Subquery must (at least) be re-evaluated for each

distinct value of D. DeptId

  • Correlated queries can be expensive to evaluate

39

Division in SQL

  • Query type : Find the subset of items in one set that

are related to all items in another set

  • Example : Find professors who taught courses in all

departments

  • Why does this involve division?

ProfId DeptId DeptId

All department Ids

Contains row

< p,d > if professor

p taught a

course in

department d

π

ProfId,DeptId

(Teaching Course) / π

DeptId

(Department)

40

Division in SQL

• Strategy for implementing division in SQL :

  • Find set, A, of all departments in which a

particular professor, p , has taught a course

  • Find set, B, of all departments
  • Output p if A ⊇ B, or, equivalently, if B–A is

empty