+ All Categories
Home > Documents > Relational Model

Relational Model

Date post: 15-Mar-2016
Category:
Upload: devin-barlow
View: 38 times
Download: 0 times
Share this document with a friend
Description:
Relational Model. Example of a Relation. Basic Structure. Formally, given sets D 1 , D 2 , …. D n a relation r is a subset of D 1 x D 2 x … x D n Thus, a relation is a set of n -tuples ( a 1 , a 2 , …, a n ) where each a i  D i - PowerPoint PPT Presentation
88
Database System Concepts, 5 th Ed. ©Silberschatz, Korth and Sudarshan See www.db-book.com for conditions on re-use Relational Model Relational Model
Transcript
Page 1: Relational Model

Database System Concepts, 5th Ed.©Silberschatz, Korth and Sudarshan

See www.db-book.com for conditions on re-use

Relational ModelRelational Model

Page 2: Relational Model

©Silberschatz, Korth and Sudarshan2.2Database System Concepts - 5th Edition, June 15, 2005

Example of a RelationExample of a Relation

Page 3: Relational Model

©Silberschatz, Korth and Sudarshan2.3Database System Concepts - 5th Edition, June 15, 2005

Basic StructureBasic Structure

Formally, given sets D1, D2, …. Dn a relation r is a subset of

D1 x D2 x … x Dn

Thus, a relation is a set of n-tuples (a1, a2, …, an) where each ai Di

Example: Ifcustomer_name = {Jones, Smith, Curry, Lindsay}customer_street = {Main, North, Park}customer_city = {Harrison, Rye, Pittsfield}

Then r = { (Jones, Main, Harrison), (Smith, North, Rye), (Curry, North, Rye), (Lindsay, Park, Pittsfield) } is a relation over

customer_name x customer_street x customer_city

Page 4: Relational Model

©Silberschatz, Korth and Sudarshan2.4Database System Concepts - 5th Edition, June 15, 2005

Attribute TypesAttribute Types Each attribute of a relation has a name The set of allowed values for each attribute is called the domain of the

attribute Attribute values are (normally) required to be atomic; that is, indivisible

Note: multivalued attribute values are not atomic Note: composite attribute values are not atomic

The special value null is a member of every domain The null value causes complications in the definition of many operations

We shall ignore the effect of null values in our main presentation and consider their effect later

Page 5: Relational Model

©Silberschatz, Korth and Sudarshan2.5Database System Concepts - 5th Edition, June 15, 2005

Relation SchemaRelation Schema

A1, A2, …, An are attributes

R = (A1, A2, …, An ) is a relation schema

Example:

Customer_schema = (customer_name, customer_street, customer_city)

r(R) is a relation on the relation schema RExample:

customer (Customer_schema)

Page 6: Relational Model

©Silberschatz, Korth and Sudarshan2.6Database System Concepts - 5th Edition, June 15, 2005

Relation InstanceRelation Instance The current values (relation instance) of a relation are specified by a

table An element t of r is a tuple, represented by a row in a table

JonesSmithCurryLindsay

customer_name

MainNorthNorthPark

customer_street

HarrisonRyeRyePittsfield

customer_city

customer

attributes(or columns)

tuples(or rows)

Page 7: Relational Model

©Silberschatz, Korth and Sudarshan2.7Database System Concepts - 5th Edition, June 15, 2005

Relations are UnorderedRelations are Unordered

Order of tuples is irrelevant (tuples may be stored in an arbitrary order) Example: account relation with unordered tuples

Page 8: Relational Model

©Silberschatz, Korth and Sudarshan2.8Database System Concepts - 5th Edition, June 15, 2005

The The depositor depositor RelationRelation

Page 9: Relational Model

©Silberschatz, Korth and Sudarshan2.9Database System Concepts - 5th Edition, June 15, 2005

Query LanguagesQuery Languages Language in which user requests information from the database. Categories of languages

Procedural Non-procedural, or declarative

“Pure” languages: Relational algebra Tuple relational calculus Domain relational calculus

Pure languages form underlying basis of query languages that people use.

Page 10: Relational Model

©Silberschatz, Korth and Sudarshan2.10Database System Concepts - 5th Edition, June 15, 2005

Relational AlgebraRelational Algebra Procedural language Six basic operators

select: project: union: set difference: – Cartesian product: x rename:

The operators take one or two relations as inputs and produce a new relation as a result.

Page 11: Relational Model

©Silberschatz, Korth and Sudarshan2.11Database System Concepts - 5th Edition, June 15, 2005

Select Operation – ExampleSelect Operation – Example Relation r

A B C D

1

5

12

23

7

7

3

10

A=B ^ D > 5 (r)A B C D

1

23

7

10

Page 12: Relational Model

©Silberschatz, Korth and Sudarshan2.12Database System Concepts - 5th Edition, June 15, 2005

Select OperationSelect Operation Notation: p(r) p is called the selection predicate Defined as:

p(r) = {t | t r and p(t)}

Where p is a formula in propositional calculus consisting of terms connected by : (and), (or), (not)Each term is one of:

<attribute> op <attribute> or <constant> where op is one of: =, , >, . <.

Example of selection:

branch_name=“Perryridge”(account)

Page 13: Relational Model

©Silberschatz, Korth and Sudarshan2.13Database System Concepts - 5th Edition, June 15, 2005

Project Operation – ExampleProject Operation – Example Relation r: A B C

10

20

30

40

1

1

1

2

A C

1

1

1

2

=

A C

1

1

2

A,C (r)

Page 14: Relational Model

©Silberschatz, Korth and Sudarshan2.14Database System Concepts - 5th Edition, June 15, 2005

Project OperationProject Operation

Notation:

where A1, A2 are attribute names and r is a relation name.

The result is defined as the relation of k columns obtained by erasing the columns that are not listed

Duplicate rows removed from result, since relations are sets Example: To eliminate the branch_name attribute of account

account_number, balance (account)

)( ,,, 21r

kAAA

Page 15: Relational Model

©Silberschatz, Korth and Sudarshan2.15Database System Concepts - 5th Edition, June 15, 2005

Union Operation – ExampleUnion Operation – Example Relations r, s:

r s:

A B

1

2

1

A B

2

3

rs

A B

1

2

1

3

Page 16: Relational Model

©Silberschatz, Korth and Sudarshan2.16Database System Concepts - 5th Edition, June 15, 2005

Union OperationUnion Operation Notation: r s Defined as:

r s = {t | t r or t s} For r s to be valid.

1. r, s must have the same arity (same number of attributes)

2. The attribute domains must be compatible (example: 2nd column of r deals with the same type of values as does the 2nd

column of s)

Example: to find all customers with either an account or a loan

customer_name (depositor) customer_name (borrower)

Page 17: Relational Model

©Silberschatz, Korth and Sudarshan2.17Database System Concepts - 5th Edition, June 15, 2005

Set Difference Operation – ExampleSet Difference Operation – Example

Relations r, s:

r – s:

A B

1

2

1

A B

2

3

rs

A B

1

1

Page 18: Relational Model

©Silberschatz, Korth and Sudarshan2.18Database System Concepts - 5th Edition, June 15, 2005

Set Difference OperationSet Difference Operation Notation r – s Defined as:

r – s = {t | t r and t s}

Set differences must be taken between compatible relations.

r and s must have the same arity attribute domains of r and s must be compatible

Page 19: Relational Model

©Silberschatz, Korth and Sudarshan2.19Database System Concepts - 5th Edition, June 15, 2005

Cartesian-Product Operation – ExampleCartesian-Product Operation – Example

Relations r, s:

r x s:

A B

1

2

A B

11112222

C D

1010201010102010

E

aabbaabb

C D

10102010

E

aabbr

s

Page 20: Relational Model

©Silberschatz, Korth and Sudarshan2.20Database System Concepts - 5th Edition, June 15, 2005

Cartesian-Product OperationCartesian-Product Operation Notation r x s Defined as:

r x s = {t q | t r and q s}

Assume that attributes of r(R) and s(S) are disjoint. (That is, R S = ). If attributes of r(R) and s(S) are not disjoint, then renaming must be

used.

Page 21: Relational Model

©Silberschatz, Korth and Sudarshan2.21Database System Concepts - 5th Edition, June 15, 2005

Rename OperationRename Operation Allows us to name, and therefore to refer to, the results of relational-

algebra expressions. Allows us to refer to a relation by more than one name. Example:

x (E)

returns the expression E under the name X If a relational-algebra expression E has arity n, then

returns the result of expression E under the name X, and with the

attributes renamed to A1 , A2 , …., An .

)(),...,,( 21E

nAAAx

Page 22: Relational Model

©Silberschatz, Korth and Sudarshan2.22Database System Concepts - 5th Edition, June 15, 2005

Banking ExampleBanking Examplebranch (branch_name, branch_city, assets)

customer (customer_name, customer_street, customer_city)

account (account_number, branch_name, balance)

loan (loan_number, branch_name, amount)

depositor (customer_name, account_number)

borrower (customer_name, loan_number)

Page 23: Relational Model

©Silberschatz, Korth and Sudarshan2.23Database System Concepts - 5th Edition, June 15, 2005

Example QueriesExample Queries Find all loans of over $1200

Find the loan number for each loan of an amount greater than $1200

amount > 1200 (loan)

loan_number (amount > 1200 (loan))

Page 24: Relational Model

©Silberschatz, Korth and Sudarshan2.24Database System Concepts - 5th Edition, June 15, 2005

Example QueriesExample Queries Find the names of all customers who have a loan, an account, or both,

from the bank

Find the names of all customers who have a loan and an account at bank.

customer_name (borrower) customer_name (depositor)

customer_name (borrower) customer_name (depositor)

Page 25: Relational Model

©Silberschatz, Korth and Sudarshan2.25Database System Concepts - 5th Edition, June 15, 2005

Example QueriesExample Queries Find the names of all customers who have a loan at the Perryridge

branch.

Find the names of all customers who have a loan at the Perryridge branch but do not have an account at any branch of the bank.

customer_name (branch_name = “Perryridge”

(borrower.loan_number = loan.loan_number(borrower x loan))) –

customer_name(depositor)

customer_name (branch_name=“Perryridge”

(borrower.loan_number = loan.loan_number(borrower x loan)))

Page 26: Relational Model

©Silberschatz, Korth and Sudarshan2.26Database System Concepts - 5th Edition, June 15, 2005

Example QueriesExample Queries Find the names of all customers who have a loan at the Perryridge branch.

Query 2

customer_name(loan.loan_number = borrower.loan_number (

(branch_name = “Perryridge” (loan)) x borrower))

Query 1

customer_name (branch_name = “Perryridge” (

borrower.loan_number = loan.loan_number (borrower x loan)))

Page 27: Relational Model

©Silberschatz, Korth and Sudarshan2.27Database System Concepts - 5th Edition, June 15, 2005

Example QueriesExample Queries Find the largest account balance

Strategy: Find those balances that are not the largest

– Rename account relation as d so that we can compare each account balance with all others

Use set difference to find those account balances that were not found in the earlier step.

The query is:

balance(account) - account.balance

(account.balance < d.balance (account x d (account)))

Page 28: Relational Model

©Silberschatz, Korth and Sudarshan2.28Database System Concepts - 5th Edition, June 15, 2005

Additional OperationsAdditional Operations

We define additional operations that do not add any power to the

relational algebra, but that simplify common queries.

Set intersection Natural join Division Assignment

Page 29: Relational Model

©Silberschatz, Korth and Sudarshan2.29Database System Concepts - 5th Edition, June 15, 2005

Set-Intersection OperationSet-Intersection Operation Notation: r s Defined as: r s = { t | t r and t s } Assume:

r, s have the same arity attributes of r and s are compatible

Note: r s = r – (r – s)

Page 30: Relational Model

©Silberschatz, Korth and Sudarshan2.30Database System Concepts - 5th Edition, June 15, 2005

Set-Intersection Operation – ExampleSet-Intersection Operation – Example

Relation r, s:

r s

A B

121

A B

23

r s

A B

2

Page 31: Relational Model

©Silberschatz, Korth and Sudarshan2.31Database System Concepts - 5th Edition, June 15, 2005

Notation: r s

Natural-Join OperationNatural-Join Operation

Let r and s be relations on schemas R and S respectively. Then, r s is a relation on schema R S obtained as follows:

Consider each pair of tuples tr from r and ts from s.

If tr and ts have the same value on each of the attributes in R S, add a tuple t to the result, where

t has the same value as tr on r

t has the same value as ts on s

Example:

R = (A, B, C, D)

S = (E, B, D) Result schema = (A, B, C, D, E) r s is defined as:

r.A, r.B, r.C, r.D, s.E (r.B = s.B r.D = s.D (r x s))

Page 32: Relational Model

©Silberschatz, Korth and Sudarshan2.32Database System Concepts - 5th Edition, June 15, 2005

Natural Join Operation – ExampleNatural Join Operation – Example Relations r, s:

A B

12412

C D

aabab

B

13123

D

aaabb

E

r

A B

11112

C D

aaaab

E

s

r s

Page 33: Relational Model

©Silberschatz, Korth and Sudarshan2.33Database System Concepts - 5th Edition, June 15, 2005

Division OperationDivision Operation

Notation: Suited to queries that include the phrase “for all”.

Let r and s be relations on schemas R and S respectively where

R = (A1, …, Am , B1, …, Bn )

S = (B1, …, Bn)

The result of r s is a relation on schema

R – S = (A1, …, Am)

r s = { t | t R-S (r) u s ( tu r ) }

Where tu means the concatenation of tuples t and u to produce a single tuple

r s

Page 34: Relational Model

©Silberschatz, Korth and Sudarshan2.34Database System Concepts - 5th Edition, June 15, 2005

Division Operation – ExampleDivision Operation – Example

Relations r, s:

r s: A

B

1

2

A B

12311134612

r

s

Page 35: Relational Model

©Silberschatz, Korth and Sudarshan2.35Database System Concepts - 5th Edition, June 15, 2005

Another Division ExampleAnother Division Example

A B

aaaaaaaa

C D

aabababb

E

11113111

Relations r, s:

r s:

D

ab

E

11

A B

aa

C

r

s

Page 36: Relational Model

©Silberschatz, Korth and Sudarshan2.36Database System Concepts - 5th Edition, June 15, 2005

Division Operation (Cont.)Division Operation (Cont.) Property

Let q = r s Then q is the largest relation satisfying q x s r

Definition in terms of the basic algebra operationLet r(R) and s(S) be relations, and let S R

r s = R-S (r ) – R-S ( ( R-S (r ) x s ) – R-S,S(r ))

To see why R-S,S (r) simply reorders attributes of r

R-S (R-S (r ) x s ) – R-S,S(r) ) gives those tuples t in

R-S (r ) such that for some tuple u s, tu r.

Page 37: Relational Model

©Silberschatz, Korth and Sudarshan2.37Database System Concepts - 5th Edition, June 15, 2005

Assignment OperationAssignment Operation

The assignment operation () provides a convenient way to express complex queries. Write query as a sequential program consisting of

a series of assignments followed by an expression whose value is displayed as a result of

the query. Assignment must always be made to a temporary relation variable.

Example: Write r s as

temp1 R-S (r )

temp2 R-S ((temp1 x s ) – R-S,S (r ))

result = temp1 – temp2

The result to the right of the is assigned to the relation variable on the left of the .

May use variable in subsequent expressions.

Page 38: Relational Model

©Silberschatz, Korth and Sudarshan2.38Database System Concepts - 5th Edition, June 15, 2005

Modification of the DatabaseModification of the Database The content of the database may be modified using the following

operations: Deletion Insertion Updating

All these operations are expressed using the assignment operator.

Page 39: Relational Model

©Silberschatz, Korth and Sudarshan2.39Database System Concepts - 5th Edition, June 15, 2005

DeletionDeletion A delete request is expressed similarly to a query, except

instead of displaying tuples to the user, the selected tuples are removed from the database.

Can delete only whole tuples; cannot delete values on only particular attributes

A deletion is expressed in relational algebra by:

r r – Ewhere r is a relation and E is a relational algebra query.

Page 40: Relational Model

©Silberschatz, Korth and Sudarshan2.40Database System Concepts - 5th Edition, June 15, 2005

Deletion ExamplesDeletion Examples Delete all account records in the Perryridge branch.

Delete all accounts at branches located in Needham.

r1 branch_city = “Needham” (account branch )

r2 branch_name, account_number, balance (r1)

r3 customer_name, account_number (r2 depositor)

account account – r2

depositor depositor – r3

Delete all loan records with amount in the range of 0 to 50

loan loan – amount 0and amount 50 (loan)

account account – branch_name = “Perryridge” (account )

Page 41: Relational Model

©Silberschatz, Korth and Sudarshan2.41Database System Concepts - 5th Edition, June 15, 2005

InsertionInsertion

To insert data into a relation, we either: specify a tuple to be inserted write a query whose result is a set of tuples to be inserted

in relational algebra, an insertion is expressed by:

r r Ewhere r is a relation and E is a relational algebra expression.

The insertion of a single tuple is expressed by letting E be a constant relation containing one tuple.

Page 42: Relational Model

©Silberschatz, Korth and Sudarshan2.42Database System Concepts - 5th Edition, June 15, 2005

Insertion ExamplesInsertion Examples Insert information in the database specifying that Smith has $1200 in

account A-973 at the Perryridge branch.

Provide as a gift for all loan customers in the Perryridge branch, a $200 savings account. Let the loan number serve as the account number for the new savings account.

account account {(“Perryridge”, A-973, 1200)}

depositor depositor {(“Smith”, A-973)}

r1 (branch_name = “Perryridge” (borrower loan))

account account branch_name, loan_number,200 (r1)

depositor depositor customer_name, loan_number (r1)

Page 43: Relational Model

©Silberschatz, Korth and Sudarshan2.43Database System Concepts - 5th Edition, June 15, 2005

UpdatingUpdating

A mechanism to change a value in a tuple without charging all values in the tuple

Use the generalized projection operator to do this task

Each Fi is either

the I th attribute of r, if the I th attribute is not updated, or, if the attribute is to be updated Fi is an expression, involving only

constants and the attributes of r, which gives the new value for the attribute

)(,,,, 21rr

lFFF

Page 44: Relational Model

©Silberschatz, Korth and Sudarshan2.44Database System Concepts - 5th Edition, June 15, 2005

Update ExamplesUpdate Examples

Make interest payments by increasing all balances by 5 percent.

Pay all accounts with balances over $10,000 6 percent interest and pay all others 5 percent

account account_number, branch_name, balance * 1.06 ( BAL 10000 (account )) account_number, branch_name, balance * 1.05 (BAL 10000 (account))

account account_number, branch_name, balance * 1.05 (account)

Page 45: Relational Model

Database System Concepts, 5th Ed.©Silberschatz, Korth and Sudarshan

See www.db-book.com for conditions on re-use

SQLSQL

Page 46: Relational Model

©Silberschatz, Korth and Sudarshan2.46Database System Concepts - 5th Edition, June 15, 2005

Data Definition LanguageData Definition Language

The schema for each relation. The domain of values associated with each attribute. Integrity constraints The set of indices to be maintained for each relations. Security and authorization information for each relation. The physical storage structure of each relation on disk.

Allows the specification of not only a set of relations but also information about each relation, including:

Page 47: Relational Model

©Silberschatz, Korth and Sudarshan2.47Database System Concepts - 5th Edition, June 15, 2005

Domain Types in SQLDomain Types in SQL char(n). Fixed length character string, with user-specified length n. varchar(n). Variable length character strings, with user-specified maximum

length n. int. Integer (a finite subset of the integers that is machine-dependent). smallint. Small integer (a machine-dependent subset of the integer

domain type). numeric(p,d). Fixed point number, with user-specified precision of p digits,

with n digits to the right of decimal point. real, double precision. Floating point and double-precision floating point

numbers, with machine-dependent precision. float(n). Floating point number, with user-specified precision of at least n

digits. More are covered in Chapter 4.

Page 48: Relational Model

©Silberschatz, Korth and Sudarshan2.48Database System Concepts - 5th Edition, June 15, 2005

Create Table ConstructCreate Table Construct

An SQL relation is defined using the create table command:

create table r (A1 D1, A2 D2, ..., An Dn,(integrity-constraint1),...,(integrity-constraintk))

r is the name of the relation each Ai is an attribute name in the schema of relation r Di is the data type of values in the domain of attribute Ai

Example:create table branch

(branch_name char(15) not null,branch_city char(30),assets integer)

Page 49: Relational Model

©Silberschatz, Korth and Sudarshan2.49Database System Concepts - 5th Edition, June 15, 2005

Integrity Constraints in Create TableIntegrity Constraints in Create Table

not null primary key (A1, ..., An )

Example: Declare branch_name as the primary key for branch and ensure that the values of assets are non-negative.

create table branch (branch_name char(15), branch_city char(30), assets integer, primary key (branch_name))

primary key declaration on an attribute automatically ensures not null in SQL-92 onwards, needs to be explicitly stated in SQL-89

Page 50: Relational Model

©Silberschatz, Korth and Sudarshan2.50Database System Concepts - 5th Edition, June 15, 2005

Drop and Alter Table ConstructsDrop and Alter Table Constructs

The drop table command deletes all information about the dropped relation from the database.

The alter table command is used to add attributes to an existing relation:

alter table r add A D

where A is the name of the attribute to be added to relation r and D is the domain of A.

All tuples in the relation are assigned null as the value for the new attribute.

The alter table command can also be used to drop attributes of a relation:

alter table r drop A

where A is the name of an attribute of relation r Dropping of attributes not supported by many databases

Page 51: Relational Model

©Silberschatz, Korth and Sudarshan2.51Database System Concepts - 5th Edition, June 15, 2005

Basic Query Structure Basic Query Structure

SQL is based on set and relational operations with certain modifications and enhancements

A typical SQL query has the form:

select A1, A2, ..., An

from r1, r2, ..., rmwhere P

Ai represents an attribute Ri represents a relation P is a predicate.

This query is equivalent to the relational algebra expression.

The result of an SQL query is a relation.

))(( 21,,, 21 mPAAA rrrn

Page 52: Relational Model

©Silberschatz, Korth and Sudarshan2.52Database System Concepts - 5th Edition, June 15, 2005

The select ClauseThe select Clause

The select clause list the attributes desired in the result of a query corresponds to the projection operation of the relational algebra

Example: find the names of all branches in the loan relation:select branch_namefrom loan

In the relational algebra, the query would be:

branch_name (loan)

NOTE: SQL names are case insensitive (i.e., you may use upper- or lower-case letters.)

Some people use upper case wherever we use bold font.

Page 53: Relational Model

©Silberschatz, Korth and Sudarshan2.53Database System Concepts - 5th Edition, June 15, 2005

The select Clause (Cont.)The select Clause (Cont.)

SQL allows duplicates in relations as well as in query results. To force the elimination of duplicates, insert the keyword distinct after

select. Find the names of all branches in the loan relations, and remove

duplicates

select distinct branch_namefrom loan

The keyword all specifies that duplicates not be removed.

select all branch_namefrom loan

Page 54: Relational Model

©Silberschatz, Korth and Sudarshan2.54Database System Concepts - 5th Edition, June 15, 2005

The select Clause (Cont.)The select Clause (Cont.)

An asterisk in the select clause denotes “all attributes”

select *from loan

The select clause can contain arithmetic expressions involving the operation, +, –, , and /, and operating on constants or attributes of tuples.

The query:

select loan_number, branch_name, amount 100 from loanwould return a relation that is the same as the loan relation, except that the value of the attribute amount is multiplied by 100.

Page 55: Relational Model

©Silberschatz, Korth and Sudarshan2.55Database System Concepts - 5th Edition, June 15, 2005

The where ClauseThe where Clause

The where clause specifies conditions that the result must satisfy Corresponds to the selection predicate of the relational algebra.

To find all loan number for loans made at the Perryridge branch with loan amounts greater than $1200.

select loan_numberfrom loanwhere branch_name = ‘ Perryridge’ and amount > 1200

Comparison results can be combined using the logical connectives and, or, and not.

Comparisons can be applied to results of arithmetic expressions.

Page 56: Relational Model

©Silberschatz, Korth and Sudarshan2.56Database System Concepts - 5th Edition, June 15, 2005

The where Clause (Cont.)The where Clause (Cont.)

SQL includes a between comparison operator Example: Find the loan number of those loans with loan amounts between

$90,000 and $100,000 (that is, $90,000 and $100,000)

select loan_numberfrom loanwhere amount between 90000 and 100000

Page 57: Relational Model

©Silberschatz, Korth and Sudarshan2.57Database System Concepts - 5th Edition, June 15, 2005

The from ClauseThe from Clause

The from clause lists the relations involved in the query Corresponds to the Cartesian product operation of the relational algebra.

Find the Cartesian product borrower X loanselect from borrower, loan

Find the name, loan number and loan amount of all customers having a loan at the Perryridge branch.

select customer_name, borrower.loan_number, amount from borrower, loan where borrower.loan_number = loan.loan_number and branch_name = ‘Perryridge’

Page 58: Relational Model

©Silberschatz, Korth and Sudarshan2.58Database System Concepts - 5th Edition, June 15, 2005

The Rename OperationThe Rename Operation

The SQL allows renaming relations and attributes using the as clause:

old-name as new-name Find the name, loan number and loan amount of all customers; rename the

column name loan_number as loan_id.

select customer_name, borrower.loan_number as loan_id, amountfrom borrower, loanwhere borrower.loan_number = loan.loan_number

Page 59: Relational Model

©Silberschatz, Korth and Sudarshan2.59Database System Concepts - 5th Edition, June 15, 2005

Tuple VariablesTuple Variables

Tuple variables are defined in the from clause via the use of the as clause.

Find the customer names and their loan numbers for all customers having a loan at some branch.

select distinct T.branch_name from branch as T, branch as S where T.assets > S.assets and S.branch_city = ‘ Brooklyn’

Find the names of all branches that have greater assets than some branch located in Brooklyn.

select customer_name, T.loan_number, S.amount from borrower as T, loan as S where T.loan_number = S.loan_number

Page 60: Relational Model

©Silberschatz, Korth and Sudarshan2.60Database System Concepts - 5th Edition, June 15, 2005

String OperationsString Operations

SQL includes a string-matching operator for comparisons on character strings. The operator “like” uses patterns that are described using two special characters:

percent (%). The % character matches any substring. underscore (_). The _ character matches any character.

Find the names of all customers whose street includes the substring “Main”.

select customer_namefrom customerwhere customer_street like ‘%Main%’

Match the name “Main%”like ‘Main\%’ escape ‘\’

SQL supports a variety of string operations such as concatenation (using “||”) converting from upper to lower case (and vice versa) finding string length, extracting substrings, etc.

Page 61: Relational Model

©Silberschatz, Korth and Sudarshan2.61Database System Concepts - 5th Edition, June 15, 2005

Ordering the Display of TuplesOrdering the Display of Tuples

List in alphabetic order the names of all customers having a loan in Perryridge branch

select distinct customer_namefrom borrower, loanwhere borrower loan_number = loan.loan_number and branch_name = ‘Perryridge’order by customer_name

We may specify desc for descending order or asc for ascending order, for each attribute; ascending order is the default.

Example: order by customer_name desc

Page 62: Relational Model

©Silberschatz, Korth and Sudarshan2.62Database System Concepts - 5th Edition, June 15, 2005

Set OperationsSet Operations

The set operations union, intersect, and except operate on relations and correspond to the relational algebra operations

Each of the above operations automatically eliminates duplicates; to retain all duplicates use the corresponding multiset versions union all, intersect all and except all.

Suppose a tuple occurs m times in r and n times in s, then, it occurs: m + n times in r union all s min(m,n) times in r intersect all s max(0, m – n) times in r except all s

Page 63: Relational Model

©Silberschatz, Korth and Sudarshan2.63Database System Concepts - 5th Edition, June 15, 2005

Set OperationsSet Operations

Find all customers who have a loan, an account, or both:

(select customer_name from depositor)except(select customer_name from borrower)

(select customer_name from depositor)intersect(select customer_name from borrower)

Find all customers who have an account but no loan.

(select customer_name from depositor)union(select customer_name from borrower)

Find all customers who have both a loan and an account.

Page 64: Relational Model

©Silberschatz, Korth and Sudarshan2.64Database System Concepts - 5th Edition, June 15, 2005

Aggregate FunctionsAggregate Functions

These functions operate on the multiset of values of a column of a relation, and return a value

avg: average valuemin: minimum valuemax: maximum valuesum: sum of valuescount: number of values

Page 65: Relational Model

©Silberschatz, Korth and Sudarshan2.65Database System Concepts - 5th Edition, June 15, 2005

Aggregate Functions (Cont.)Aggregate Functions (Cont.)

Find the average account balance at the Perryridge branch.

Find the number of depositors in the bank.

Find the number of tuples in the customer relation.

select avg (balance)from accountwhere branch_name = ‘Perryridge’

select count (*)from customer

select count (distinct customer_name)from depositor

Page 66: Relational Model

©Silberschatz, Korth and Sudarshan2.66Database System Concepts - 5th Edition, June 15, 2005

Aggregate Functions – Group ByAggregate Functions – Group By

Find the number of depositors for each branch.

Note: Attributes in select clause outside of aggregate functions must appear in group by list

select branch_name, count (distinct customer_name) from depositor, account where depositor.account_number = account.account_number group by branch_name

Page 67: Relational Model

©Silberschatz, Korth and Sudarshan2.67Database System Concepts - 5th Edition, June 15, 2005

Aggregate Functions – Having ClauseAggregate Functions – Having Clause

Find the names of all branches where the average account balance is more than $1,200.

Note: predicates in the having clause are applied after the formation of groups whereas predicates in the where clause are applied before forming groups

select branch_name, avg (balance) from account group by branch_name having avg (balance) > 1200

Page 68: Relational Model

©Silberschatz, Korth and Sudarshan2.68Database System Concepts - 5th Edition, June 15, 2005

Null ValuesNull Values

It is possible for tuples to have a null value, denoted by null, for some of their attributes

null signifies an unknown value or that a value does not exist. The predicate is null can be used to check for null values.

Example: Find all loan number which appear in the loan relation with null values for amount.

select loan_numberfrom loanwhere amount is null

The result of any arithmetic expression involving null is null Example: 5 + null returns null

However, aggregate functions simply ignore nulls More on next slide

Page 69: Relational Model

©Silberschatz, Korth and Sudarshan2.69Database System Concepts - 5th Edition, June 15, 2005

Nested SubqueriesNested Subqueries

SQL provides a mechanism for the nesting of subqueries. A subquery is a select-from-where expression that is nested within

another query. A common use of subqueries is to perform tests for set membership, set

comparisons, and set cardinality.

Page 70: Relational Model

©Silberschatz, Korth and Sudarshan2.70Database System Concepts - 5th Edition, June 15, 2005

Example QueryExample Query

Find all customers who have both an account and a loan at the bank.

Find all customers who have a loan at the bank but do not have an account at the bank

select distinct customer_namefrom borrowerwhere customer_name not in (select customer_name

from depositor )

select distinct customer_namefrom borrowerwhere customer_name in (select customer_name

from depositor )

Page 71: Relational Model

©Silberschatz, Korth and Sudarshan2.71Database System Concepts - 5th Edition, June 15, 2005

ViewsViews

In some cases, it is not desirable for all users to see the entire logical model (that is, all the actual relations stored in the database.)

Consider a person who needs to know a customer’s loan number but has no need to see the loan amount. This person should see a relation described, in SQL, by

(select customer_name, loan_number from borrower, loan where borrower.loan_number = loan.loan_number )

A view provides a mechanism to hide certain data from the view of certain users.

Any relation that is not of the conceptual model but is made visible to a user as a “virtual relation” is called a view.

Page 72: Relational Model

©Silberschatz, Korth and Sudarshan2.72Database System Concepts - 5th Edition, June 15, 2005

View DefinitionView Definition

A view is defined using the create view statement which has the form

create view v as < query expression >

where <query expression> is any legal SQL expression. The view name is represented by v.

Once a view is defined, the view name can be used to refer to the virtual relation that the view generates.

View definition is not the same as creating a new relation by evaluating the query expression

Rather, a view definition causes the saving of an expression; the expression is substituted into queries using the view.

Page 73: Relational Model

©Silberschatz, Korth and Sudarshan2.73Database System Concepts - 5th Edition, June 15, 2005

Example QueriesExample Queries

A view consisting of branches and their customers

Find all customers of the Perryridge branch

create view all_customer as (select branch_name, customer_name from depositor, account where depositor.account_number =

account.account_number ) union (select branch_name, customer_name from borrower, loan where borrower.loan_number = loan.loan_number )

select customer_namefrom all_customerwhere branch_name = ‘Perryridge’

Page 74: Relational Model

©Silberschatz, Korth and Sudarshan2.74Database System Concepts - 5th Edition, June 15, 2005

Modification of the Database – DeletionModification of the Database – Deletion

Delete all account tuples at the Perryridge branch

delete from accountwhere branch_name = ‘Perryridge’

Delete all accounts at every branch located in the city ‘Needham’.

delete from accountwhere branch_name in (select branch_name

from branch where branch_city = ‘Needham’)

Page 75: Relational Model

©Silberschatz, Korth and Sudarshan2.75Database System Concepts - 5th Edition, June 15, 2005

Modification of the Database – InsertionModification of the Database – Insertion

Add a new tuple to accountinsert into account

values (‘A-9732’, ‘Perryridge’,1200)

or equivalently

insert into account (branch_name, balance, account_number) values (‘Perryridge’, 1200, ‘A-9732’)

Add a new tuple to account with balance set to null

insert into accountvalues (‘A-777’,‘Perryridge’, null )

Page 76: Relational Model

©Silberschatz, Korth and Sudarshan2.76Database System Concepts - 5th Edition, June 15, 2005

Modification of the Database – UpdatesModification of the Database – Updates

Increase all accounts with balances over $10,000 by 6%, all other accounts receive 5%.

Write two update statements:

update accountset balance = balance 1.06where balance > 10000

update accountset balance = balance 1.05where balance 10000

The order is important Can be done better using the case statement (next slide)

Page 77: Relational Model

©Silberschatz, Korth and Sudarshan2.77Database System Concepts - 5th Edition, June 15, 2005

Updates Through Views (Cont.)Updates Through Views (Cont.)

Some updates through views are impossible to translate into updates on the database relations

create view v asselect branch_name from account

insert into v values (‘L-99’, ‘ Downtown’, ‘23’)

Others cannot be translated uniquely insert into all_customer values (‘ Perryridge’, ‘John’)

Have to choose loan or account, and create a new loan/account number!

Most SQL implementations allow updates only on simple views (without aggregates) defined on a single relation

Page 78: Relational Model

©Silberschatz, Korth and Sudarshan2.78Database System Concepts - 5th Edition, June 15, 2005

Joined Relations**Joined Relations**

Join operations take two relations and return as a result another relation.

These additional operations are typically used as subquery expressions in the from clause

Join condition – defines which tuples in the two relations match, and what attributes are present in the result of the join.

Join type – defines how tuples in each relation that do not match any tuple in the other relation (based on the join condition) are treated.

Page 79: Relational Model

©Silberschatz, Korth and Sudarshan2.79Database System Concepts - 5th Edition, June 15, 2005

Joined Relations – Datasets for ExamplesJoined Relations – Datasets for Examples

Relation loan

Relation borrower

Note: borrower information missing for L-260 and loan information missing for L-155

Page 80: Relational Model

©Silberschatz, Korth and Sudarshan2.80Database System Concepts - 5th Edition, June 15, 2005

Joined Relations – Examples Joined Relations – Examples

loan inner join borrower onloan.loan_number = borrower.loan_number

loan left outer join borrower onloan.loan_number = borrower.loan_number

Page 81: Relational Model

©Silberschatz, Korth and Sudarshan2.81Database System Concepts - 5th Edition, June 15, 2005

Joined Relations – ExamplesJoined Relations – Examples

loan natural inner join borrower

loan natural right outer join borrower

Page 82: Relational Model

©Silberschatz, Korth and Sudarshan2.82Database System Concepts - 5th Edition, June 15, 2005

Joined Relations – ExamplesJoined Relations – Examples

loan full outer join borrower using (loan_number)

Find all customers who have either an account or a loan (but not both) at the bank.

select customer_namefrom (depositor natural full outer join borrower )where account_number is null or loan_number is null

Page 83: Relational Model

©Silberschatz, Korth and Sudarshan2.83Database System Concepts - 5th Edition, June 15, 2005

Tuple Relational CalculusTuple Relational Calculus

A nonprocedural query language, where each query is of the form

{t | P (t ) } It is the set of all tuples t such that predicate P is true for t t is a tuple variable, t [A ] denotes the value of tuple t on attribute A t r denotes that tuple t is in relation r P is a formula similar to that of the predicate calculus

Page 84: Relational Model

©Silberschatz, Korth and Sudarshan2.84Database System Concepts - 5th Edition, June 15, 2005

Example QueriesExample Queries

Find the loan_number, branch_name, and amount for loans of over $1200

Find the loan number for each loan of an amount greater than $1200

{t | s loan (t [loan_number ] = s [loan_number ] s [amount ] 1200)}

Notice that a relation on schema [loan_number ] is implicitly defined by

the query

{t | t loan t [amount ] 1200}

Page 85: Relational Model

©Silberschatz, Korth and Sudarshan2.85Database System Concepts - 5th Edition, June 15, 2005

Example QueriesExample Queries

Find the names of all customers having a loan, an account, or both at the bank

{t | s borrower ( t [customer_name ] = s [customer_name ]) u depositor ( t [customer_name ] = u [customer_name] )

Find the names of all customers who have a loan and an account at the bank

{t | s borrower ( t [customer_name ] = s [customer_name ]) u depositor ( t [customer_name ] = u [customer_name ])

Page 86: Relational Model

©Silberschatz, Korth and Sudarshan2.86Database System Concepts - 5th Edition, June 15, 2005

Domain Relational CalculusDomain Relational Calculus

A nonprocedural query language equivalent in power to the tuple relational calculus

Each query is an expression of the form:

{ x1, x2, …, xn | P (x1, x2, …, xn)}

x1, x2, …, xn represent domain variables

P represents a formula similar to that of the predicate calculus

Page 87: Relational Model

©Silberschatz, Korth and Sudarshan2.87Database System Concepts - 5th Edition, June 15, 2005

Example QueriesExample Queries

Find the loan_number, branch_name, and amount for loans of over $1200

Find the names of all customers who have a loan from the Perryridge branch and the loan amount:

{ c, a | l ( c, l borrower b ( l, b, a loan

b = “Perryridge”))} { c, a | l ( c, l borrower l, “ Perryridge”, a loan)}

{ c | l, b, a ( c, l borrower l, b, a loan a > 1200)}

Find the names of all customers who have a loan of over $1200

{ l, b, a | l, b, a loan a > 1200}

Page 88: Relational Model

©Silberschatz, Korth and Sudarshan2.88Database System Concepts - 5th Edition, June 15, 2005

Example QueriesExample Queries

Find the names of all customers having a loan, an account, or both at the Perryridge branch:

{ c | s,n ( c, s, n customer)

x,y,z ( x, y, z branch y = “Brooklyn”) a,b ( x, y, z account c,a depositor)}

Find the names of all customers who have an account at all branches located in Brooklyn:

{ c | l ( c, l borrower b,a ( l, b, a loan b = “Perryridge”)) a ( c, a depositor b,n ( a, b, n account b = “Perryridge”))}


Recommended