0% found this document useful (0 votes)
16 views

Lecture 3 Examples

Uploaded by

maeveschoudel21
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)
16 views

Lecture 3 Examples

Uploaded by

maeveschoudel21
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/ 33

IE 3425 Eng’g.

Database
Lecture 3 Examples
Topics: Integrity Constraints, Derived Attributes,
Attribute Types, Relationship Types

© Professor Zeid, Northeastern University


Integrity Constraints

 Integrity constraints are are pre-defined set of rules that are


applied on the table fields(columns) or relations to ensure that
the overall validity, integrity, and consistency of the data
present in the database table is maintained
 Evaluation of all the conditions or rules mentioned in the
integrity constraint is done every time a table insert, update,
delete, or alter operation is performed
 The data can be inserted, updated, deleted, or altered only if
the constraint is satisfied.
 Thus, integrity constraints are useful in preventing any
accidental damage to the database by an authorized user.
Types of Integrity Constraints

There are four types of


integrity constraints in DBMS:
 Domain Constraint
 Entity Constraint
 Referential Integrity
Constraint
 Key Constraint
Domain Constraint

 Domain integrity constraint contains a certain set of rules


or conditions to restrict the kind of attributes or values a
column can hold in the database table.
 The data type of a domain can be text, integer, numeric,
datetime, currency, etc.
 The value of the attribute must be available in the
corresponding domain.
 See Example 1
Example 1: Domain Constraint
 Example 1 Consider a student table having roll no, name, age,
class of students.

student_roll_n
student_name student_age student_class
umber

101 Adam 14 6
102 Steve 16 8
103 David 8 4
104 Bruce 18 12
105 Tim 6 A
 In the above student table, the value A in the last row last
column violates the domain integrity constraint because the Class
attribute contains only integer values while A is a character.
Entity Integrity Constraint

 Entity Integrity Constraint is used to ensure that the


primary key cannot be null.
 A primary key is used to identify individual records in a
table and if the primary key has a null value, then we
can't identify those records.
 There can be null values anywhere in the table except
the primary key column (unless we specify in the design
that the attribute is ‘not null’.
 Entity integrity applies to one table only
 A table has entity integrity if all its PK values are unique
and not null (undefined) or blank (spacebar hit)
 See Example 2
Example 2: Entity Integrity Constraint
 Consider employee table having id, name, and salary of
employees

employee_id employee_name employee_salary

1101 Jackson 40000


1102 Harry 60000
1103 Steve 80000
1104 Ash 1800000
James 36000

 In the above employee's table, we can see that the id column is


the primary key and contains a null value in the last row which
violates the entity integrity constraint.
Referential Integrity Constraint

 Referential Integrity Constraint ensures that there must always


exist a valid relationship between two relational database
tables.
 This valid relationship between the two tables confirms that a
foreign key exists in a table.
 If a table has FK values and these values match the PK values in
the related table or are null, the table with FK values has
referential integrity (applies to table with FK)
 Referential integrity prevents pointing to non-existent PK
values
 See Example 3
Example 3: Referential Integrity Constraint
 Consider an employee and a department table where department_id
acts as a foreign key between the two tables
employee Table department Table
employee employee employee employee department_nam
_id _name _salary _dept_id department_id
e
1101 Jackson 40000 3 1 Sales
1102 Harry 60000 2
2 HR
1103 Steve 80000 4
3 Technical
1104 Ash 1800000 3
1105 James 36000 1

 In the above example, department_id acts as a foreign key in the


employee table and a primary key in the department table. Row
having department_id =4 violates the referential integrity constraint
since department_id 4 is not defined as a primary key column in the
department table.
Key constraint – Reiterating the Concept

 Keys are the set of entities that are used to identify an entity
within its entity set uniquely.
 There could be multiple keys in a single entity set, but out of
these multiple keys, only one key will be the primary key.
 A primary key can only contain unique and not null values in the
relational database table.
 See Example 4
Example 4: Key Constraint
 Consider a student table

student_roll_n
student_name student_age student_class
umber
101 Adam 14 6
102 Steve 16 8
103 David 8 4
104 Bruce 18 12
102 Tim 6 2
 The last row of the student table violates the key integrity
constraint since student_roll_number 102 is repeated twice in
the primary key column. A primary key must be unique and not null
therefore duplicate values are not allowed in the
student_roll_number column of the above student table.
Data type Description
CHARACTER(n) Character string. Fixed-length n
Text Character string. Variable length
VARCHAR(n) or CHARACTER Character string. Variable length. Maximum
VARYING(n) length n

Data Types BINARY(n)


BOOLEAN
Binary string. Fixed-length n
Stores TRUE or FALSE values
VARBINARY(n) or BINARY Binary string. Variable length. Maximum length n
VARYING(n)
INTEGER(p) Integer numerical (no decimal).
 Data type states the type of SMALLINT Integer numerical (no decimal).

values that can be stored in a INTEGER Integer numerical (no decimal).

particular column BIGINT Integer numerical (no decimal).


DECIMAL(p,s) Exact numerical, precision p, scale s.

 The data type not only tells NUMERIC(p,s) Exact numerical, precision p, scale s. (Same as
DECIMAL)
the column which type of FLOAT(p) Approximate numerical, mantissa precision p. A
values can be inserted but also floating number in base 10 exponential notation.
REAL Approximate numerical
what values cannot be used in
FLOAT Approximate numerical
a column DOUBLE PRECISION Approximate numerical

 Some common datatypes in DATE Stores year, month, and day values
TIME Stores hour, minute, and second values
SQL are shown in the table TIMESTAMP Stores year, month, day, hour, minute, and
second values
 Keep in mind that each INTERVAL Composed of a number of integer fields,
database system recognizes its representing a period of time, depending on the
type of interval
own set of datatypes ARRAY A set-length and ordered collection of elements
MULTISET A variable-length and unordered collection of
elements
XML Stores XML data
SQLite Datatypes

STORAGE
USES
CLASS

There are 5 storage classes in NULL Value is a null value.

SQLite, i.e. all the datatypes that Value is a signed integer.


Depending on the magnitude of the
we have seen in the previous table INTEGER
value, it can be stored in 1, 2, 3, 4,
can be stored in one of these five 6, or 8 bytes.
classes Value is a floating-point value.
REAL Stored as an 8-byte IEEE floating
We will mostly be dealing with point number.
Integer, Real, Text and Null
Value is a text string.
text Stored using the database encoding
(utf-8, utf-16be or utf-16le)
Value is a blob of data.
BLOB
Stored exactly as it was input.
What types of data are allowed in
SQLite classes?
 Integer class allows all the DATA TYPE AFFINITY
integer data types such as INT,
INTEGER, etc. INT INTEGER TINYINT SMALLINT
MEDIUMINT BIGINT UNSIGNED INTEGER
 Text class can contain VARCHAR,
TEXT, CHAR, etc. BIGINT INT2 INT8

 BLOB stands for Binary Large CHARACTER(20) VARCHAR(255)


Object – a collection of binary VARYING CHARACTER(255)
data stored as a value in the DB. NCHAR(55) NATIVE TEXT
Blob can be documents, images, CHARACTER(70) NVARCHAR(100)
or other multimedia files. TEXT CLOB
 Real class can contain any real
values including Float. BLOB no datatype specified NONE
 Numeric class is used mostly for REAL DOUBLE DOUBLE PRECISION
REAL
Date, Datetime and Decimal FLOAT
values
NUMERIC DECIMAL(10,5) BOOLEAN
NUMERIC
DATE DATETIME
Date Attributes – Using text Composite Primary Key

 Suppose we wanted to create a date attribute in the invoice table.


 For the time being, ignore any FK relationships
Set date attribute as
text data type

Note that invoice_number


In the insert into statement, and invoice_date are shown
results use the date() function while as CPK just as an example.
entering the date In that lab, you should
 We use the ISO8601 date format which is ’yyyy-mm-dd’ create invoice_number and
invoice_line as CPK.
 The time format is ‘hh:mm:ss.sss’
 and datetime format is ‘yyyy-mm-dd hh:mm:ss.ssss
 For more date and time related information in sqlite, check out the strftime()
Attribute Types
 There are a few types of attributes you need to be familiar with.
 Some of these are to be left as is, but some need to be adjusted to
facilitate representation in the relational model.
 It is important to note that Attribute type ≠ attribute data type
 Attribute type is established before deciding on the attribute’s data type
The different types of attributes in a DB are as follows:
 Simple attributes
 Composite attributes
 Single valued attributes
 Multi valued attributes
 Derived attributes
Attribute Types
 Simple attributes are those drawn from the atomic value
domains; they cannot be divided or broken down into multiple
attributes
Examples: The roll number of a student, the id number of an
employee, SSN of a person
 A composite attribute is one that can be further divided into
meaningful sub-parts based on the values of that attribute.
Examples: Name, which can be stored as the first name, last
name, and middle initial. Another example is address.
 An attribute which takes up only a single value for each entity
instance is a single-valued attribute.
Examples: The age of a student, the id number of an employee,
SSN of a person
Attribute Types

 Multivalued attributes are attributes that have a set of values


for each entity. They can take up more than a single-value.
Examples: Phone number of a student: Landline and mobile.
Other examples include a student’s major (MATH, ECON), and
an employee’s degree (BS, MS, PhD)
 Derived attributes are attributes that contain values calculated
from other attributes.
Examples: sales tax, invoice total, average grades of a student

The best attribute type in DB design is simple-single valued


Derived Attributes
 Derived attributes are calculated automatically via SQL queries
(update query)
 A derived attribute is one that is not really input by DB user and
requires calculations using one or more table attributes
 Class discussion
Relationship Types
 Tables of a single DB may share attributes using keys (FK). This
introduces the concept of relationships
 Relationships between tables are fundamental to the SQL join
queries. Without them, a DB will be of limited use
 There are 3 types of relationships when it comes to DB design:
 One-to-one (1:1): one entity in a table is related to only one
entity in another table
 One-to-many (1:M): one entity in one table is related to
multiple entities in the other table
 Many-to-many (M:N): multiple entities in one table are related
to multiple entities in the other table
 See Example 5
Example 5: Relationship Types
One-to-one (1:1) relationship example:
Tables: person and passport
 Each person has only one passport and each passport belongs to only
one person. 1:1 is rare
One-to-many (1:M) relationship example (most common):
Tables: invoice and customer
 A customer may generate more than one invoice, and an invoice belongs
to only one customer. 1:M is the most common in DB design
Many-to-many (M:N) relationship example:
Tables; employee and degree
 An employee may have multiple degrees and a degree is attained by
multiple employees. You DB Design should never have M:N type
Example 5: Relationship (schema) Diagram
(generated form Microsoft Access)
Relationships in SQLite
 To check whether your current version of SQLite supports foreign key
constraints or not, you use the following command:

 The command returns an integer value: 1: enable, 0: disabled. If the


command returns nothing, it means that your SQLite version doesn’t support
foreign key constraints.
 To enable foreign key constraint, type the following command:

 Foreign keys can be established now that the constraint has been enabled.

Note: You will have to enable foreign keys every time you reopen SQLite on your computer.
Without enabling foreign keys, you will be still be able to add data, so make sure to enable FK’s.
Establishing Relationships
 Suppose we add more data to the employee table, and we want
to establish a relationship between the employee and seller
table. This would be a One-One relationship.
 We can write the query as shown below to create a seller table
that consists of a Foreign Key (employee_id) referencing the
employee_id from the employee table

 In this case, the employee table would be the Parent table


(the table that a foreign key constraint refers to) and the
seller table would be the Child table (the table that a foreign
key constraint is applied to and the table that contains the
references clause)
Testing the FK Relationship – Referential
Integrity Constraint
 Insert some values into the seller table.
 Remember, for the referential integrity constraint to hold, any
FK value in the seller table (employee_id) must already exist in
the employee table (as employee_id)
1. Insert a record
into Seller table
2. View records
in seller table
3. View records
in employee
table

4. Insert a record into seller table that


5. The referential integrity constraint holds violates the referential Integrity constraint
and prevents the record from being inserted
SQLite FK Constraint Actions
 What would happen if you delete a row in the employee table? Should all the
corresponding rows in the seller table are also deleted?
 The same questions can be asked if we update a row in the employee table
 To specify how foreign key constraint behaves whenever the parent key is deleted or
updated, you use the on delete or on update action as follows:
foreign key (foreign_key_columns)
references parent_table(parent_key_columns)
on update action
on delete action;
 In practice, the values of the primary key in the parent table do not change therefore
the update rules are less important. The more important rule is the delete rule that
specifies the action when the parent key is deleted.
 SQLite supports the following actions: set null, set default, restrict, no action, and
cascade.
 We’ll examine each of the above actions
set null
 When the parent key changes, delete or update, the corresponding child keys
of all rows in the child table set to null.

First, drop and create the


table seller using the set null action
for the employee_id foreign key:

Second, insert some rows


into the seller table
Third, delete employee_id
1 from the employee table

Fourth, query data from the seller table.


See the null value in the 3rd column of results
set default
 The set default action sets the value of the foreign key to the default value
specified in the column definition when you create the table.
 Because the values in the column employee_id defaults to null, if you delete a
row from the employee table, the values of the employee_id will set to null.
 After assigning the default value, the foreign key constraint kicks in and carries First, add employee_id
the check. 1 back since we
dropped it while testing
the set null action

Second, drop and create the seller table using


the set null action for the employee_id foreign key

Third, insert some rows into


the seller table

Fourth, delete employee_id


1 from the employee table
See the default value (null) in the 3rd column of results
restrict
 The restrict action does not allow you to change or delete values in the parent key of the parent
table. First, Add employee_id
1 back since we
dropped it while testing
the set default action

Second, drop and create the seller table using


the restrict action for the employee_id foreign key

Third, insert some rows into


the seller table

Fourth, delete employee_id


1 from the employee table

We see that we are not able to delete employee_id = 1 due to the restrict action

To avoid this, we must first delete the records from the


seller table (child table) before deleting the records from the employee table (parent table),
no action
 The no action does not mean by-pass the foreign key constraint.
 It has the similar effect as the restrict.

 Practice it on your own time.


cascade
 The cascade action propagates the changes from the parent table to the child table when
you update or delete the parent key.
 First, let’s add some more records into the employee table
First, some records into
the employee table

Second,drop and create


the seller table using
the cascade action for
the employee_id foreign
key
Third, insert some rows
into the seller table
Fourth, update employee_id in the employee table, and see the
results in the seller table. The employee_id is automatically
updated in the seller table due to cascade.
Fifth, delete employee_id in the employee table, and see the
results in the seller table. The employee_id is automatically
deleted in the seller table due to cascade.
on update and delete actions
We have seen all the actions that are available in mysqlite. To recap,
 the set null action sets the employee_id value to null in the seller table when it
is deleted from the parent table
 The set default action sets the employee_id value to the default value (null) in
the seller table when it is deleted from the parent table
 The restrict action prevents us from deleting the employee_id from the
employee table (parent) before it is deleted from the seller table (child)
 Similar to the restrict action, the no action condition prevents
updation/deletion
 The cascade condition, allows the update of employee_id from the employee
table, and simultaneously updates the employee_id in the seller table. It works
in the same way for delete queries too.
Good Database Design
 Good DB designs do not use M:N relationships because it is
bad for editing and updating the DB
 M:N relationship results from using multi-valued attributes
 Use 1:1 and 1:M relationships (1:M are most common)
 Table key (PK, CPK) controls the relationship type
 Class discussion

You might also like