0% found this document useful (0 votes)
5 views65 pages

DBMS Week4

The document outlines the fundamentals of the Relational Model, including its history, key terminologies, and basic building blocks such as entities, attributes, and relationships. It explains various types of keys used in relational databases, integrity constraints, and the importance of business rules in defining data structure. Additionally, it provides examples and class activities to reinforce understanding of these concepts.

Uploaded by

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

DBMS Week4

The document outlines the fundamentals of the Relational Model, including its history, key terminologies, and basic building blocks such as entities, attributes, and relationships. It explains various types of keys used in relational databases, integrity constraints, and the importance of business rules in defining data structure. Additionally, it provides examples and class activities to reinforce understanding of these concepts.

Uploaded by

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

Database Systems (CC-230)

Lecture # 7-8

Instructor
Rida Ayesha
Lecture # 7-8 Agenda:
• The Relational Model:
o Brief History of the Relational Model

o Terminologies
▪ Relational Data Structure/Database Relations
▪ Mathematical Relations
▪ Properties of Relations
▪ Basic Building Blocks of Relational Model (Class Activity 02)
▪ Business Rules (Sources, Importance, Translating)

o Types of Keys (Super Key, Candidate Keys, Primary Key, Alternate Keys, Foreign Key, Composite
Key, Compound Key, Surrogate Key/Artificial Key, Sort/Control Key,
Secondary Key) (Class Activity 03)

o Integrity Constraints
▪ Entity Integrity
▪ Referential Integrity
▪ Domain Integrity
▪ Key Constraints (PK, FK, Not Null, Check, Unique and Default)

o Representing Relational Database Schemas 2


Introduction to the Relational Model
• Introduced by E.F. Codd in 1970

• Based on mathematical set theory and first-order predicate logic

• Provides a structured way to store and retrieve data efficiently

• Foundation of modern RDBMS (Relational Database Management Systems)

3
Terminologies in the
Relational Model

4
Relational Data Structure/Database Relations

• A Table is called a Relation.


• A Row in a relation is also called Tuple.
• Number of tuples in a relation is called Cardinality of the relation.
• Number of columns/attributes in a relation is called Degree or arity of the relation.
• Each attribute has a Domain (set of valid values and format).

5
Relational Data Structure/Database Relations
(cont.)
Linking the Relational Tables:
• The relational tables are linked through a common attribute.

6
Relational Data Structure/Database Relations
(cont.)
Linking the Relational Tables (cont.):

Emp Relation WorksOn Relation


eno ename eno pno resp
E1 J. Doe 01-05-75 EE 30000 E2 null E1 P1 Manager 12
E2 M. Smith 06-04-66 SA 50000 E5 D3 E2 P1 Analyst 24
E3 A. Lee 07-05-66 ME 40000 E7 D2 E2 P2 Analyst 6
E4 J. Miller 09-01-50 PR 20000 E6 D3 E3 P3 Consultant 10
E5 B. Casey 12-25-71 SA 50000 E8 D3 E3 P4 Engineer 48
E6 L. Chu 11-30-65 EE 30000 E7 D2 E4 P2 Programmer 18
E7 R. Davis 09-08-77 ME 40000 E8 D1 E5 P2 Manager 24
E8 J. Jones 10-11-72 SA 50000 null D1 E6 P4 Manager 48
E7 P3 Engineer 36

Proj Relation Dept Relation


pno pnam e dno dname mgreno
P1 I n s t r u me n t s 150000 D1
D1 Management E8
P2 D B Develop 135000 D2
D2 Consulting E7
P3 Budget 250000 D3
D3 Accounting E5
P4 Maintenance 310000 D2
D4 Development null
P5 CAD/CAM 500000 D2 7
Relation Practice Questions

• What is the name of the relation?


• What is the cardinality of the relation?
• What is the degree of the relation?

8
Mathematical Relations
Given two sets (domains):
• Set A (Student ID) = {101, 102, 103}
• Set B (Student Name) = {Alice, Bob, Charlie}

The Cartesian product 𝐴×𝐵 would be:


{(101,Alice),(101,Bob),(101,Charlie),(102,Alice),(102,Bob),(102,Charlie),(103,Alic
e),(103,Bob),(103,Charlie)}

This contains all possible combinations of Student ID and Student Name.


A relation (R) is a meaningful subset of this Cartesian product. For Example:
R={(101,Alice),(102,Bob),(103,Charlie)}

This subset represents an actual student database table where each tuple (row)
represents a valid record.

9
Mathematical Relations (Connection to Database
Relations)
• In a database, a relation corresponds to a table.

• The Cartesian product represents all possible data combinations, but only a valid
subset forms the actual database table.

• Each row (tuple) in a relational table is part of this mathematical relation.

• The table's columns (attributes) correspond to different domains in the relation.

10
Properties of Relations
• Uniqueness: No duplicate rows (tuples)

• Atomicity: Each attribute contains an atomic (indivisible) value

• Order Irrelevance: Tuples have no predefined order

• Column Uniqueness: Each column name in a relation is unique

11
Relational Model: Basic Building Blocks
1. Entity: Unique and distinct object used to collect and store data

2. Attribute: Characteristic of an entity

3. Relationship: Describes an association among entities


i. One-to-one (1:1)
ii. One-to-many (1:M)
iii. Many-to-many (M:N or M:M)

4. Constraint: Set of rules to ensure data integrity

12
Relational Model: Basic Building Blocks (cont.)
1. Entity
• An Entity is an Object, Event, Persons, Place or Concept about which the
organization wishes to maintain data.

• An Entity Type or Entity Class is a collection of entities that can be described


under the same set of characteristics.

• For Example: Doctor and Patient Entity Class, Student and Faculty Entity Class
etc.

• An Entity is diagrammatically represented as

STUDENT

13
Relational Model: Basic Building Blocks (cont.)
2. Attribute

• An attribute is a characteristic of an entity.


• For example, a CUSTOMER entity would be described by attributes such
▪ customer last name,
▪ customer first name,
▪ customer phone,
▪ customer address,
▪ customer credit limit.

3. Relationship:
• Describes an association among entities
▪ One-to-one (1:1)
▪ One-to-many (1:M)
▪ Many-to-many (M:N or M:M)

14
Relational Model: Basic Building Blocks (cont.)

Types of Relationship – 1:1 Relationship:

A 1:1 relationship, also known as a one-to-one relationship, is a type of cardinality (or


relationship type) where one record in one table is associated with exactly one record in
another table, and vice versa.

For Example: Each citizen has exactly one passport, and each passport is assigned to only
one citizen.

15
Relational Model: Basic Building Blocks (cont.)

Types of Relationship – 1:M Relationship:

A 1:M relationship, also known as a one-to-many relationship, is a type of cardinality (or


relationship type) where one record in a table can be associated with zero, one, or
multiple records in another table, while each record in the second table is associated
with at most one record in the first table.

For Example: Consider a scenario with "Customers" and "Orders." One customer can
place many orders, but each order belongs to only one customer.

16
Relational Model: Basic Building Blocks (cont.)

Types of Relationship – M:1 Relationship:

A M:1 relationship, also known as a many-to-one relationship, is a type of cardinality (or


relationship type) where one record in the "one" table is associated with zero, one, or
multiple records in the "many" table.

For Example: Multiple customers (many) can be associated with one order (one).

17
Relational Model: Basic Building Blocks (cont.)

Types of Relationship – M:N or M:M Relationship:

A M:N or M:M relationship, also known as a many-to-many relationship, is a type of


cardinality (or relationship type) where multiple records in one table can be related to
multiple records in another table.

For Example: A student can be enrolled in multiple courses, and a course can have many
students enrolled. This is a many-to-many relationship between the "Student" and
"Course" entities.

Note: Relational databases don't directly


support M:N relationships. Instead, you
need to use a third table, called a join table,
junction table or an associative table, to
represent the relationship.

18
Relational Model: Basic Building Blocks (cont.)
4. Constraint:

• The fourth and final basic building block is a constraint, which is a restriction
placed on the data.

• Constraints are important because they help to ensure data integrity.

• Constraints are normally expressed in the form of rules. For example:


– An employee’ s salary must have values between 45,000 and 200,000.
– A student’ s GPA must be between 0.00 and 4.00.
– Each class must have one and only one teacher.
– Each Student must have a unique ID.

• Constraints arise from business rules which are derived from a detailed
description of how an organization operates.

19
Business Rules
• Brief, precise, and unambiguous description of a policy, procedure, or principle
within a specific organization’s environment.

• Properly written business rules are used to define entities, attributes,


relationships, and constraints.

• For Example,
o A customer generate many invoices
o An agent can serve many customers, and each customer can be served by
only one agent.

20
Sources of Business Rules

Company Department
Policy makers
managers managers

Direct
Written
interviews
documentation
with end users

21
Importance of Business Rules
• Help standardize company’s view of data

• Communication tool between users and designers

• Allow designer to:


o Understand the nature, role, scope of data, and business processes
o Develop appropriate relationship participation rules and constraints
o Create an accurate data model

22
Translating Business Rules Into Relational Model
Components
• Nouns translate into entities

• Verbs translate into relationships among entities

• Relationships are bidirectional

• Questions to identify the relationship type

o How many instances of B are related to one instance of A?


o How many instances of A are related to one instance of B?

23
Business Rules: Naming Conventions

Entity names - Required to:


• Be descriptive of the objects in the business environment
• Use terminology that is familiar to the users

Attribute name - Required to:


• Be descriptive of the data represented by the attribute
• It is also a good practice to prefix the name of an attribute with the name of
the entity (or an abbreviation of the entity name) in which it occurs.

Proper naming:
• Facilitates communication between parties
• Promotes self-documentation

24
Class Activity 02

CASE STUDY: Identify all possible Entities,


Attributes, Relationship types from the following
case study

A university maintains a database to manage student course registrations. The system


includes students, courses, instructors, and departments. Each student can register
for multiple courses, and each course can have multiple students. Each course is
taught by one instructor, and each instructor belongs to one department.

25
Class Activity 02 - Solution

CASE STUDY: Identify all possible Entities,


Attributes, Relationship types from the following
case study

Entities: Relationship Types:


• Student
• Course • Student ↔ Course = Many-to-Many (M:N)
• Instructor (Students enroll in many courses; courses have many students)
• Department
• Course → Instructor = One-to-One (1:1)
(Each course has one instructor; assume one instructor teaches
Attributes: one course)
• Student: StudentID, Name, Email
• Course: CourseID, Title, Credits • Instructor → Department = Many-to-One (M:1) or
• Instructor: InstructorID, Name, Phone One-to-Many (1:M)
• Department: DeptID, DeptName (Many instructors work in one department)

26
Types of Keys in the
Relational Model

27
Keys in Relational Model

What is a Key?
• A key is an attribute or set of attributes that uniquely identifies any record/tuple
from the table/relation.
Purpose:
• Key is used to uniquely identify any record or row of data from the table.
• It is also used to establish and identify relationships between tables.
Example:
Student table

28
Relational Keys - Types

• Super Key
• Candidate Keys
• Primary Key (PK)
• Alternate Keys
• Foreign Key (FK)
• Composite Key
• Compound Key
• Surrogate Key/Artificial Key
• Sort/Control Key
• Secondary Key

29
Relational Keys – Super Key
• A Super Key is a combination of all possible attributes that can uniquely identify
the rows/tuple in the given table/relation.
o Super key is a superset of a candidate key.
o A table/relation can have many super keys.
o A super key may contain extra attributes that are not necessary for achieving
uniqueness.
Student table

Super Keys: 4. {Stud_Id, Stud_CNIC} 8. {Stud_Id, Dept_Id}


1. {Stud_Id} 5. {Stud_Id, Stud_Name} 9. {Stud_Id, Stud_Email, Stud_CNIC}
2. {Stud_Email} 6. {Stud_CNIC, Stud_Email} 10. {Stud_Id, Stud_Name, Stud_CNIC,
3. {Stud_CNIC} 7. {Stud_Id, Stud_Email} Stud_Email, Dept_Id}, etc…… 30
Relational Keys – Candidate Key
• A Candidate Key is an attribute or set of an attribute which can uniquely identify a
record/tuple.
• A candidate key is a minimal super key; or a Super key with no redundant
attributes
o It is called a minimal super key because we select a candidate key from a set of super key
such that the selected candidate key is the minimum attribute required to uniquely
identify the tuple.

• Every candidate key is a super key, but not every super key is a candidate key.
• A primary key is chosen from the set of candidate keys.
Properties of Candidate key:
o It must contain unique values
o Candidate key in SQL may have multiple attributes
o Must not contain null values

31
Relational Keys – Candidate Key (cont.)

Candidate Keys

Student table

Candidate Keys:
1. {Stud_Id}
2. {Stud_Email}
3. {Stud_CNIC}

32
Relational Keys – Primary Key
• A Primary Key is one of the candidate key chosen by the database designer to
uniquely identify the record/tuple in the table/relation.
• Rules for defining Primary key:
o Primary key values are not allowed to accept NULL value
o The value of primary key must always be unique (not duplicate)
o The value of primary key must be assigned when inserting a record.
o The value in a primary key column can never be modified or updated if any foreign key
refers to that primary key.
o A relation is allowed to have only one primary key.
Student table

Primary
Key:
1. {Stud_Id}

33
Relational Keys – Alternate Keys
Alternate Key are the keys left behind after the selection of the primary key among
the possible candidate keys of an entity.
For Example: If Stud_id, Stud_CNIC and Stud_Email of a student are candidate keys and
Stud_Id is chosen as the Primary Key then Stud_CNIC and Stud_Email will be called Alternate
Keys.
Alternate Keys
Primary Key
Student table

Alternate Keys:
1. {Stud_CNIC}
2. {Stud_Email}
34
Relational Keys – Foreign Keys (FK)
• A Foreign Key is:
o A key used to link two tables together.
o An attribute (or set of attributes) in one table that refers to the Primary Key in another
table.
• The purpose of the foreign key is
o To ensure (or maintain) referential integrity of the data.
• Referenced relation may also be called as the master/primary/parent table.
• Referencing relation may also be called as the foreign/child table.
• Foreign key can take only those values which are present in the primary key of the
referenced table/relation.
• Foreign key may have a name other than that of primary key.
• Foreign key can take the NULL value.
• There is no restriction on a foreign key to be unique. In fact, foreign key is not
unique most of the time.
35
Relational Keys - Foreign Key (FK) (cont.)

• Consider the following two relations:


o R1: EMP(EmpNo, EName,…,DeptNo)
o R2: DEPT(DeptNo, DName)

• The values of DeptNo in the EMP relation should either be one of the values stored
in DEPT relation or it may optionally be NULL.

Table Name: EMP (Referencing Relation) Table Name: DEPT (Referenced Relation)

EMPNO ENAME JOB DEPTNO DEPTNO DNAME LOC


7839 KING PRESIDENT 10 10 ACCOUNTING NEW YORK
7698 BLAKE MANAGER 30 20 RESEARCH DALLAS
7782 CLARK MANAGER 10 30 SALES CHICAGO
7566 JONES MANAGER 20 40 OPERATIONS BOSTON

Primary key Foreign key Primary key

Foreign Key:
1. {DEPTNO} 36
Relational Keys – Composite Key
• A composite key is a candidate key that consists of two or more attributes that together
uniquely identify a record/tuple in the table/relation.
• Sometimes a single attribute is not sufficient to uniquely identify a record/tuple. In such
situations, two or more attributes are combined together to form a key and such a key is
called Composite Key.
• A Composite Key must satisfy the conditions of uniqueness & Minimality i.e. Elimination of
any part of key will destroy uniqueness.
• Combination ensures uniqueness, if we analyse separately, there comes repeated values.
Order table

Composite Key:
1. {Cust_Id, Product_Code}
37
Relational Keys – Compound Key

• A compound key is a composite key for which each attribute that makes up the key is a
foreign key in its own right.
• A compound key is created when two or more primary keys from different tables are present
as foreign keys within an entity. The foreign keys are used together to uniquely identify each
record.
• Example: In an a hotel reservation system, a Reservation table has the compound key, (Guest_Id,
Hotel_Id, Arrival_Date). Guest_Id identifies a Guest, and references the Guests table. Hotel_Id identifies
a Hotel, and references the Hotels table.

Reservation table

Foreign keys

Compound Key:
1. {Guest_Id, Hotel_Id, Arrival_Date}
38
Relational Keys – Compound Key (cont.)

Statement Is it true?
A compound key must have at least 2 attributes ✅ Yes
All parts of a compound key must be foreign keys ❌ No

A compound key can include foreign keys and non-foreign keys ✅ Yes

A compound key is always a candidate key too ✅ Yes

39
Composite Key vs Compound Key

Feature Composite Key Compound Key


A key formed by combining two or A composite key where the combined
Definition more columns to uniquely identify a columns are foreign keys referencing
record. other tables.
Contains Foreign
Not necessarily Yes, always
Keys?
No single attribute can uniquely The uniqueness comes from combining
Used When
identify a record foreign keys

40
Relational Keys – Surrogate /Artificial Key

• Sometimes row-ids or sequential numbers are assigned to uniquely identify each


record/tuple of the table/relation. Such key is called Artificial Key or Surrogate Key.
• Example: In the Reservation table below, Guest_Id identifies a Guest, and references the
Guests table. Hotel_Id identifies a Hotel, and references the Hotels table. Since, there is no
attribute that can be used to uniquely identify a tuple, we need to introduce a column
‘Reservation_Id’ as artificial/surrogate key to uniquely identify each tuple of the relation.

Surrogate/Artificial Reservation table


Key

Foreign Keys 41
Relational Keys – Sort / Control Key

• An attribute or set of attributes that is used to physically sequence the stored data
is called Sort Key. It is also known as control key. The stored data can be sorted in
different ways according to the user requirement.
• Example: In the Student table below, the Stud_Marks attribute can be used as a
Sort key as it sorts all the tuples on the basis of Marks.

Student table

Sort / Control Key

42
Relational Keys – Secondary Key

• A Secondary Key is an additional key, which can be use in addition to the primary
key to locate specific data.
• Non-unique attribute or set of attribute use to fetch the group of tuples from
relation.
• Use to retrieve the common unique data from the table.
• Example: In the Student table below, the Stud_Dept attribute can be used as a Secondary
Key as it groups the tuples on the basis of Department.

Student table Secondary Key

43
Relational Keys: Class Activity 03
Scenario:
You are given the following table from a university’s enrollment database.

EnrollmentID StudentID StudentName CourseCode DeptCode Semester EnrollDate Email

1001 S101 Ali Khan CS101 CS Fall'23 2023-10-10 [email protected]

1002 S102 Sara Raza CS101 CS Fall'23 2023-10-10 [email protected]

1003 S103 Imran Shah SE201 SE Fall'23 2023-10-10 [email protected]

1004 S101 Ali Khan SE201 CS Spring'24 2024-02-15 [email protected]

1005 S104 Zainab Ali CS101 SE Spring’24 2024-01-02 [email protected]

Questions:
• List all possible Super Keys for this table.
• Identify Candidate Keys.
• Choose the most appropriate Primary Key (PK).
• Which attribute(s) can be considered Alternate Key(s)?
• Which column(s) can act as Foreign Key(s) if this table references Student, Course & Department tables?
• Can you spot a Composite Key in this table?
• Is there any Compound Key? If yes, identify it.
• What column could serve as a Surrogate/Artificial Key? Why?
• Which attribute would you use as a Sort/Control Key for generating reports?
• Suggest a possible Secondary Key and justify your choice.

44
Relational Keys: Class Activity 03 (Solution)

Super keys include, but are not limited to:


{EnrollmentID}, {EnrollmentID, StudentID}, {EnrollmentID, CourseCode},
Super Key
{EnrollmentID, CourseCode, Semester}, {StudentID, CourseCode, Semester} …
etc."
Candidate Keys {EnrollmentID}, {StudentID, CourseCode, Semester}
Primary Key EnrollmentID
Alternate Key {StudentID, CourseCode, Semester}
StudentID → Students table
Foreign Key CourseCode → Courses table
DeptCode → Departments table
Composite Key {StudentID, CourseCode, Semester}
{StudentID, CourseCode, Semester} – all can be foreign keys from different
Compound Key
tables
Surrogate Key EnrollmentID (system-generated unique identifier)
Sort/Control Key EnrollDate or Semester
Secondary Key DeptCode – useful for grouping students from the same department

45
Integrity Constraints in
the Relational Model

46
Integrity Constraints or Integrity Rules

• To maintain the accuracy & integrity of data in the database, there are the
following classes and Types of Integrity Constraints:

a) Static or Schema Constraints


1. Domain Constraint
2. Entity Integrity
3. Referential Integrity
4. Key Constraints

b) Dynamic Constraints
5. Action Assertion / Business Rules

47
Integrity Constraints or Integrity Rules (cont.)

1. Domain Constraint:

• Domain is a set of values that may be assigned to an attribute

• Defines valid values for attributes

• Ensured using Data Types and Constraints

Attribute Domain Description


Emp_No Set of all possible Employee Numbers (PK)
Emp_Name Set of all possible Employee Names
(NOT NULL)

Job CLERK, MANAGER, SALESMAN etc.


Sal Sal is between 6000 and 40000
Rank Rank can be between 1 and 5

48
Integrity Constraints or Integrity Rules (cont.)

1. Domain Constraint (cont.)

49
Integrity Constraints or Integrity Rules (cont.)
2. Entity Integrity:

• Each table must have a Primary Key

• Primary Key values cannot be NULL

• Ensures unique identification of tuples

• Note: Some other attributes of a relation may also be constrained to disallow


null values, even though they are not members of the primary key.

• Formally, t[PK]  null for any tuple t in r(R)

50
Integrity Constraints or Integrity Rules (cont.)
3. Referential Integrity:
• It is a constraint involving two relations called referencing relation and
referenced or target relation.

• It specifies a relationship among tuples in two relations.

• A tuple t1 in R1 (referencing relation) is said to reference a tuple t2 in R2


(referenced relation) if t1[FK] = t2[PK].

• The database must not contain any unmatched FK values.

• The value in the foreign key column (or columns) FK of the referencing relation
R1 can be either:
o A value of an existing primary key value of a corresponding primary
key PK in the referenced relation R2, or
o a null.

• In case (2), the FK in R1 should not be a part of PK of its containing relation.


51
Integrity Constraints or Integrity Rules (cont.)
3. Referential Integrity (cont.):
• Ensures consistency between related tables

• Foreign Key in one table must refer to a valid Primary Key in another
table

52
Integrity Constraints or Integrity Rules (cont.)
3. Referential Integrity (cont.):

Q: What should happen if an attempt is made to delete a record from a target table,
while some matching records exist in the referencing table?

There are three possible options:

a) Not Allowed. This is the default option.


b) Cascade: All the matching records in the referencing table will also be deleted.
c) Nullify: Null will be placed in the FK. This option is only applicable if the FK is not a
part of PK.

53
Integrity Constraints or Integrity Rules (cont.)
4. Key Constraints:

• Key constraints in DBMS are a restriction on values.

Types of Key Constraints:

• Within databases, a key constraint is a rule that defines how data in a column(s) can
be stored in a table.

• There are several different types of key


constraints in DBMS, each with its own
specific purpose.

• We’ll take a high-level look at the five


most common types of key constraints:
primary key constraints, unique key
constraints, foreign key constraints, NOT
NULL constraints, check constraints and
default constraint.
54
Integrity Constraints or Integrity Rules (cont.)
Types of Key Constraints (cont.):

i. Primary Key Constraints


• A primary key constraint (also known as a "primary key") is a type of key constraint
that requires every value in a given column to be unique.
• In other words, no two rows in a table can have the same value for their primary key
column(s).
• A primary key can either be a single column or multiple columns (known as a
"composite" primary key).
• The null value is not allowed in the primary key column(s).
• To allow naming of a PRIMARY KEY constraint, and for defining a PRIMARY KEY
constraint on multiple columns, use the following SQL syntax:

CREATE TABLE Persons (


ID int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int,
CONSTRAINT PK_Person PRIMARY KEY (ID,LastName)
);

55
Integrity Constraints or Integrity Rules (cont.)
Types of Key Constraints (cont.):

ii. Unique Key Constraints


• A unique key constraint is a column or set of columns that ensures that the values
stored in the column are unique.
• A table can have more than one unique key constraint, unlike the primary key.
• A unique key column can contain NULL values (but only once).
• Like primary keys, unique keys can be made up of a single column or multiple
columns.
• To name a UNIQUE constraint, and to define a UNIQUE constraint on multiple
columns, use the following SQL syntax:

CREATE TABLE Persons (


ID int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int,
CONSTRAINT UC_Person UNIQUE (ID,LastName)
);

56
Integrity Constraints or Integrity Rules (cont.)
Types of Key Constraints (cont.):

iii. Foreign Key Constraints


• A foreign key constraint defines a relationship between two tables.
• A foreign key in one table references a primary key in another table.
• Foreign keys prevent invalid data from being inserted into the foreign key column.
• Foreign keys can reference a single column or multiple columns.
• To define a FOREIGN KEY constraint, use the following SQL syntax:

CREATE TABLE Orders (


OrderID int NOT NULL,
OrderNumber int NOT NULL,
PersonID int,
CONSTRAINT PK_Order PRIMARY KEY (OrderID),
CONSTRAINT FK_PersonOrder FOREIGN KEY (PersonID)
REFERENCES Persons(PersonID)
);

57
Integrity Constraints or Integrity Rules (cont.)
Types of Key Constraints (cont.):

iv. NOT NULL Constraints


• A NOT NULL constraint is used to ensure that no row can be inserted into the table
without a value being specified for the column(s) with this type of constraint. Thus,
every row must have a non-NULL value for these columns.

• To define a NULL constraint, use the following SQL syntax:

CREATE TABLE Persons (


ID int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255) NOT NULL,
Age int
);

58
Integrity Constraints or Integrity Rules (cont.)
Types of Key Constraints (cont.):

v. Check Constraints
• A check constraint enforces data integrity by allowing you to specify conditions that
must be met for data to be inserted into a column.

• For example, you could use a check constraint to ensure that only positive integer
values are inserted into a particular column.

• Check constraints are usually used in combination with other constraints (such as NOT
NULL constraints) to enforce more complex rules.

• The following SQL creates a CHECK constraint on the "Age" column when the
"Persons" table is created. The CHECK constraint ensures that the age of a person
must be 18, or older and less than or equal to 60:
CREATE TABLE Persons (
ID int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int CHECK (Age>=18 and Age<=60)
); 59
Integrity Constraints or Integrity Rules (cont.)
Types of Key Constraints (cont.):

v. Check Constraints (cont.)

• To allow naming of a CHECK constraint, and for defining a CHECK constraint on multiple
columns, use the following SQL syntax:

CREATE TABLE Persons (


ID int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int,
City varchar(255),
CONSTRAINT CHK_Person CHECK (Age>=18 AND City='Sandnes')
);

60
Integrity Constraints or Integrity Rules (cont.)
Types of Key Constraints (cont.):

vi. Default Constraint


• The DEFAULT constraint is used to set a default value for a column.
• The default value will be added to all new records, if no other value is specified.
• If any value is specified, the default value will be overwritten.

• The following SQL sets a DEFAULT value for • The DEFAULT constraint can also be used
the "City" column when the "Persons" to insert system values, by using functions
table is created: like GETDATE():

CREATE TABLE Persons ( CREATE TABLE Orders (


ID int NOT NULL, ID int NOT NULL,
LastName varchar(255) NOT NULL, OrderNumber int NOT NULL,
FirstName varchar(255), OrderDate date DEFAULT GETDATE()
Age int, );
City varchar(255) DEFAULT 'Sandnes'
);

61
Integrity Constraints or Integrity Rules (cont.)

SQL Example – All constraints:


create table tbl_Dept create table tbl_Employee
( (
dept_id int, emp_id int,
dept_name varchar(15), emp_name varchar(25) not null,
constraint pk_dept_id primary emp_age int check (emp_age>18 and emp_age<=60),
key(dept_id) emp_city varchar(20) default 'Lahore',
) emp_email varchar(35) unique,
dept_id int,

constraint pk_emp_id primary key (emp_id),


constraint fk_emp_dept foreign key (dept_id)
references tbl_Dept (dept_id)
)

62
Integrity Constraints or Integrity Rules (cont.)

5. Action Assertion

• Control on the actions of the organization.

• ‘’An Employee can avail a certain facility only after a certain period of service’’.

63
Representing Relational Database Schemas

64
Representing Relational Database Schemas (cont.)

65

You might also like