SlideShare a Scribd company logo
1 of 56
1
Teaching Innovation - Entrepreneurial - Global
The Centre for Technology enabled Teaching & Learning , N Y S S, India
(Department for Technology Enhanced Learning)
DEPARTMENT OF COMPUTER TECHNOLOGY
VI-SEMESTER
2
CHAPTER NO.3
Relational Model
CHAPTER 2:- SYLLABUS
.
Structure of Relational Databases
1
The Relational Algebra
2
Tuple Relational Calculus
3
Relational Commercial Languages
4
3
SQL (DDL, DML, DCL)
5
CHAPTER-2 SPECIFIC OBJECTIVE / COURSE OUTCOME
Understand the Structure of Relational Databases.
1
Understand and Learned Relational Commercial Languages.
3
4
The student will be able to:
Fundamental Relational-Algebra-Operations.
2
Relational Model
 A particular way of structuring data (relations)
 Simple
 Mathematically based
Expressions (queries) can be analyzed by DBMS
Transformed to equivalent expressions automatically (query
optimization)
Optimizers have limits (=> programmer needs to know how
queries are evaluated and optimized)
LECTURE 1 Structure of Relational Database
5
Example of a Relation
LECTURE 1 Structure of Relational Database
6
Attribute 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
E.g. the value of an attribute can be an account
number,
but cannot be a set of account numbers
 Domain is said to be atomic if all its members are 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
LECTURE 1 Structure of Relational Database
7
Relation Schema
 Formally, given domains 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
 Schema of a relation consists of
attribute definitions
name
type/domain
integrity constraints
LECTURE 1 Structure of Relational Database
8
Relation 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
 Order of tuples is irrelevant (tuples may be stored in an
arbitrary order)
Jones
Smith
Curry
Lindsay
customer_name
Main
North
North
Park
customer_street
Harrison
Rye
Rye
Pittsfield
customer_city
customer
attributes
(or columns)
tuples
(or rows)
LECTURE 1 Structure of Relational Database
9
Database
 A database consists of multiple relations
 Information about an enterprise is broken up into parts,
with each relation storing one part of the information
E.g.
account : information about accounts
depositor : which customer owns which account
customer : information about customers
LECTURE 1 Structure of Relational Database
10
The customer Relation
LECTURE 1 Structure of Relational Database
11
The depositor Relation
LECTURE 1 Structure of Relational Database
12
Why Split Information Across Relations?
 Storing all information as a single relation such as
bank(account_number, balance, customer_name, ..)
results in
repetition of information
e.g.,if two customers own an account (What gets
repeated?)
the need for null values
e.g., to represent a customer without an account
 Normalization theory (Chapter 7) deals with how to design
relational schemas
LECTURE 1 Structure of Relational Database
13
Keys
 Let K  R
 K is a superkey of R if values for K are sufficient to identify a unique
tuple of each possible relation r(R)
by “possible r ” we mean a relation r that could exist in
the enterprise we are modeling.
Example: {customer_name, customer_street} and
{customer_name}
are both superkeys of Customer, if no two customers
can possibly have the same name
In real life, an attribute such as customer_id would be used
instead of customer_name to uniquely identify customers,
but we omit it to keep our examples small, and instead
LECTURE 1 Structure of Relational Database
14
Keys (Cont.)
 K is a candidate key if K is minimal
Example: {customer_name} is a candidate key for
Customer, since it is a superkey and no subset of it is a
superkey.
 Primary key: a candidate key chosen as the principal
means of identifying tuples within a relation
Should choose an attribute whose value never,
or very rarely, changes.
E.g. email address is unique, but may change
LECTURE 1 Structure of Relational Database
15
Foreign Keys
 A relation schema may have an attribute that corresponds to
the primary key of another relation. The attribute is called a
foreign key.
E.g. customer_name and account_number
attributes of depositor are foreign keys to
customer and account respectively.
Only values occurring in the primary key attribute
of the referenced relation may occur in the
foreign key attribute of the referencing relation.
LECTURE 1 Structure of Relational Database
16
Schema Diagram
LECTURE 1 Structure of Relational Database
17
Relational Algebra
 Basic operations:
 Selection ( ) Selects a subset of rows from relation.
 Projection ( ) Deletes unwanted columns from relation.
 Cross-product ( ) Allows us to combine two relations.
 Set-difference ( ) Tuples in reln. 1, but not in reln. 2.
 Union ( ) Tuples in reln. 1 and in reln. 2.
 Additional operations:
 Intersection, join, division, renaming: Not essential, but (very!)
useful.
 Since each operation returns a relation, operations can be
composed! (Algebra is “closed”.)





LECTURE 2 Relational Algebra
18
Projection
 Deletes attributes that are not in
projection list.
 Schema of result contains exactly the
fields in the projection list, with the
same names that they had in the (only)
input relation.
 Projection operator has to eliminate
duplicates! (Why??, what are the
consequences?)
 Note: real systems typically
don’t do duplicate elimination
unless the user explicitly asks
for it. (Why not?)
sname rating
yuppy 9
lubber 8
guppy 5
rusty 10
sname rating
S
,
( )
2
age
35.0
55.5
age S
( )
2
LECTURE 2 Relational Algebra
19
Selection
 Selects rows that satisfy
selection condition.
 Schema of result identical
to schema of (only) input
relation.
 Result relation can be the
input for another
relational algebra
operation! (Operator
composition.)
rating
S
8
2
( )
sid sname rating age
28 yuppy 9 35.0
58 rusty 10 35.0
sname rating
yuppy 9
rusty 10
 
sname rating rating
S
,
( ( ))
8
2
LECTURE 2 Relational Algebra
20
Union, Intersection, Set-Difference
 All of these operations take
two input relations, which
must be union-compatible:
 Same number of fields.
 `Corresponding’ fields
have the same type.
 What is the schema of result?
sid sname rating age
22 dustin 7 45.0
31 lubber 8 55.5
58 rusty 10 35.0
44 guppy 5 35.0
28 yuppy 9 35.0
sid sname rating age
31 lubber 8 55.5
58 rusty 10 35.0
S S
1 2

S S
1 2

sid sname rating age
22 dustin 7 45.0
S S
1 2

LECTURE 2 Relational Algebra
21
Cross-Product
Each row of S1 is paired with each row of R1.
Result schema has one field per field of S1 and
R1, with field names `inherited’ if possible.
 Conflict: Both S1 and R1 have a field called sid.
 ( ( , ), )
C sid sid S R
1 1 5 2 1 1
  
(sid) sname rating age (sid) bid day
22 dustin 7 45.0 22 101 10/10/96
22 dustin 7 45.0 58 103 11/12/96
31 lubber 8 55.5 22 101 10/10/96
31 lubber 8 55.5 58 103 11/12/96
58 rusty 10 35.0 22 101 10/10/96
58 rusty 10 35.0 58 103 11/12/96
 Renaming operator:
LECTURE 2 Relational Algebra
22
Joins
 Condition Join:
 Result schema same as that of cross-product.
 Fewer tuples than cross-product. Filters tuples not satisfying the
join condition.
 Sometimes called a theta-join.
R c S c R S

  
 ( )
(sid) sname rating age (sid) bid day
22 dustin 7 45.0 58 103 11/12/96
31 lubber 8 55.5 58 103 11/12/96
S R
S sid R sid
1 1
1 1


. .

LECTURE 2 Relational Algebra
23
Joins
 Equi-Join: A special case of condition join where the condition c
contains only equalities.
 Result schema similar to cross-product, but only one copy of
fields for which equality is specified.
 Natural Join: Equijoin on all common fields.
sid sname rating age bid day
22 dustin 7 45.0 101 10/10/96
58 rusty 10 35.0 103 11/12/96
)
1
1
(
,..
,
,..,
R
S
sid
bid
age
sid



LECTURE 2 Relational Algebra
24
Division
 Not supported as a primitive operator, but useful for expressing
queries like:
Find sailors who have reserved all boats.
 Precondition: in A/B, the attributes in B must be included in the
schema for A. Also, the result has attributes A-B.
SALES(supId, prodId);
PRODUCTS(prodId);
Relations SALES and PRODUCTS must be built using
projections.
SALES/PRODUCTS: the ids of the suppliers supplying
ALL products.
LECTURE 2 Relational Algebra
25
Examples of Division A/B
sno pno
s1 p1
s1 p2
s1 p3
s1 p4
s2 p1
s2 p2
s3 p2
s4 p2
s4 p4
pno
p2
pno
p2
p4
pno
p1
p2
p4
sno
s1
s2
s3
s4
sno
s1
s4
sno
s1
A
B1
B2
B3
A/B1 A/B2 A/B3
LECTURE 2 Relational Algebra
26
Expressing A/B Using Basic Operators
 Division is not essential op; just a useful shorthand.
 (Also true of joins, but joins are so common that
systems implement joins specially. Division is NOT
implemented in SQL).
 Idea: For SALES/PRODUCTS, compute all products such that there
exists at least one supplier not supplying it.
x value is disqualified if by attaching y value from B,
we obtain an xy tuple that is not in A.
)
)
Pr
)
(
(( Sales
oducts
Sales
sid
sid
A 

 

The answer is sid(Sales) - A
LECTURE 2 Relational Algebra
27
Find names of sailors who’ve reserved boat
#103
• Solution 1:  
sname bid
serves Sailors
(( Re ) )
103


 Solution 2:  
( , Re )
Temp serves
bid
1
103

 ( , )
Temp Temp Sailors
2 1 

 sname Temp
( )
2
 Solution 3:  
sname bid
serves Sailors
( (Re ))
103


LECTURE 2 Relational Algebra
28
Find names of sailors who’ve reserved a red
boat
Information about boat color only available
in Boats; so need an extra join:
 
sname color red
Boats serves Sailors
((
' '
) Re )


 

 A more efficient solution:
   
sname sid bid color red
Boats s Sailors
( ((
' '
) Re ) )


 

A query optimizer can find this, given the first solution!
LECTURE 2 Relational Algebra
29
Find sailors who’ve reserved a red or a green
boat
Can identify all red or green boats, then find
sailors who’ve reserved one of these boats:
 
( , (
' ' ' '
))
Tempboats
color red color green
Boats
  
 sname Tempboats serves Sailors
( Re )

 

 Can also define Tempboats using union! (How?)
 What happens if is replaced by in this query?
 
LECTURE 2 Relational Algebra
30
Find sailors who’ve reserved a red and a green
boat
Previous approach won’t work! Must identify
sailors who’ve reserved red boats, sailors
who’ve reserved green boats, then find the
intersection (note that sid is a key for Sailors):
  
( , ((
' '
) Re ))
Tempred
sid color red
Boats serves



 sname Tempred Tempgreen Sailors
(( ) )
 

  
( , ((
' '
) Re ))
Tempgreen
sid color green
Boats serves



LECTURE 2 Relational Algebra
31
Find the names of sailors who’ve reserved all
boats
Uses division; schemas of the input
relations to / must be carefully chosen:
  
( , (
,
Re ) / ( ))
Tempsids
sid bid
serves
bid
Boats
 sname Tempsids Sailors
( )


 To find sailors who’ve reserved all ‘Interlake’ boats:
/ (
' '
)
 
bid bname Interlake
Boats

.....
LECTURE 2 Relational Algebra
32
Tuple 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
LECTURE 3 Tuple Relational Calculus
33
Predicate Calculus Formula
1. Set of attributes and constants
2. Set of comparison operators: (e.g., , , , , , )
3. Set of connectives: and (), or (v)‚ not ()
4. Implication (): x  y, if x if true, then y is true
x  y x v y
5. Set of quantifiers:
 t  r (Q (t ))  ”there exists” a tuple in t in relation r
such that predicate Q (t ) is true
t r (Q (t )) Q is true “for all” tuples t in relation r
LECTURE 3 Tuple Relational Calculus
34
Banking Example
branch (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 )
LECTURE 3 Tuple Relational Calculus
35
Example 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 $120
{t |  s loan (t [loan_number ] = s [loan_number ]  s [amount ]
1200)}
Notice that a relation on schema [loan_number ] is implicitly define
by
the query
{t | t  loan  t [amount ]  1200}
LECTURE 3 Tuple Relational Calculus
36
Example 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 ])
LECTURE 3 Tuple Relational Calculus
37
Example Queries
Find the names of all customers having a loan
at the Perryridge branch
{t | s  borrower (t [customer_name ] = s [customer_name ]
 u  loan (u [branch_name ] = “Perryridge”
 u [loan_number ] = s [loan_number ]))
 not v  depositor (v [customer_name ] =
t [customer_name ])}
 Find the names of all customers who have a loan at the
Perryridge branch, but no account at any branch of the bank
{t | s  borrower (t [customer_name ] = s [customer_name ]
 u  loan (u [branch_name ] = “Perryridge”
 u [loan_number ] = s [loan_number ]))}
LECTURE 3 Tuple Relational Calculus
38
Example Queries
 Find the names of all customers having a loan from the
Perryridge branch, and the cities in which they live
{t | s  loan (s [branch_name ] = “Perryridge”
 u  borrower (u [loan_number ] = s [loan_number ]
 t [customer_name ] = u [customer_name ])
  v  customer (u [customer_name ] = v [customer_name ]
 t [customer_city ] = v [customer_city ])))}
LECTURE 3 Tuple Relational Calculus
39
Example Queries
Find the names of all customers who have an
account at all branches located in Brooklyn:
{t |  r  customer (t [customer_name ] = r [customer_name ]) 
(  u  branch (u [branch_city ] = “Brooklyn” 
 s  depositor (t [customer_name ] = s [customer_name ]
  w  account ( w[account_number ] = s [account_number ]
 ( w [branch_name ] = u [branch_name ]))))}
LECTURE 3 Tuple Relational Calculus
40
Safety of Expressions
 It is possible to write tuple calculus expressions that
generate infinite relations.
For example, { t |  t r } results in an infinite relation if
the domain of any attribute of relation r is infinite
 To guard against the problem, we restrict the set of
allowable expressions to safe expressions.
 An expression {t | P (t )} in the tuple relational calculus is
safe if every component of t appears in one of the
relations, tuples, or constants that appear in P
NOTE: this is more than just a syntax condition.
E.g. { t | t [A] = 5  true } is not safe --- it defines an
infinite set with attribute values that do not appear
in any relation or tuples or constants in P.
LECTURE 3 Tuple Relational Calculus
41
Domain 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
LECTURE 3 Domain Relational Calculus
42
Example 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}
LECTURE 3 Domain Relational Calculus
43
Example 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”))}
LECTURE 3 Domain Relational Calculus
44
Relational Query Languages
 A major strength of the relational model: supports simple,
powerful querying of data.
 Queries can be written intuitively, and the DBMS is
responsible for efficient evaluation.
 The key: precise semantics for relational queries.
 Allows the optimizer to extensively re-order
operations, and still ensure that the answer does not
change.
45
LECTURE 3 Domain Relational Calculus
Relational Query Languages
 Query languages: Allow manipulation and retrieval of
data from a database.
 Relational model supports simple, powerful QLs:
 Strong formal foundation based on logic.
 Allows for much optimization.
 Query Languages != programming languages!
 QLs not expected to be “Turing complete”.
 QLs not intended to be used for complex calculations.
 QLs support easy, efficient access to large data sets.
46
LECTURE 3 Relational Commercial
Languages
Formal Relational Query Languages
 Two mathematical Query Languages form the basis for
“real” languages (e.g. SQL), and for implementation:
 Relational Algebra: More operational, very useful for
representing execution plans.
 Relational Calculus: Lets users describe what they
want, rather than how to compute it. (Non-
operational, declarative.)
47
LECTURE 4 Relational Commercial
Languages
The SQL Query Language
 Developed by IBM’s System-R Project in the 1970s
 Need for a standard since it is used by many vendors
 Standards:
 SQL-86
 SQL-89 (minor revision)
 SQL-92 (major revision)
 SQL-99 (major extensions, current standard)
 Find Out what is SQL-MM!!
48
LECTURE 4 Relational Commercial
Languages
The SQL Query Language
 SQL consists of:
DDL (Data Definition Language)
Create conceptual schema
DML (Data Manipulation Language)
Relational operators
Insert, Delete, Update
VDL (View Definition Language)
Specify user views & their mapping to the conceptual
schema (in most DBMSs, done by DDL)
SDL (Storage Definition Language)
File organization
Indexes 49
LECTURE 4 Relational Commercial
Languages
The SQL Query Language
 SDL is being removed from SQL
 DMLs
High-level or nonprocedural (declarative)
Can be entered at the SQL > or can be embedded in a
general purpose programming language
Can specify & retrieve many records uin a single DML
statement & are hence called Set-at-a-time DMLs
Low-level or procedural
Must be embedded in a general purpose programming
language
Typically retrieves individual records or objects from
the DB & processes each separately
Therefore it need PL constructs like looping
Record-at-a-time DMLs 50
LECTURE 4 Relational Commercial
Languages
The SQL Query Language
DMLs
 Whenever DML statements are embedded in a PL, that language is
called as the host language and the DML is called the Data
Sublanguage
 In object DBs, the host language & data sublanguage form one
integrated language – for eg. C++ with some extensions to support
database functionality
 Some RDBMSs also provide integrated languages – for eg. ORACLE’s
PL/SQL.
51
LECTURE 4 Relational Commercial
Languages
Data Definition Language (DDL) statements are used to define
the database structure or schema. Some examples:
* CREATE - to create objects in the database
* ALTER - alters the structure of the database
* DROP - delete objects from the database
* TRUNCATE - remove all records from a table, including all
spaces allocated for the records are removed
* COMMENT - add comments to the data dictionary
* RENAME - rename an object
52
LECTURE 4
Data Definition Language (DDL)
Relational Commercial
Languages
53
LECTURE 4
Data Manipulation Language (DML) statements are used for
managing data within schema objects. Some examples:
* SELECT - retrieve data from the a database
* INSERT - insert data into a table
* UPDATE - updates existing data within a table
* DELETE - deletes all records from a table, the space for the
records remain
* MERGE - UPSERT operation (insert or update)
* CALL - call a PL/SQL or Java subprogram
* EXPLAIN PLAN - explain access path to data
* LOCK TABLE - control concurrency
Data Manipulation Language (DML)
Relational Commercial
Languages
© Prof. Navneet Goyal, BITS, Pilani 54
LECTURE 4
Data Control Language (DCL) statements. Some examples:
* GRANT - gives user's access privileges to database
* REVOKE - withdraw access privileges given with the GRANT
command
Data Control Language (DCL)
Relational Commercial
Languages
Summary
The relational model has rigorously defined
query languages that are simple and
powerful.
Relational algebra is more operational;
useful as internal representation for query
evaluation plans.
Several ways of expressing a given query; a
query optimizer should choose the most
efficient version.
55
LECTURE 4
56
LECTURE 4
Thank You…

More Related Content

Similar to uniT 4 (1).pptx

4_RelationalDataModelAndRelationalMapping.pdf
4_RelationalDataModelAndRelationalMapping.pdf4_RelationalDataModelAndRelationalMapping.pdf
4_RelationalDataModelAndRelationalMapping.pdfLPhct2
 
Chapter – 5 Relational Algebra.pdf
Chapter – 5 Relational Algebra.pdfChapter – 5 Relational Algebra.pdf
Chapter – 5 Relational Algebra.pdfTamiratDejene1
 
relational model in Database Management.ppt.ppt
relational model in Database Management.ppt.pptrelational model in Database Management.ppt.ppt
relational model in Database Management.ppt.pptRoshni814224
 
Database : Relational Data Model
Database : Relational Data ModelDatabase : Relational Data Model
Database : Relational Data ModelSmriti Jain
 
Sm relationaldatamodel-150423084157-conversion-gate01
Sm relationaldatamodel-150423084157-conversion-gate01Sm relationaldatamodel-150423084157-conversion-gate01
Sm relationaldatamodel-150423084157-conversion-gate01Ankit Dubey
 
Sm relationaldatamodel-150423084157-conversion-gate01
Sm relationaldatamodel-150423084157-conversion-gate01Sm relationaldatamodel-150423084157-conversion-gate01
Sm relationaldatamodel-150423084157-conversion-gate01Ankit Dubey
 
Relational Algebra and it's Operations pptx
Relational Algebra and it's Operations pptxRelational Algebra and it's Operations pptx
Relational Algebra and it's Operations pptxdanishriasat792
 
Relational model and its utility%28 rajkumar%29.pptx
Relational model and its       utility%28 rajkumar%29.pptxRelational model and its       utility%28 rajkumar%29.pptx
Relational model and its utility%28 rajkumar%29.pptxRajkumar Mondal
 

Similar to uniT 4 (1).pptx (20)

4_RelationalDataModelAndRelationalMapping.pdf
4_RelationalDataModelAndRelationalMapping.pdf4_RelationalDataModelAndRelationalMapping.pdf
4_RelationalDataModelAndRelationalMapping.pdf
 
Dbms relational model
Dbms relational modelDbms relational model
Dbms relational model
 
Chapter – 5 Relational Algebra.pdf
Chapter – 5 Relational Algebra.pdfChapter – 5 Relational Algebra.pdf
Chapter – 5 Relational Algebra.pdf
 
RDBMS
RDBMSRDBMS
RDBMS
 
Algebra
AlgebraAlgebra
Algebra
 
DBMS Unit-2.pdf
DBMS Unit-2.pdfDBMS Unit-2.pdf
DBMS Unit-2.pdf
 
Unit03 dbms
Unit03 dbmsUnit03 dbms
Unit03 dbms
 
relational model in Database Management.ppt.ppt
relational model in Database Management.ppt.pptrelational model in Database Management.ppt.ppt
relational model in Database Management.ppt.ppt
 
Relational model
Relational modelRelational model
Relational model
 
ch14.ppt
ch14.pptch14.ppt
ch14.ppt
 
2 rel-algebra
2 rel-algebra2 rel-algebra
2 rel-algebra
 
Lec02
Lec02Lec02
Lec02
 
Cs501 rel algebra
Cs501 rel algebraCs501 rel algebra
Cs501 rel algebra
 
Database : Relational Data Model
Database : Relational Data ModelDatabase : Relational Data Model
Database : Relational Data Model
 
Sm relationaldatamodel-150423084157-conversion-gate01
Sm relationaldatamodel-150423084157-conversion-gate01Sm relationaldatamodel-150423084157-conversion-gate01
Sm relationaldatamodel-150423084157-conversion-gate01
 
Sm relationaldatamodel-150423084157-conversion-gate01
Sm relationaldatamodel-150423084157-conversion-gate01Sm relationaldatamodel-150423084157-conversion-gate01
Sm relationaldatamodel-150423084157-conversion-gate01
 
Relational Algebra and it's Operations pptx
Relational Algebra and it's Operations pptxRelational Algebra and it's Operations pptx
Relational Algebra and it's Operations pptx
 
NMEC RD_UNIT 1.ppt
NMEC RD_UNIT 1.pptNMEC RD_UNIT 1.ppt
NMEC RD_UNIT 1.ppt
 
Relational model and its utility%28 rajkumar%29.pptx
Relational model and its       utility%28 rajkumar%29.pptxRelational model and its       utility%28 rajkumar%29.pptx
Relational model and its utility%28 rajkumar%29.pptx
 
Lllll
LllllLllll
Lllll
 

Recently uploaded

Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)
Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)
Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)dollysharma2066
 
Sachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
Sachpazis Costas: Geotechnical Engineering: A student's Perspective IntroductionSachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
Sachpazis Costas: Geotechnical Engineering: A student's Perspective IntroductionDr.Costas Sachpazis
 
Churning of Butter, Factors affecting .
Churning of Butter, Factors affecting  .Churning of Butter, Factors affecting  .
Churning of Butter, Factors affecting .Satyam Kumar
 
Introduction to Machine Learning Unit-3 for II MECH
Introduction to Machine Learning Unit-3 for II MECHIntroduction to Machine Learning Unit-3 for II MECH
Introduction to Machine Learning Unit-3 for II MECHC Sai Kiran
 
VICTOR MAESTRE RAMIREZ - Planetary Defender on NASA's Double Asteroid Redirec...
VICTOR MAESTRE RAMIREZ - Planetary Defender on NASA's Double Asteroid Redirec...VICTOR MAESTRE RAMIREZ - Planetary Defender on NASA's Double Asteroid Redirec...
VICTOR MAESTRE RAMIREZ - Planetary Defender on NASA's Double Asteroid Redirec...VICTOR MAESTRE RAMIREZ
 
Electronically Controlled suspensions system .pdf
Electronically Controlled suspensions system .pdfElectronically Controlled suspensions system .pdf
Electronically Controlled suspensions system .pdfme23b1001
 
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube Exchanger
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube ExchangerStudy on Air-Water & Water-Water Heat Exchange in a Finned Tube Exchanger
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube ExchangerAnamika Sarkar
 
Effects of rheological properties on mixing
Effects of rheological properties on mixingEffects of rheological properties on mixing
Effects of rheological properties on mixingviprabot1
 
Software and Systems Engineering Standards: Verification and Validation of Sy...
Software and Systems Engineering Standards: Verification and Validation of Sy...Software and Systems Engineering Standards: Verification and Validation of Sy...
Software and Systems Engineering Standards: Verification and Validation of Sy...VICTOR MAESTRE RAMIREZ
 
IVE Industry Focused Event - Defence Sector 2024
IVE Industry Focused Event - Defence Sector 2024IVE Industry Focused Event - Defence Sector 2024
IVE Industry Focused Event - Defence Sector 2024Mark Billinghurst
 
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdf
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdfCCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdf
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdfAsst.prof M.Gokilavani
 
Application of Residue Theorem to evaluate real integrations.pptx
Application of Residue Theorem to evaluate real integrations.pptxApplication of Residue Theorem to evaluate real integrations.pptx
Application of Residue Theorem to evaluate real integrations.pptx959SahilShah
 
Heart Disease Prediction using machine learning.pptx
Heart Disease Prediction using machine learning.pptxHeart Disease Prediction using machine learning.pptx
Heart Disease Prediction using machine learning.pptxPoojaBan
 
Call Girls Narol 7397865700 Independent Call Girls
Call Girls Narol 7397865700 Independent Call GirlsCall Girls Narol 7397865700 Independent Call Girls
Call Girls Narol 7397865700 Independent Call Girlsssuser7cb4ff
 
Past, Present and Future of Generative AI
Past, Present and Future of Generative AIPast, Present and Future of Generative AI
Past, Present and Future of Generative AIabhishek36461
 
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...srsj9000
 
Biology for Computer Engineers Course Handout.pptx
Biology for Computer Engineers Course Handout.pptxBiology for Computer Engineers Course Handout.pptx
Biology for Computer Engineers Course Handout.pptxDeepakSakkari2
 
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdfCCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdfAsst.prof M.Gokilavani
 

Recently uploaded (20)

Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)
Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)
Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)
 
Sachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
Sachpazis Costas: Geotechnical Engineering: A student's Perspective IntroductionSachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
Sachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
 
Churning of Butter, Factors affecting .
Churning of Butter, Factors affecting  .Churning of Butter, Factors affecting  .
Churning of Butter, Factors affecting .
 
Introduction to Machine Learning Unit-3 for II MECH
Introduction to Machine Learning Unit-3 for II MECHIntroduction to Machine Learning Unit-3 for II MECH
Introduction to Machine Learning Unit-3 for II MECH
 
VICTOR MAESTRE RAMIREZ - Planetary Defender on NASA's Double Asteroid Redirec...
VICTOR MAESTRE RAMIREZ - Planetary Defender on NASA's Double Asteroid Redirec...VICTOR MAESTRE RAMIREZ - Planetary Defender on NASA's Double Asteroid Redirec...
VICTOR MAESTRE RAMIREZ - Planetary Defender on NASA's Double Asteroid Redirec...
 
Electronically Controlled suspensions system .pdf
Electronically Controlled suspensions system .pdfElectronically Controlled suspensions system .pdf
Electronically Controlled suspensions system .pdf
 
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube Exchanger
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube ExchangerStudy on Air-Water & Water-Water Heat Exchange in a Finned Tube Exchanger
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube Exchanger
 
Design and analysis of solar grass cutter.pdf
Design and analysis of solar grass cutter.pdfDesign and analysis of solar grass cutter.pdf
Design and analysis of solar grass cutter.pdf
 
Effects of rheological properties on mixing
Effects of rheological properties on mixingEffects of rheological properties on mixing
Effects of rheological properties on mixing
 
Software and Systems Engineering Standards: Verification and Validation of Sy...
Software and Systems Engineering Standards: Verification and Validation of Sy...Software and Systems Engineering Standards: Verification and Validation of Sy...
Software and Systems Engineering Standards: Verification and Validation of Sy...
 
IVE Industry Focused Event - Defence Sector 2024
IVE Industry Focused Event - Defence Sector 2024IVE Industry Focused Event - Defence Sector 2024
IVE Industry Focused Event - Defence Sector 2024
 
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdf
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdfCCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdf
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdf
 
Application of Residue Theorem to evaluate real integrations.pptx
Application of Residue Theorem to evaluate real integrations.pptxApplication of Residue Theorem to evaluate real integrations.pptx
Application of Residue Theorem to evaluate real integrations.pptx
 
Heart Disease Prediction using machine learning.pptx
Heart Disease Prediction using machine learning.pptxHeart Disease Prediction using machine learning.pptx
Heart Disease Prediction using machine learning.pptx
 
Call Girls Narol 7397865700 Independent Call Girls
Call Girls Narol 7397865700 Independent Call GirlsCall Girls Narol 7397865700 Independent Call Girls
Call Girls Narol 7397865700 Independent Call Girls
 
Past, Present and Future of Generative AI
Past, Present and Future of Generative AIPast, Present and Future of Generative AI
Past, Present and Future of Generative AI
 
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
 
Biology for Computer Engineers Course Handout.pptx
Biology for Computer Engineers Course Handout.pptxBiology for Computer Engineers Course Handout.pptx
Biology for Computer Engineers Course Handout.pptx
 
🔝9953056974🔝!!-YOUNG call girls in Rajendra Nagar Escort rvice Shot 2000 nigh...
🔝9953056974🔝!!-YOUNG call girls in Rajendra Nagar Escort rvice Shot 2000 nigh...🔝9953056974🔝!!-YOUNG call girls in Rajendra Nagar Escort rvice Shot 2000 nigh...
🔝9953056974🔝!!-YOUNG call girls in Rajendra Nagar Escort rvice Shot 2000 nigh...
 
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdfCCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
 

uniT 4 (1).pptx

  • 1. 1 Teaching Innovation - Entrepreneurial - Global The Centre for Technology enabled Teaching & Learning , N Y S S, India (Department for Technology Enhanced Learning)
  • 2. DEPARTMENT OF COMPUTER TECHNOLOGY VI-SEMESTER 2 CHAPTER NO.3 Relational Model
  • 3. CHAPTER 2:- SYLLABUS . Structure of Relational Databases 1 The Relational Algebra 2 Tuple Relational Calculus 3 Relational Commercial Languages 4 3 SQL (DDL, DML, DCL) 5
  • 4. CHAPTER-2 SPECIFIC OBJECTIVE / COURSE OUTCOME Understand the Structure of Relational Databases. 1 Understand and Learned Relational Commercial Languages. 3 4 The student will be able to: Fundamental Relational-Algebra-Operations. 2
  • 5. Relational Model  A particular way of structuring data (relations)  Simple  Mathematically based Expressions (queries) can be analyzed by DBMS Transformed to equivalent expressions automatically (query optimization) Optimizers have limits (=> programmer needs to know how queries are evaluated and optimized) LECTURE 1 Structure of Relational Database 5
  • 6. Example of a Relation LECTURE 1 Structure of Relational Database 6
  • 7. Attribute 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 E.g. the value of an attribute can be an account number, but cannot be a set of account numbers  Domain is said to be atomic if all its members are 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 LECTURE 1 Structure of Relational Database 7
  • 8. Relation Schema  Formally, given domains 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  Schema of a relation consists of attribute definitions name type/domain integrity constraints LECTURE 1 Structure of Relational Database 8
  • 9. Relation 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  Order of tuples is irrelevant (tuples may be stored in an arbitrary order) Jones Smith Curry Lindsay customer_name Main North North Park customer_street Harrison Rye Rye Pittsfield customer_city customer attributes (or columns) tuples (or rows) LECTURE 1 Structure of Relational Database 9
  • 10. Database  A database consists of multiple relations  Information about an enterprise is broken up into parts, with each relation storing one part of the information E.g. account : information about accounts depositor : which customer owns which account customer : information about customers LECTURE 1 Structure of Relational Database 10
  • 11. The customer Relation LECTURE 1 Structure of Relational Database 11
  • 12. The depositor Relation LECTURE 1 Structure of Relational Database 12
  • 13. Why Split Information Across Relations?  Storing all information as a single relation such as bank(account_number, balance, customer_name, ..) results in repetition of information e.g.,if two customers own an account (What gets repeated?) the need for null values e.g., to represent a customer without an account  Normalization theory (Chapter 7) deals with how to design relational schemas LECTURE 1 Structure of Relational Database 13
  • 14. Keys  Let K  R  K is a superkey of R if values for K are sufficient to identify a unique tuple of each possible relation r(R) by “possible r ” we mean a relation r that could exist in the enterprise we are modeling. Example: {customer_name, customer_street} and {customer_name} are both superkeys of Customer, if no two customers can possibly have the same name In real life, an attribute such as customer_id would be used instead of customer_name to uniquely identify customers, but we omit it to keep our examples small, and instead LECTURE 1 Structure of Relational Database 14
  • 15. Keys (Cont.)  K is a candidate key if K is minimal Example: {customer_name} is a candidate key for Customer, since it is a superkey and no subset of it is a superkey.  Primary key: a candidate key chosen as the principal means of identifying tuples within a relation Should choose an attribute whose value never, or very rarely, changes. E.g. email address is unique, but may change LECTURE 1 Structure of Relational Database 15
  • 16. Foreign Keys  A relation schema may have an attribute that corresponds to the primary key of another relation. The attribute is called a foreign key. E.g. customer_name and account_number attributes of depositor are foreign keys to customer and account respectively. Only values occurring in the primary key attribute of the referenced relation may occur in the foreign key attribute of the referencing relation. LECTURE 1 Structure of Relational Database 16
  • 17. Schema Diagram LECTURE 1 Structure of Relational Database 17
  • 18. Relational Algebra  Basic operations:  Selection ( ) Selects a subset of rows from relation.  Projection ( ) Deletes unwanted columns from relation.  Cross-product ( ) Allows us to combine two relations.  Set-difference ( ) Tuples in reln. 1, but not in reln. 2.  Union ( ) Tuples in reln. 1 and in reln. 2.  Additional operations:  Intersection, join, division, renaming: Not essential, but (very!) useful.  Since each operation returns a relation, operations can be composed! (Algebra is “closed”.)      LECTURE 2 Relational Algebra 18
  • 19. Projection  Deletes attributes that are not in projection list.  Schema of result contains exactly the fields in the projection list, with the same names that they had in the (only) input relation.  Projection operator has to eliminate duplicates! (Why??, what are the consequences?)  Note: real systems typically don’t do duplicate elimination unless the user explicitly asks for it. (Why not?) sname rating yuppy 9 lubber 8 guppy 5 rusty 10 sname rating S , ( ) 2 age 35.0 55.5 age S ( ) 2 LECTURE 2 Relational Algebra 19
  • 20. Selection  Selects rows that satisfy selection condition.  Schema of result identical to schema of (only) input relation.  Result relation can be the input for another relational algebra operation! (Operator composition.) rating S 8 2 ( ) sid sname rating age 28 yuppy 9 35.0 58 rusty 10 35.0 sname rating yuppy 9 rusty 10   sname rating rating S , ( ( )) 8 2 LECTURE 2 Relational Algebra 20
  • 21. Union, Intersection, Set-Difference  All of these operations take two input relations, which must be union-compatible:  Same number of fields.  `Corresponding’ fields have the same type.  What is the schema of result? sid sname rating age 22 dustin 7 45.0 31 lubber 8 55.5 58 rusty 10 35.0 44 guppy 5 35.0 28 yuppy 9 35.0 sid sname rating age 31 lubber 8 55.5 58 rusty 10 35.0 S S 1 2  S S 1 2  sid sname rating age 22 dustin 7 45.0 S S 1 2  LECTURE 2 Relational Algebra 21
  • 22. Cross-Product Each row of S1 is paired with each row of R1. Result schema has one field per field of S1 and R1, with field names `inherited’ if possible.  Conflict: Both S1 and R1 have a field called sid.  ( ( , ), ) C sid sid S R 1 1 5 2 1 1    (sid) sname rating age (sid) bid day 22 dustin 7 45.0 22 101 10/10/96 22 dustin 7 45.0 58 103 11/12/96 31 lubber 8 55.5 22 101 10/10/96 31 lubber 8 55.5 58 103 11/12/96 58 rusty 10 35.0 22 101 10/10/96 58 rusty 10 35.0 58 103 11/12/96  Renaming operator: LECTURE 2 Relational Algebra 22
  • 23. Joins  Condition Join:  Result schema same as that of cross-product.  Fewer tuples than cross-product. Filters tuples not satisfying the join condition.  Sometimes called a theta-join. R c S c R S      ( ) (sid) sname rating age (sid) bid day 22 dustin 7 45.0 58 103 11/12/96 31 lubber 8 55.5 58 103 11/12/96 S R S sid R sid 1 1 1 1   . .  LECTURE 2 Relational Algebra 23
  • 24. Joins  Equi-Join: A special case of condition join where the condition c contains only equalities.  Result schema similar to cross-product, but only one copy of fields for which equality is specified.  Natural Join: Equijoin on all common fields. sid sname rating age bid day 22 dustin 7 45.0 101 10/10/96 58 rusty 10 35.0 103 11/12/96 ) 1 1 ( ,.. , ,.., R S sid bid age sid    LECTURE 2 Relational Algebra 24
  • 25. Division  Not supported as a primitive operator, but useful for expressing queries like: Find sailors who have reserved all boats.  Precondition: in A/B, the attributes in B must be included in the schema for A. Also, the result has attributes A-B. SALES(supId, prodId); PRODUCTS(prodId); Relations SALES and PRODUCTS must be built using projections. SALES/PRODUCTS: the ids of the suppliers supplying ALL products. LECTURE 2 Relational Algebra 25
  • 26. Examples of Division A/B sno pno s1 p1 s1 p2 s1 p3 s1 p4 s2 p1 s2 p2 s3 p2 s4 p2 s4 p4 pno p2 pno p2 p4 pno p1 p2 p4 sno s1 s2 s3 s4 sno s1 s4 sno s1 A B1 B2 B3 A/B1 A/B2 A/B3 LECTURE 2 Relational Algebra 26
  • 27. Expressing A/B Using Basic Operators  Division is not essential op; just a useful shorthand.  (Also true of joins, but joins are so common that systems implement joins specially. Division is NOT implemented in SQL).  Idea: For SALES/PRODUCTS, compute all products such that there exists at least one supplier not supplying it. x value is disqualified if by attaching y value from B, we obtain an xy tuple that is not in A. ) ) Pr ) ( (( Sales oducts Sales sid sid A      The answer is sid(Sales) - A LECTURE 2 Relational Algebra 27
  • 28. Find names of sailors who’ve reserved boat #103 • Solution 1:   sname bid serves Sailors (( Re ) ) 103    Solution 2:   ( , Re ) Temp serves bid 1 103   ( , ) Temp Temp Sailors 2 1    sname Temp ( ) 2  Solution 3:   sname bid serves Sailors ( (Re )) 103   LECTURE 2 Relational Algebra 28
  • 29. Find names of sailors who’ve reserved a red boat Information about boat color only available in Boats; so need an extra join:   sname color red Boats serves Sailors (( ' ' ) Re )       A more efficient solution:     sname sid bid color red Boats s Sailors ( (( ' ' ) Re ) )      A query optimizer can find this, given the first solution! LECTURE 2 Relational Algebra 29
  • 30. Find sailors who’ve reserved a red or a green boat Can identify all red or green boats, then find sailors who’ve reserved one of these boats:   ( , ( ' ' ' ' )) Tempboats color red color green Boats     sname Tempboats serves Sailors ( Re )      Can also define Tempboats using union! (How?)  What happens if is replaced by in this query?   LECTURE 2 Relational Algebra 30
  • 31. Find sailors who’ve reserved a red and a green boat Previous approach won’t work! Must identify sailors who’ve reserved red boats, sailors who’ve reserved green boats, then find the intersection (note that sid is a key for Sailors):    ( , (( ' ' ) Re )) Tempred sid color red Boats serves     sname Tempred Tempgreen Sailors (( ) )       ( , (( ' ' ) Re )) Tempgreen sid color green Boats serves    LECTURE 2 Relational Algebra 31
  • 32. Find the names of sailors who’ve reserved all boats Uses division; schemas of the input relations to / must be carefully chosen:    ( , ( , Re ) / ( )) Tempsids sid bid serves bid Boats  sname Tempsids Sailors ( )    To find sailors who’ve reserved all ‘Interlake’ boats: / ( ' ' )   bid bname Interlake Boats  ..... LECTURE 2 Relational Algebra 32
  • 33. Tuple 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 LECTURE 3 Tuple Relational Calculus 33
  • 34. Predicate Calculus Formula 1. Set of attributes and constants 2. Set of comparison operators: (e.g., , , , , , ) 3. Set of connectives: and (), or (v)‚ not () 4. Implication (): x  y, if x if true, then y is true x  y x v y 5. Set of quantifiers:  t  r (Q (t ))  ”there exists” a tuple in t in relation r such that predicate Q (t ) is true t r (Q (t )) Q is true “for all” tuples t in relation r LECTURE 3 Tuple Relational Calculus 34
  • 35. Banking Example branch (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 ) LECTURE 3 Tuple Relational Calculus 35
  • 36. Example 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 $120 {t |  s loan (t [loan_number ] = s [loan_number ]  s [amount ] 1200)} Notice that a relation on schema [loan_number ] is implicitly define by the query {t | t  loan  t [amount ]  1200} LECTURE 3 Tuple Relational Calculus 36
  • 37. Example 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 ]) LECTURE 3 Tuple Relational Calculus 37
  • 38. Example Queries Find the names of all customers having a loan at the Perryridge branch {t | s  borrower (t [customer_name ] = s [customer_name ]  u  loan (u [branch_name ] = “Perryridge”  u [loan_number ] = s [loan_number ]))  not v  depositor (v [customer_name ] = t [customer_name ])}  Find the names of all customers who have a loan at the Perryridge branch, but no account at any branch of the bank {t | s  borrower (t [customer_name ] = s [customer_name ]  u  loan (u [branch_name ] = “Perryridge”  u [loan_number ] = s [loan_number ]))} LECTURE 3 Tuple Relational Calculus 38
  • 39. Example Queries  Find the names of all customers having a loan from the Perryridge branch, and the cities in which they live {t | s  loan (s [branch_name ] = “Perryridge”  u  borrower (u [loan_number ] = s [loan_number ]  t [customer_name ] = u [customer_name ])   v  customer (u [customer_name ] = v [customer_name ]  t [customer_city ] = v [customer_city ])))} LECTURE 3 Tuple Relational Calculus 39
  • 40. Example Queries Find the names of all customers who have an account at all branches located in Brooklyn: {t |  r  customer (t [customer_name ] = r [customer_name ])  (  u  branch (u [branch_city ] = “Brooklyn”   s  depositor (t [customer_name ] = s [customer_name ]   w  account ( w[account_number ] = s [account_number ]  ( w [branch_name ] = u [branch_name ]))))} LECTURE 3 Tuple Relational Calculus 40
  • 41. Safety of Expressions  It is possible to write tuple calculus expressions that generate infinite relations. For example, { t |  t r } results in an infinite relation if the domain of any attribute of relation r is infinite  To guard against the problem, we restrict the set of allowable expressions to safe expressions.  An expression {t | P (t )} in the tuple relational calculus is safe if every component of t appears in one of the relations, tuples, or constants that appear in P NOTE: this is more than just a syntax condition. E.g. { t | t [A] = 5  true } is not safe --- it defines an infinite set with attribute values that do not appear in any relation or tuples or constants in P. LECTURE 3 Tuple Relational Calculus 41
  • 42. Domain 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 LECTURE 3 Domain Relational Calculus 42
  • 43. Example 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} LECTURE 3 Domain Relational Calculus 43
  • 44. Example 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”))} LECTURE 3 Domain Relational Calculus 44
  • 45. Relational Query Languages  A major strength of the relational model: supports simple, powerful querying of data.  Queries can be written intuitively, and the DBMS is responsible for efficient evaluation.  The key: precise semantics for relational queries.  Allows the optimizer to extensively re-order operations, and still ensure that the answer does not change. 45 LECTURE 3 Domain Relational Calculus
  • 46. Relational Query Languages  Query languages: Allow manipulation and retrieval of data from a database.  Relational model supports simple, powerful QLs:  Strong formal foundation based on logic.  Allows for much optimization.  Query Languages != programming languages!  QLs not expected to be “Turing complete”.  QLs not intended to be used for complex calculations.  QLs support easy, efficient access to large data sets. 46 LECTURE 3 Relational Commercial Languages
  • 47. Formal Relational Query Languages  Two mathematical Query Languages form the basis for “real” languages (e.g. SQL), and for implementation:  Relational Algebra: More operational, very useful for representing execution plans.  Relational Calculus: Lets users describe what they want, rather than how to compute it. (Non- operational, declarative.) 47 LECTURE 4 Relational Commercial Languages
  • 48. The SQL Query Language  Developed by IBM’s System-R Project in the 1970s  Need for a standard since it is used by many vendors  Standards:  SQL-86  SQL-89 (minor revision)  SQL-92 (major revision)  SQL-99 (major extensions, current standard)  Find Out what is SQL-MM!! 48 LECTURE 4 Relational Commercial Languages
  • 49. The SQL Query Language  SQL consists of: DDL (Data Definition Language) Create conceptual schema DML (Data Manipulation Language) Relational operators Insert, Delete, Update VDL (View Definition Language) Specify user views & their mapping to the conceptual schema (in most DBMSs, done by DDL) SDL (Storage Definition Language) File organization Indexes 49 LECTURE 4 Relational Commercial Languages
  • 50. The SQL Query Language  SDL is being removed from SQL  DMLs High-level or nonprocedural (declarative) Can be entered at the SQL > or can be embedded in a general purpose programming language Can specify & retrieve many records uin a single DML statement & are hence called Set-at-a-time DMLs Low-level or procedural Must be embedded in a general purpose programming language Typically retrieves individual records or objects from the DB & processes each separately Therefore it need PL constructs like looping Record-at-a-time DMLs 50 LECTURE 4 Relational Commercial Languages
  • 51. The SQL Query Language DMLs  Whenever DML statements are embedded in a PL, that language is called as the host language and the DML is called the Data Sublanguage  In object DBs, the host language & data sublanguage form one integrated language – for eg. C++ with some extensions to support database functionality  Some RDBMSs also provide integrated languages – for eg. ORACLE’s PL/SQL. 51 LECTURE 4 Relational Commercial Languages
  • 52. Data Definition Language (DDL) statements are used to define the database structure or schema. Some examples: * CREATE - to create objects in the database * ALTER - alters the structure of the database * DROP - delete objects from the database * TRUNCATE - remove all records from a table, including all spaces allocated for the records are removed * COMMENT - add comments to the data dictionary * RENAME - rename an object 52 LECTURE 4 Data Definition Language (DDL) Relational Commercial Languages
  • 53. 53 LECTURE 4 Data Manipulation Language (DML) statements are used for managing data within schema objects. Some examples: * SELECT - retrieve data from the a database * INSERT - insert data into a table * UPDATE - updates existing data within a table * DELETE - deletes all records from a table, the space for the records remain * MERGE - UPSERT operation (insert or update) * CALL - call a PL/SQL or Java subprogram * EXPLAIN PLAN - explain access path to data * LOCK TABLE - control concurrency Data Manipulation Language (DML) Relational Commercial Languages
  • 54. © Prof. Navneet Goyal, BITS, Pilani 54 LECTURE 4 Data Control Language (DCL) statements. Some examples: * GRANT - gives user's access privileges to database * REVOKE - withdraw access privileges given with the GRANT command Data Control Language (DCL) Relational Commercial Languages
  • 55. Summary The relational model has rigorously defined query languages that are simple and powerful. Relational algebra is more operational; useful as internal representation for query evaluation plans. Several ways of expressing a given query; a query optimizer should choose the most efficient version. 55 LECTURE 4

Editor's Notes

  1. 6
  2. 7
  3. 8
  4. 9
  5. 10
  6. 11
  7. 12
  8. 13
  9. 14
  10. 15
  11. 16
  12. 17
  13. 18
  14. 19
  15. 20