0% found this document useful (0 votes)
25 views72 pages

Chapter 3 The Relational Model

The document discusses the relational data model proposed by Codd in 1970. It introduces some key concepts of the relational model including relations, attributes, tuples, keys, and Structured Query Language (SQL). An example shows a relation with students and their details. Keys such as candidate keys, primary keys and foreign keys are explained. SQL commands for data definition, manipulation and integrity constraints are provided.

Uploaded by

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

Chapter 3 The Relational Model

The document discusses the relational data model proposed by Codd in 1970. It introduces some key concepts of the relational model including relations, attributes, tuples, keys, and Structured Query Language (SQL). An example shows a relation with students and their details. Keys such as candidate keys, primary keys and foreign keys are explained. SQL commands for data definition, manipulation and integrity constraints are provided.

Uploaded by

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

Chapter 3, The Relational

Model
Introduction to Relational Model

• Codd proposed the relational data model


in 1970. Student ID Name Major

• Prior to that, database systems were 1161234 Ahmad ENCS

based on older data models (the and the 1161455 Noor COMP

network model); hierarchical model he


relational model revolutionized the
database field and largely supplanted Course ID CODE Name
these earlier models 56478 COMP333 Database
management
• Main idea was to organize data as groups Systems
of relations 56479 COMP232 Data Structures

• Each relation describes a group of objects


with similar attributes
Relational data model example

3
Keys
• A super key of an entity set is a set of one or more attributes whose
values uniquely determine each entity.
• A candidate key of an entity set is a minimal super key
• ID is candidate key of instructor
• course_id is candidate key of course
• Although several candidate keys may exist, one of the candidate keys is
selected to be the primary key.

Database System Concepts 4


Simplicity

• The relational model is very simple and elegant; a database is a


collection of one or more relations, where each relation is a table
with rows and columns.

• A DBMS permits the use of SQL to query, and manipulate data and
relations in a database.
SQL

• DBMS Supports Structured


Query Language.
• Based on Relational
Algebra

• Composed of
• DDL
• DML

6
Main Constructs

• The main construct in relational model is Relation


• A Relation consist of:
• Schema
• Instance
• There should be no redundant data (rows) inside a database
• Degree: number of fields (attributes)
• Cardinality: number of records (tuples)
Example:
Example Instance of Students Relation

❖ Cardinality = 3, degree = 5, all rows distinct


❖ Do all columns in a relation instance have
to
be distinct?
Example SQL
Example SQL..2
mySQL

• We will be using mySql server


• Download from
• https://dev.mysql.com/downloads/mysql/

• Must install a client to connect to server


• Best: mySql WorkBench
MySQL Basics – Data Definition

• SHOW DATABASES;

• CREATE DATABASE university;

• SHOW DATABASES;

• USE university;

• DROP DATABASE university;


MySQL Basics

• CREATE TABLE student (


sid INT,
sname VARCHAR(32),
bdate DATE,
gpa REAL,
PRIMARY KEY (sid));
• SHOW TABLES;
• SHOW CREATE TABLE student;
• ALTER TABLE STUDENT ADD major VARCHAR(16);
• ALTER TABLE STUDENT ADD phone VARCHAR(16) AFTER bdate;
• DROP TABLE student;
MySQL Basics – Data Manipulation

• Query:
SELECT *
FROM student;
• INSERT INTO STUDENT VALUES (1051122, 'Ahmad', '1980-01-20', 99);
• SELECT * FROM student;
• INSERT INTO STUDENT (sid, sname) VALUES (1061122, 'Sireen’);
• DELETE FROM student WHERE sid>=1060000 AND sid<=1069999;
• Query:
SELECT sid, sname
FROM student
WHERE sname = ‘Ahmad’;
MySQL Basics – Auto increment

• ALTER TABLE student MODIFY sid int auto_increment;


• SELECT * FROM student;
• INSERT INTO student (sname) VALUES ('Iyad');
• ALTER TABLE student auto_increment=1070000;
• INSERT INTO student (sname) VALUES ('Gabi');
• ALTER TABLE student MODIFY gpa REAL DEFAULT 60;
• SELECT * FROM student;
• ALTER TABLE student MODIFY bdate DATE DEFAULT '1900-01-01';
• INSERT INTO student (sname) VALUES ('Gabi');
MySQL Basics – Data Control

• CREATE USER 'user1'@'localhost' IDENTIFIED BY ‘password';


• GRANT ALL PRIVILEGES ON university.* TO 'user1'@'localhost' WITH
GRANT OPTION;
• CREATE USER 'user1'@'%' IDENTIFIED BY ‘password';
• GRANT ALL PRIVILEGES ON university.* TO 'user1'@'%' WITH GRANT
OPTION;

• CREATE USER 'user2'@'localhost' IDENTIFIED BY ‘password2';


• GRANT SELECT ON university.* TO 'user2'@'localhost' WITH GRANT
OPTION;
• CREATE USER 'user2'@'%' IDENTIFIED BY ‘password2';
• GRANT SELECT ON university.* TO 'user2'@'%' WITH GRANT OPTION;
Integrity Constraints Over Relations

• A database is only as good as the information stored in it, and a


DBMS must therefore help prevent the entry of incorrect
information.

• An integrity constraint (IC) is a condition that is specified on a


database schema, and restricts the data that can be stored in an
instance of the database.
• We already have seen the Domain Constraints
Key Constraints

• A key constraint is a statement that a certain minimal subset of the


fields of a relation is a unique identifier for a tuple.
• Two Important Note:
• Two distinct tuples in a legal instance cannot have identical values in all the
fields of a key.
• No subset of the set of fields in a key is a unique identifier for a tuple.
• Primary Key, Candidate Key, and Super key
Keys (continued)

• Composite key
• Composed of more than one attribute
• Key attribute
• Any attribute that is part of a key
• Superkey
• Any key that uniquely identifies each row
• Candidate key
• A superkey without redundancies

42
Keys (continued)
• Nulls:
• No data entry
• Not permitted in primary key
• Should be avoided in other attributes
• Can represent
• An unknown attribute value
• A known, but missing, attribute value
• A “not applicable” condition
• Can create problems when functions such as COUNT,
AVERAGE, and SUM are used
• Can create logical problems when relational tables
are linked

43
SQL for Data Definition: CREATE with
CONSTRAINT

• Creating database tables with PRIMARY KEY constraints


• The SQL CREATE TABLE statement
• The SQL CONSTRAINT keyword

CREATE TABLE Employee(


EmpID Integer Not Null,
EmpName Char(25) Not Null,
PRIMARY KEY (EmpID)
);

44
SQL for Data Definition: CREATE with
CONSTRAINT

• Creating database tables with composite primary keys


using PRIMARY KEY constraints
• The SQL CREATE TABLE statement
• The SQL CONSTRAINT keyword

CREATE TABLE Emp_Skill (


EmpID Integer Not Null,
SkillID Integer Not Null,
SkillLevel Integer,
PRIMARY KEY (EmpID, SkillID)
);

45
Keys for Relationship Sets
• The combination of primary keys of the participating entity sets forms a
super key of a relationship set.
• (s_id, i_id) is the super key of advisor
• NOTE: this means a pair of entity sets can have at most one relationship in a particular
relationship set.
• Example: if we wish to track multiple meeting dates between a student and her advisor, we cannot assume a
relationship for each meeting. We can use a multivalued attribute though

• Must consider the mapping cardinality of the relationship set when


deciding what are the candidate keys
• Need to consider semantics of relationship set in selecting the primary key
in case of more than one candidate key

Database System Concepts 46


Foreign Key Constraints
Specifying Foreign Keys

Foreign Key (sid) References Students(sid)


Foreign Key (cid) References Course(cid));
Foreign Key Example

Department Employee

DeptID Primary Key EmpID

DeptName DeptID
Foreign Key
Location EmpName

49
Referential Integrity

• Referential integrity states that every value of a foreign key must


match a value of an existing primary key
• For example (see previous slide)
• If EmpID = 4 in EMPLOYEE has a DeptID = 7 (a foreign key), a Department
with DeptID = 7 must exist in DEPARTMENT

50
SQL for Data Definition: CREATE with
CONSTRAINT
• Creating database tables using PRIMARY KEY and FOREIGN KEY
constraints
• The SQL CREATE TABLE statement
• The SQL CONSTRAINT keyword

CREATE TABLE Emp_Skill (


EmpID Integer Not Null,
SkillID Integer Not Null,
SkillLevel Integer,
PRIMARY KEY (EmpID, SkillID),
FOREIGN KEY (EmpID) REFERENCES Employee (EmpID),
FOREIGN KEY (SkillID) REFERENCES Skill (SkillID)
);

51
SQL for Data Definition: CREATE with CONSTRAINT
• Creating database tables using PRIMARY KEY and FOREIGN KEY
constraints
• The SQL CREATE TABLE statement
• The SQL CONSTRAINT keyword
• ON UPDATE CASCADE and ON DELETE CASCADE
CREATE TABLE Emp_Skill (
EmpID Integer Not Null,
SkillID Integer Not Null,
SkillLevel Integer,
PRIMARY KEY (EmpID, SkillID),
FOREIGN KEY (EmpID)
REFERENCES Employee (EmpID)
ON DELETE CASCADE,
FOREIGN KEY (SkillID)
REFERENCES Skill (SkillID)
ON UPDATE CASCADE
);

When the row of EmpID (primary key) in Employee TABLE is deleted, the
EmpFK (foreign key) is deleted also.
52
Deleting Database Objects: DROP

• To remove unwanted database objects from the


database, use the SQL DROP statement
• Warning… The DROP statement will permanently
remove the object and all data
DROP TABLE Employee;

53
Enforcing Integrity Constraints

• Deletion of Enrolled tuples do not violate referential integrity, but


insertions could.
• Inserting a tuple with an un-exist sid in Students.

• Insertion of Students tuples do not violate referential integrity, but


deletions could.

INSERT INTO Enrolled (sid, cid, grade) VALUES (51111, ‘Hindi101’, ‘B’);
Ways to handle foreign key violations

• If an Enrolled row with un-existing sid is inserted, it is


rejected.
• If a Students row is deleted/updated,
• Option 1: Delete/Update all Enrolled rows that refer to the deleted
sid in Students (CASCADE). Both are affected
• Option 2: Reject the deletion/updating of the Students row if an
Enrolled row refers to it (NO ACTION ). [The default action for SQL].
None is affected.

• Option 3: Set the sid of Enrolled to some existing (default) sid value
in Students for every involved Enrolled row (SET NULL / SET
DEFAULT ). Both are affected.
Referential Integrity in SQL

• When a Students row is deleted, all CREATE TABLE Enrolled


Enrolled rows that refer to it are to (sid CHAR(20),
be deleted as well. cid CHAR(20),
• When a Students sid is modified, grade CHAR(2),
the update is to be rejected if an PRIMARY KEY (sid,cid),
Enrolled row refers to the modified FOREIGN KEY (sid)
Students row. REFERENCES Students (sid)
ON DELETE No Action
ON UPDATE Cascade);
SQL Constraints
• NOT NULL constraint
• Ensures that column does not accept nulls
• UNIQUE constraint
• Ensures that all values in column are unique
• DEFAULT constraint
• Assigns value to attribute when a new row is added to table
• CUS_AREACODE CHAR(3) DEFAULT ‘615’ NOT NULL
CHECK (CUS_AREACODE IN (‘615’, ‘713’, 931’))

CREATE TABLE STUDENT (


sid int primary key,
name varchar(32) not null default ‘Ahmad’

57
Relationship Types to Relational Model

• Possible cardinality ratio: 1:1, 1: N, N:1, and N:M


• Easiest is N:M
• Every Entity is a relation
• Every Relationship is a relation

1 1
Owner ow Car
ns

N 1
Owner ow Car
ns

N M
Owner ow Car
ns
58
ER to Relational Model - Entities
• Entity sets to tables:
• Attributes to columns
nam
ss e lo
n t

Employee
• CREATE TABLE Employees
s
(ssn int,
name CHAR(20),
lot INTEGER,
PRIMARY KEY (ssn))
ER to Relational Model - Relationships
CREATE TABLE EMP ….
• Relationship Sets to Tables CREATE TABLE DEPT …
• Attributes to columns
• In translating a relationship set to a CREATE TABLE works_in (
since date,
relation, attributes of the relation ssn_emp int,
must include: did_dept int
• Keys for each participating entity set (as primary key (ssn_emp, did_dept),
foreign keys). Foreign key (ssn_emp) references emp(ssn),
• This set of attributes forms a Foreign key (did_dept) references dept(Did))
key for the relation.

Since Ssn did


1/1/2019 1 2
1/1/2018 1 1
1/5/2020 2 3
ER to Relational Model - Relationships
• EMP (SSN: int primary key, name: varchar(32), etc…)
• PROJ (Number: int primary key, Name: varchar(32), etc..)
• CREATE TABLE EMP2PROJ (SSN int, Proj_num int not null, Hours int,
PRIMARY KEY (SSN, Proj_num),
Foreign Key (SSN) References EMP(SSN),
Foreign Key (Proj_num) References PROJ(Number));
One-to-Many

• Start with Each Entity as a relation


• EMP(eid: int, name: varchar(32), etc..)
• DEPT(did: int, dname: varchar(32), etc..)
• Relationship needs special care on the 1-1 side
• Especially if total participation
• Relationship must be merged with Emp
• Result:
• EMP_works(eid: int,
name: varchar(32)
rank int,
salary real,
did: int not null,
primary key(eid),
foreign key (did) references DEPT(did))

Replaces employee table


Replaces works_for table
One-to-One

• Start with Each Entity as a relation


• EMP(eid: int, name: varchar(32), etc..)
• DEPT(did: int, dname: varchar(32), etc..)
• Relationship needs special care on the 1-1 side
• Especially if total participation
• Relationship must be merged with DEPT
• Result:
• DEPT( did int,
name varchar(32),
stdate date,
mgr_ssn: int not null,
primary key(did),
foreign key (mgr_ssn)
references EMP(eid));

Dept_locations
( did int,
Location int,
Primary key( did, location),
Foreign key (did) references dept(did));
Musicians Example
Create Table Address ( Phone int primary key, City
varchar(16), Street varchar(32));
CREATE TABLE Musicians (Ssn int primary key,
Name char(32), Phone int,
Foreign key(phone) references Address(phone));

Create table instruments(Inst_id int primary key,


Name varchar(32), Musical_key varchar(32));

Create table Mus2Inst( ssn int, inst_id int,


Primary key(ssn, inst_id),
Foreign key (ssn) references musicians(ssn),
Foreign key (inst_id) references instruments(inst_id));

Create table albums (alb_id int primary key, Prod_ssn int,


A_date date, format varchar(32), Title varchar(32),
Foreign key (prod_ssn) references musicians(ssn));

Create table Songs (song_id int primary key, title varchar(32), author varchar(32),
Alb_id int, foreign key (alb_id) references albums(alb_id));
Create table Mus2Songs(ssn int, song_id int, primary key (ssn, song_id),
Foreign key (ssn) References Musicians(ssn),
Foreign key (song_id) references Songs(song_id));
University Example
Create Table Prof(ssn int primary key, age int,
rank int);
CREATE TABLE run_Dept (did int primary key,
office varchar(32),
dname varchar(32), mgr_ssn int,
Foreign key(mgr_ssn) references Prof(ssn));

Create table Prof2DeptW( did int, ssn int, percent int,


Primary key(did, ssn),
Foreign key (ssn) references Prof(ssn),
Foreign key (did) references run_Dept(did));

Create table Proj(pnum int primary key, sponser varchar(32), sdate date,
Edate date, budget real, mgr_ssn int,
Foreign key (mgr_ssn) references Prof(ssn));

Create table Prof2ProjW(pnum int, ssn int, Primary key(pnum, ssn),


Foreign key (ssn) references Prof(ssn),
Foreign key (pnum) references Proj(pnum));
Create table gStudent(ssn int primary key, name varchar(32), age int,
degree varchar(32), senior_ssn int, major_did int,
Foreign key (major_did) references run_Dept(did));
Create table Student2ProjW(pnum int, ssn int, Primary key(pnum, ssn), supervisor varchar(32),
Foreign key (ssn) references gStudent(ssn), Foreign key (pnum) references Proj(pnum));
Relational Model for Weak Entity Sets

• Start with Each Entity as a relation


• EMP(eid: int, name: varchar(32), etc..)
• Dependents(Name: varchar(32), relationship: varchar(32), etc..)
• Weak Relationships needs special care
• Relationship must be merged with Dependents
Dependents(Name: Varchar(32),
Relationship: Varchar(32),
emp_id: int not null,
Primary key (emp_id*, Name),
Foreign Key (emp_id)
References EMP(eid)
on delete cascade)
Relational Model for Class Hierarchies name
ssn lot

Just Hourly_Emps and Contract_Emps.


Hourly_Emps: ssn, name, lot, Employee
s
hourly_wages, hours_worked.
Each employee must be in one of hourly_wage hours_worke
these two subclasses. s d IS
A contracti
d

Contract_Emp
• General approach: Hourly_Emp
s
s
• 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.
Relational Model for Recursive Relationships

• EMP (employeeNo int primary key,


employeeName varchar(32),
ManagerSSN int))
employee
employee NAME
NO
1 EMPLOYEE 1

manage

Empno Emp name Mgr_ssn

1 Ahmad -1

2 Dania 1

You might also like