0% found this document useful (0 votes)
119 views53 pages

Relation:-A Relation /table Is Set of Records in The Form of Two

The document describes fundamental concepts of the relational database model including relations, relation schemas, relation instances, domains, and SQL commands for querying, modifying, and managing relations. It defines key concepts like tables, rows, columns, primary keys, foreign keys, and integrity constraints. It provides SQL examples for creating tables, inserting and deleting tuples, and enforcing referential integrity between relations.

Uploaded by

X Boy
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
119 views53 pages

Relation:-A Relation /table Is Set of Records in The Form of Two

The document describes fundamental concepts of the relational database model including relations, relation schemas, relation instances, domains, and SQL commands for querying, modifying, and managing relations. It defines key concepts like tables, rows, columns, primary keys, foreign keys, and integrity constraints. It provides SQL examples for creating tables, inserting and deleting tuples, and enforcing referential integrity between relations.

Uploaded by

X Boy
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 53

Fundamental concepts of relational model

Relation :- a relation /table is set of records in the form of two


dimensional table containing rows and columns.
A relation consists of two things
A relation schema
A relation instance
Relation schema-it contains the information of a table which
includes the name of the table , the names of the columns and
data types.
E.G. Students (sid: string, name: string, login: string, age:
integer, gpa: real).

Relation instance- it is a table with rows and columns.

Relational database schema-it is a collection of relation schemas


describing one or more relations

Domain-is the set of permitted values of an attribute


The SQL Query Language

sid name login age gpa


SELECT * 53666 Jones jones@cs 18 3.4
FROM Students S 53688 Smith smith@ee 18 3.2
WHERE S.age=18

•To find just names and logins, replace the first line:

SELECT S.name, S.login


Querying Multiple Relations

• What does the following SELECT S.name, E.cid


query compute? FROM Students S, Enrolled E
WHERE S.sid=E.sid AND E.grade=“A”

Given the following instances sid cid grade


of Enrolled and Students: 53831 Carnatic101 C
sid name login age gpa 53831 Reggae203 B
53650 Topology112 A
53666 Jones jones@cs 18 3.4 53666 History105 B
53688 Smith smith@eecs 18 3.2
53650 Smith smith@math 19 3.8
S.name E.cid
we get: Smith Topology112
Creating Relations in SQL

• Creates the Students CREATE TABLE Students


relation. Observe that the (sid CHAR(20),
type of each field is name CHAR(20),
specified, and enforced by login CHAR(10),
the DBMS whenever age number
tuples are added or gpa number(6,2))
modified.
• As another example, the CREATE TABLE Enrolled
Enrolled table holds (sid CHAR(20),
information about courses cid CHAR(20),
that students take. grade CHAR(2))
Destroying and Altering Relations
DROP TABLE Students
• Destroys the relation Students. The schema
information and the tuples are deleted.

ALTER TABLE Students


ADD COLUMN ( grade char(1))

 The schema of Students is altered by adding a


new field; every tuple in the current instance is
extended with a null value in the new field.
Adding and Deleting Tuples

• Can insert a single tuple using:

INSERT INTO Students (sid, name, login, age, gpa)


VALUES (53688, ‘Smith’, ‘smith@ee’, 18, 3.2)

 Can delete all tuples satisfying some condition (e.g.,


name = Smith):

DELETE
FROM Students S
WHERE S.name = ‘Smith’
Integrity Constraints (ICs) over relations
• An integrity constraint is a condition that is specified on a data
base schema and resticts the data that can be stored in an
instance of the database.ICs help to prevent incorrect information
into the database.
• IC: condition that must be true for any instance of the database;
– ICs are specified when schema is defined.
– ICs are checked when relations are modified.

• A legal instance of a relation is one that satisfies all specified ICs.

• If the DBMS checks ICs, stored data is more faithful to real-world


Integrity constraints are of the following types
 Entity integrity constraints/key constraints
 Referential integrity constraints/foreign key constraints
 Domain constraints
key Constraints

• It specifies the condition and restricts the data


that can be stored only in one relation
• Example consider a student table
• If we want that no two students should have
the same student id ,this is an example of a
key constraint
• Key constraint is a statement that certain
subset of fields of a relation has a unique
identifier for all tupes
• Candidate key-it is an attribute/set of
attributes that uniquely identify a row in a
relation
Specifying Key constraints in SQL

 “Students can take only one CREATE TABLE Enrolled


course, and receive a single grade (sid CHAR(20)
for that course; cid CHAR(20),
 further, no two students in a grade CHAR(2),
course receive the same grade.” PRIMARY KEY (sid,cid) )
 !
CREATE TABLE Enrolled
(sid CHAR(20)
cid CHAR(20),
grade CHAR(2),
PRIMARY KEY (sid),
UNIQUE (cid, grade) )
Foreign Keys, Referential Integrity
• Foreign key : Set of fields in one relation that is
used to `refer’ to a tuple in another relation.
(Must correspond to primary key of the second
relation.) Like a `logical pointer’.
• E.g. sid is a foreign key referring to Students:
– Enrolled(sid: string, cid: string, grade: string)
– If all foreign key constraints are enforced,
referential integrity is achieved, i.e., no
dangling references.
Foreign Keys in SQL

• Only students listed in the Students relation should be allowed to enroll


for courses.

CREATE TABLE Enrolled


(sid CHAR(20), cid CHAR(20), grade CHAR(2),
PRIMARY KEY (sid,cid),
FOREIGN KEY (sid) REFERENCES Students )

Enrolled
sid cid grade Students
sid name login age gpa
53666 Carnatic101 C
53666 Reggae203 B 53666 Jones jones@cs 18 3.4
53650 Topology112 A 53688 Smith smith@eecs 18 3.2
53666 History105 B 53650 Smith smith@math 19 3.8
General constraints-primary and foreign key constraints
are fundamental part of the relational model.but some times we need
to specify more general constraints

Example- we may require that student ages be with in a certain range.


Current database systems support general constraints in two
forms

Constraint table-is associated with a single table and checked when


ever that table is modified.

Assertions- it involves several tables and are checked whenever any


of these tables is modified.
Enforcing integrity constraints

Integrity constraints are the rules when applied on


relations restricts the insertion of incorrect data and also
helps to prevent deletion and updation of consistent data
that may lead to loss of data integrity.
The operations such as insertion, deletion, updation must be
discarded if they are found to violate integrity constraints.
Consider the employee relation where eid is a primary key
Insert into emplyee values(‘hanseen’, 1234,…………)
Violates the primary key constraint if 1234 already exists in the
relation

And also consider


Insert into employee values(‘jack’, null,……..) violates primary
key constraint as primary key can contain null values.
Insert into emp(ename, eid,…….)
Values(1234,12345260,…………………..);
It violates domain constraint as domain for
ename is character but the inserted value is
integer.

Update employee E
Set E.eid=12345263
Where E.eid=12345267;
It violates the rules and rejected if employee
with 12345263 already exists.
Enforcing Referential Integrity

• Consider Students and Enrolled; sid in Enrolled


is a foreign key that references Students.
• What should be done if an Enrolled tuple with a
non-existent student id is inserted? (Reject it!)
• What should be done if a Students tuple is
deleted?
– Also delete all Enrolled tuples that refer to it.
– Disallow deletion of a Students tuple that is
referred to.
– Set sid in Enrolled tuples that refer to it to a
default sid.
Referential Integrity in SQL
– Default is NO ACTION
(delete/update is rejected)
– CASCADE (also delete all
tuples that refer to deleted CREATE TABLE Enrolled
tuple) (sid CHAR(20),
– SET NULL / SET DEFAULT cid CHAR(20),
(sets foreign key value of
referencing tuple) grade CHAR(2),
PRIMARY KEY (sid,cid),
FOREIGN KEY (sid)
REFERENCES Students
ON DELETE CASCADE
ON UPDATE SET
DEFAULT )
Querying relational data
Query is a question. A query Is formulated for a relation to retrieve
some useful information from the table. Different query languages are
used to frame queries.
Example SQL
List the employees who are working for department number 7
Select * from employee where dno=7;
Select * can be read as select all fields from employee table
The general format is
Select field1, field2,………fieldn From table1, table2 ….
Where (condition);

list the name,id,department name, phone no of the employees


who are also the namagers of the respective departments
Select ename, eid,dname,phone,dno from
Employee E , department D Where
E.dno=D.dno and E.eid=D.manager-id.
This query combines 2 relations based on some conditions and
displays the result.Not all fields but the fields which are mentioned
after select keyword. The Resultant relation is as follows

Ename eid dname dno phone


john 1234526 admin 7 7712345
1 689
bill 1234526 research 8 9987653
5 424
donald 1234526 sales 9 9987676
7 543
Logical DB Design: ER to Relational

• Entity sets to tables:

CREATE TABLE Employees


name (ssn CHAR(11),
ssn lot name CHAR(20),
lot number(3),
Employees PRIMARY KEY (ssn))
Relationship sets to tables(ok)

since
name dname
ssn lot did budget

Employees Works_In Departments


Relationship Sets to Tables

• In translating a relationship
set to a relation, attributes
CREATE TABLE Works_In(
of the relation must include:
ssn CHAR(11),
– Keys for each
did number(2),
participating entity set
since DATE,
(as foreign keys).
PRIMARY KEY (ssn, did),
• This set of attributes
FOREIGN KEY (ssn)
forms a superkey for
REFERENCES Employees,
the relation.
FOREIGN KEY (did)
– All descriptive attributes.
REFERENCES Departments)
Review of Key Constraints

• Each dept has at most


one manager, according
to the key constraint since
on Manages. name dname
ssn lot did budget

Employees Manages Departments

Translation to
relational model?

1-to-1 1-to Many Many-to-1 Many-to-Many


Translating ER Diagrams with Key
Constraints
CREATE TABLE Manages(
ssn CHAR(11),
did number(2),
since DATE,
PRIMARY KEY (did),
FOREIGN KEY (ssn) REFERENCES Employees,
FOREIGN KEY (did) REFERENCES Departments)

The manages table has the attributes ssn,did,since.because


each dept has at most one manager ,no two tuples can have
the same did value. As did is a key
Review: Participation Constraints

• Does every department have a manager?


– If so, this is a participation constraint: the participation of Departments
in Manages is said to be total (vs. partial).
• Every did value in Departments table must appear in a row
of the Manages table (with a non-null ssn value!)

since
name dname
ssn lot did budget

Employees Manages Departments

Works_In

since
Participation Constraints in SQL

• We can capture participation constraint that every dept must have a


manager .because ssn can not take on null values .each tuple of dept_mgr
identifies a tuple in employees(who is the manager)

CREATE TABLE Dept_Mgr(


did number(2),
dname CHAR(20),
budget number(10,2),
ssn CHAR(11) not null,NOT NULL,
since DATE,
PRIMARY KEY (did),
FOREIGN KEY (ssn) REFERENCES Employees,
)
Translating weak Entity sets(√ok)

• A weak entity can be identified uniquely only by considering the primary


key of another (owner) entity.
– Owner entity set and weak entity set must participate in a one-to-many
relationship set (1 owner, many weak entities).
– Weak entity set must have total participation in this identifying
relationship set.

name
cost pname age
ssn lot

Employees Policy Dependents


Translating Weak Entity Sets

• Weak entity set and identifying relationship set are translated


into a single table.
– When the owner entity is deleted, all owned weak entities
must also be deleted.

CREATE TABLE Dep_Policy (


pname CHAR(20),
age number(2),
cost number(8,2),
ssn CHAR(11) NOT NULL,
PRIMARY KEY (pname, ssn),
FOREIGN KEY (ssn) REFERENCES Employees,
ON DELETE CASCADE)
Review: ISA Hierarchies√

name
 As in C++, or other ssn lot
PLs, attributes are
inherited. Employees

 If we declare A ISA B,
hourly_wages hours_worked
every A entity is also ISA
contractid
considered to be a B
entity. Contract_Emps
Hourly_Emps

• Overlap constraints: Can Joe be an Hourly_Emps as well as a


Contract_Emps entity? (Allowed/disallowed)
• Covering constraints: Does every Employees entity also have to be an
Hourly_Emps or a Contract_Emps entity? (Yes/no)
Translating ISA Hierarchies to Relations

• General approach:
– 3 relations: Employees, Hourly_Emps and Contract_Emps.
• Hourly_Emps: Every employee is recorded in
Employees. For hourly emps, extra info recorded in
Hourly_Emps (hourly_wages, hours_worked, ssn); must
delete Hourly_Emps tuple if referenced Employees tuple
is deleted).
• Queries involving all employees easy, those involving
just Hourly_Emps require a join to get some attributes.
• Alternative: Just Hourly_Emps and Contract_Emps.
– Hourly_Emps: ssn, name, lot, hourly_wages, hours_worked.
– Each employee must be in one of these two subclasses.
Review: Binary vs. Ternary Relationships
name
ssn lot pname age
• What are the
additional Employees Covers
constraints in the
Dependents
2nd diagram? Bad design Policies

policyid cost

name pname age


ssn lot
Dependents
Employees

Purchaser
Beneficiary

Better design Policies

policyid cost
Binary vs. Ternary Relationships
CREATE TABLE Policies (
• The key
constraints allow policyid number(10),
us to combine cost number(9,2),
Purchaser with ssn CHAR(11) NOT NULL,
Policies and PRIMARY KEY (policyid).
Beneficiary with FOREIGN KEY (ssn) REFERENCES Employees,
Dependents. ON DELETE CASCADE)
• Deletion of an CREATE TABLE Dependents (
employee leads to pname CHAR(20),
deletion of all
age number(2),
policies owned by
employee policyid number(10),
PRIMARY KEY (pname, policyid).
• And all
dependents who FOREIGN KEY (policyid) REFERENCES Policies,
are beneficiaries ON DELETE CASCADE)
• Of those policies
Views

• Views are like windows to the original relation.


Using views we peep into the original relation
and we can see only some portion of the original
relation using views. These are virtual tables
and they do not exist physically. They derive the
data from the original relation. The
modifications made to the view are reflected
back to the original relation and vice versa.
• The syntax for creating a view is
• Create view (view name) ( field1,field2,….field n)
as select ( attribute1, attribute 2,….. Attribute
n) from table1,table2, ….table n where
<condition>
Views
• Example
Create view project_info
( name,id,dno,pnumber,pname) as select
E.ename,E.eid,E.dno,P.pno,P.pname, from
employee E , project P where E.eid=P.eid and
P.location=‘newjersy’);

Now we can use the command


Select * from project_info where dno=7;
Advantages of views
1. Views provide data security
2. They do not occupy any space
3. Views can be used to hide complex queries
involving join operations
Destroying and altering tables and views
Drop table table-name RESTRICT/CASCADE
If restrict option is used, the drop command fails if some view or
IC is referring to the table
If CASCADE is specified, the views and ICs are deleted along with
the table

Ex: drop table department restrict


Drop view view-name

Altering table syntax


ALTER TABLE table-name
ADD [column] column-name data type
DROP column-name
ADD [constraint] constraint name
DROP [constraint] constraint-name
MODIFY column-name data-type
ALTER column-name set default default value;
Example

Alter table students add column maiden-name char(10);


Relational Algebra and calculus

Query languages are of two types


Procedural languages
Non-procedural
In procedural languages, the user has to describe
the procedure(the way) to retrieve the information
from the database
Example:Relational algebra
In non procedural languages, the user specifies
only what he wants not the procedure

Example:Tuple relational calculus,domain relational


calculus
Relational algebra
 It is a procedural language
 It consists of set of operations that take one or two relations
as input and produce a new relation
 Some relational algebra operations
A. Select
B. Project
C. Union,intersection
D. Rename
E. Difference
F. Join
G. Divide
H. Cartesian product
the select ,project and rename operators are called unary
operators as they operate only on a single relation.
• 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
Example Instances
sid bid day R1
22 101 10/10/96
• “
58 103 11/12/96 sid sname rating age
S1 22 dustin 7 45.0
31 lubber 8 55.5
58 rusty 10 35.0

sid sname rating age


S2
28 yuppy 9 35.0
31 lubber 8 55.5
44 guppy 5 35.0
58 rusty 10 35.0
Projection
sname rating
yuppy 9
• Deletes attributes that are not
in projection list.
lubber 8
• Schema of result contains
guppy 5
exactly the fields in the rusty 10
projection list, with the same
names that they had in the
 sname,rating(S2)
(only) input relation.
• Projection operator has to
eliminate duplicates! (Why??) age
– Note: real systems typically 35.0
don’t do duplicate elimination
unless the user explicitly asks 55.5
for it. (Why not?)
 age(S2)
Selection
sid sname rating age
• Selects rows that satisfy 28 yuppy 9 35.0
selection condition. 58 rusty 10 35.0
 rating 8(S2)

sname rating
yuppy 9
rusty 10

 sname,rating( rating 8(S2))


Union, Intersection, Set-Difference
• All of these operations take two sid sname rating age
input relations, which must be
union-compatible: 22 dustin 7 45.0
– Same number of fields.
31 lubber 8 55.5
– `Corresponding’ fields have
the same type.
58 rusty 10 35.0
44 guppy 5 35.0
28 yuppy 9 35.0

S1 S2
sid sname rating age sid sname rating age
22 dustin 7 45.0 31 lubber 8 55.5
58 rusty 10 35.0
S1 S2
S1 S2
Cross-Product(or cartesian product)
• R X S returns a relation instance whose schema
contains all fields of R followed by all fields of S and
each tuple of R is paired with each tuple of S.

(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 S1XR1
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(ok)

 (C(1 sid1, 5  sid 2), S1 R1)

The above expression gives a relation that


contains tuples of S1 x R1 but the field1
is renamed as sid1 and field 5 is renames
as sid2 and the name of the relation is C.
The join operation
It combines two relations like cartesian product but finally removes
duplicate attributes (same columns to only one column).and makes
the operations selection,projection etc very simple.it is denoted by
the symbol

There are three types of joins

1.Natural join(⋈ )
2.Outer join
i) left outer join
ii) right outer join
iii) full outer join
3.Theta join(conditional join).

Natural join: it allows us to combine two different relations into one


relation and makes the same column in two different relations into
only one column in the resulting relation
Employee table

Emp name street city


coyote town hollywood
rabbit tunnel Carrot ville
smith revolver vallley
williams seaview seattle

Employee_works
Emp name Branch salary
coyote Mesa 1500
Rabbit Mesa 1300
Gates Redmond 5300
Williams Redmomd 1500
The natural join of these two relations employee ⋈
employee-works is

Employee street city branch salary


name

coyote town hollywood mesa 1500


rabbit tunnel carrotville mesa 1300
williams seavie seattle redmond 1500
w

Notice that we lost the street and city info about smith, since
smith tuple is not there in emp-works.and also lost the branch
name and salary info about gates since gates tuple is absent in the
employe relation
To over come the drawbacks of natural join, we use outer join
operation

Left outer join-it takes all tuples in left relation that did not match
with any tuples in the right relation ,adds the tuples with null values for
all other columns from right relation and adds them to the result.
the following is added to the result of natural join

Smith, revolver,valley null,null


Right outer join
it takes all tuples in right relation that did not match with any tuples in
the left relation ,adds the tuples with null values for all other columns
from left relation and adds them to the result.
the following is added to the result of natural join

Gates, null,null, redmond,5300


Full outer join:it is combination of left and right outer join

Employee street city branch salary


name

coyote town hollywood mesa 1500


rabbit tunnel carrotville mesa 1300
williams seavie seattle redmond 1500
w
Smith Revolv Valley Null Null
er
Gates Null Null Redmond 5300
Conditional join

R  c S   c ( R  S)
• Condition Join:
(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
S1  R1
S1. sid  R1. sid

• Result schema same as that of cross-product


followed by selection
• Fewer tuples than cross-product, might be able
to compute more efficiently
• Sometimes called a theta-join.
Joins(ok)

• Equi-Join: A special case of condition join where the


condition c contains only equalities.
sid sname rating age bid day
22 dustin 7 45.0 101 10/10/96
58 rusty 10 35.0 103 11/12/96

S1  R1
sid
• Result schema similar to cross-product, but only one
copy of fields for which equality is specified.
Division√

• Let A have 2 fields, x and y; B have only field y:


– A/B =
contains set of all x values such that for every y
value in B, there is tuple (x,y ) in A.
Examples of Division A/B

sno pno pno pno pno


s1 p1 p2 p2 p1
s1 p2 p4 p2
s1 p3 p4
B1
s1 p4 B2
s2 p1 sno B3
s2 p2 s1 sno
s3 p2 sno
s2 s1 s1
s4 p2 s3 s4
s4 p4 s4

A A/B1 A/B2 A/B3

You might also like