0% found this document useful (0 votes)
17 views13 pages

Lab Chapter 5

Uploaded by

Tegbaru Tamene
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)
17 views13 pages

Lab Chapter 5

Uploaded by

Tegbaru Tamene
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/ 13

CHAPTER FIVE

5. MySQL CONSTRAINTS
Learning Objectives: After completing this chapter, you should be able to do the following:
• Explain the purpose of constraints in a table
• Distinguish among PRIMARY KEY, FOREIGN KEY, UNIQUE, CHECK, DEFAULT and
NOT NULL constraints and understand the correct use of each constraint
• Create PRIMARY KEY constraints for a single column and a composite primary key
• Create a FOREIGN KEY constraint
• Create UNIQUE, CHECK, and DEFAULT constraints
• Create a NOT NULL constraint with the ALTER TABLE … MODIFY command
• Include constraints during table creation and after table creation.
• Add multiple constraints on a single column
• Use the DROP command with constraints
5.1. Primary Key
A column or columns is called primary key (PK) that uniquely identifies each row in the table.
If you want to create a primary key, you should define a PRIMARY KEY constraint when you create
or modify a table. When multiple columns are used as a primary key, it is known as composite primary
key. It is good for storage and performance both, the more columns you use for primary key the more
storage space you require. In terms of performance, less data means the database can process faster.
Points to remember for primary key:
• Primary key enforces the entity integrity of the table.
• Primary key always has unique data. There can be no duplicate value for a primary key.
• A primary key length cannot be exceeded than 900 bytes.
• A primary key cannot have null value.
• A table can contain only one primary key constraint.
When we specify a primary key constraint for a table, database engine automatically creates a unique
index for the primary key column. Main advantage of primary key: The main advantage of this
uniqueness is that we get fast access.

1
Prepared by: Worku Muluye
5.1.1. Primary Key for One Column
The following SQL command creates a PRIMARY KEY on the "StudentID" column when the
"Student" table is created. MySQL:
CREATE TABLE Student(
StudentID int NOT NULL,
LastName varchar (255) NOT NULL,
FirstName varchar (255),
Address varchar (255),
City varchar (255),
PRIMARY KEY (StudentID));
5.1.2. Primary Key for Multiple Columns
MySQL:
CREATE TABLE CCI_Student (
StudentID int NOT NULL,
LastName varchar (255) NOT NULL,
FirstName varchar (255),
Address varchar (255),
City varchar (255),
CONSTRAINT PK-StudentID PRIMARY KEY (StudentID, LastName));
Note: you should note that in the above example there is only one PRIMARY KEY (PK-StudentID).
However, it is made up of two columns (StudentID and LastName).
5.1.3. Primary Key and Primary Key Constraint on Alter Table
When table is already created and you want to create a PRIMARY KEY constraint on the StudentID
column you should use the following SQL Statement. A primary key (PK) is a single column or
combination of columns (called a compound key) that uniquely identifies each row in a table. A primary
key constraint contains unique, non-null values. When you apply the primary key constraint, the not
NULL and unique constraints are added implicitly. Primary key on one column:
Syntax: ALTER TABLE Student ADD PRIMARY KEY (StudentID)
Primary key constraint:
Syntax: ALTER TABLE Student ADD CONSTRAINT PKStudentID PRIMARY KEY
(StudentID, LastName);
When you use ALTER TABLE statement to add a primary key, the primary key columns must not
contain NULL values (when the table was first created).
5.1.4. Drop Primary Key and Primary Key Constraint
If you want to DROP (remove) a primary key and primary key constraint, you should use following
syntax: MySQL:
Syntax: ALTER TABLE Student DROP PRIMARY KEY;
2
Prepared by: Worku Muluye
5.2. Foreign Key
In the relational databases, a foreign key is a field or a column that is used to establish a link between
two tables. In simple words you can say that, a foreign key in one table used to point primary key in
another table. Here are two tables first one is student table and second is order table. Example: First
table:
STUDENT
StudentID FirstName LastName CITY
1 Abebe Dawit Addis Ababa
2 Ermias Yonas Adama
3 Sara Abraham Bahir Dar
Second table:
ORDER
OrderID OrderNo StudentID
1 99586465 2
2 78466588 2
3 22354846 3
4 57698656 1
Here you see that " StudentID " column in the "Order" table points to the " StudentID " column in
"Student" table. The " StudentID " column in the "Student" table is the PRIMARY KEY in the
"Student" table. The " StudentID " column in the "Order" table is a FOREIGN KEY in the "Order"
table. The foreign key constraint is generally preventing action that destroy links between tables. It also
prevents invalid data to enter in foreign key column.
5.2.1. Foreign Key Constraint on Create Table
(Defining a foreign key constraint on single column) To create a foreign key on the " StudentID "
column when the "Order" table is created: MySQL:
CREATE TABLE Order(
OrderID int NOT NULL,
OrderNo int NOT NULL,
StudentID int,
PRIMAY KEY (OrderID),
FOREIGN KEY (StudentID) REFERENCES Student (StudentID));
5.2.2. Foreign Key and Foreign Key Constraint on Alter Table
If the Order table is already created and you want to create a FOREIGN KEY constraint on the
StudentID column, you should write the following syntax: The FOREIGN KEY constraint is used to
prevent actions that would destroy links between tables. The FOREIGN KEY constraint also prevents
3
Prepared by: Worku Muluye
invalid data from being inserted into the foreign key column, because it has to be one of the values
contained in the table it points to. Defining a foreign key on single column:
Syntax: ALTER TABLE Order ADD FOREIGN KEY(StudentID) references student(StudentID);
Defining a foreign key constraint on single column.
Syntax: ALTER TABLE Order ADD CONSTRAINT FKPerOrder FOREIGN KEY(StudentID)
REFERENCES Student (StudentID)
5.2.3. Drop Foreign Key Constraint
If you want to drop a FOREIGN KEY constraint, use the following syntax.
Syntax: ALTER TABLE Order DROP FOREIGN KEY FKPerOrder
5.2.4. Primary Key Vs Foreign Key
These are some important differences between primary key and foreign key in SQL:
• Primary key cannot be null on the other hand foreign key can be null.
• Primary key is always unique while foreign key can be duplicated.
• Primary key uniquely identifies a record in a table while foreign key is a field in a table that is
primary key in another table.
• There is only one primary key in the table on the other hand we can have more than one foreign
key in the table.
• By default, primary key adds a clustered index on the other hand foreign key does not
automatically create an index, clustered or non-clustered. You must manually create an index for
foreign key.
5.3. Composite Key
A composite key is a combination of two or more columns in a table that can be used to uniquely
identify each row in the table when the columns are combined uniqueness is guaranteed, but when it
taken individually it does not guarantee uniqueness. Sometimes more than one attributes are needed to
uniquely identify an entity. A primary key that is made by the combination of more than one attribute
is known as a composite key. Columns that make up the composite key can be of different data types.
SQL Syntax to specify composite key:
CREATE TABLE TABLE_NAME
(COLUMN_1, DATA_TYPE_1,
COLUMN_2, DATA_TYPE_2,
PRIMARY KEY (COLUMN_1, COLUMN_2, ...));
In all cases composite key created consist of COLUMN1 and COLUMN2.
MySQL:
CREATE TABLE SAMPLE_TABLE (COL1 int,
4
Prepared by: Worku Muluye
COL2 varchar(30),
COL3 varchar(50),
PRIMARY KEY (COL1, COL2));
5.4. Unique Key
A unique key is a set of one or more than one fields/columns of a table that uniquely identify a record
in a database table. You can say that it is little like primary key but it can accept only one null value
and it cannot have duplicate values. The unique key and primary key both provide a guarantee for
uniqueness for a column or a set of columns. There is an automatically defined unique key constraint
within a primary key constraint. There may be many unique key constraints for one table, but only one
PRIMARY KEY constraint for one table.
5.4.1. Unique Key Constraint on Create Table
If you want to create a UNIQUE constraint on the StudentID column when the Student table is created,
use the following syntax. Defining a unique key constraint on single column. MySQL:
CREATE TABLE student(
StudentID int NOT NULL,
LastName varchar (255) NOT NULL,
FirstName varchar (255),
City varchar (255),
UNIQUE (StudentID));
Defining a unique key constraint on multiple columns. MySQL:
CREATE TABLE Student(
S_Id int NOT NULL,
LastName varchar (255) NOT NULL,
FirstName varchar (255),
City varchar (255),
CONSTRAINT UCStudentID UNIQUE (StudentID, LastName));
5.4.2. Unique Key Constraint on Alter Table
If you want to create a unique constraint on StudentID column when the table is already created, you
should use the following syntax. Defining a unique key constraint on single column. MySQL:
ALTER TABLE student ADD UNIQUE (StudentID);
Defining a unique key constraint on multiple columns:
ALTER TABLE student ADD CONSTRAINT UCStudentID UNIQUE (StudentID, LastName);
5.4.3. Drop Unique Key Constraint
If you want to drop a UNIQUE constraint, use the following MySQL syntax:
MySQL: ALTER TABLE student DROP UNIQUE UCStudentID;

5
Prepared by: Worku Muluye
5.5. DEFAULT Constraint
The DEFAULT constraint is used to provide a default value for a column. The default value will be
added to all new records IF no other value is specified. MySQL

CREATE TABLE Person (


PID int NOT NULL,
LastName varchar(25) NOT NULL,
FirstName varchar(25),
Age int,
City varchar(50) DEFAULT 'Addis Ababa'
);
Not null, unique, check and default constraints.
create table studentIS(ID int,
Fname varchar(10),
Lname varchar(50) not null, -- Not null constraint, this column cannot be null.
Email varchar(60) unique, -- unique constraint, this column must have unique value & can be null once.
age int check(age >=18), -- Check constraint it is not work in MySQL
city varchar(40) default 'Addis Ababa'); -- Default constraint, with default value ‘Addis Ababa’
-- Insert value into StudentIS table.
insert into studentIS(ID, Fname, Lname, Email, age) values(1, 'A', 'B', 'H', 2);

5.6. CHECK Constraint


The following SQL creates a CHECK constraint on the "Age" column when the "Person" table is
created. The CHECK constraint ensures that you cannot have any person below 18 years: MySQL:
However, it is not work in MySQL example.
CREATE TABLE Person(
ID int NOT NULL,
Age int,
CHECK (Age>=18 and Age <=200));
insert into person(ID, age) values(10, 2);
5.6.1. CHECK on ALTER TABLE
To create a CHECK constraint on the "Age" column when the table is already created.
ALTER TABLE Person ADD CONSTRAINT CHK_PersonAge CHECK (Age>=18 AND City='Addis Ababa);
5.6.2. DROP a CHECK Constraint
To drop a CHECK constraint use the following syntax.
ALTER TABLE Person DROP CHECK CHK_PersonAge;

6
Prepared by: Worku Muluye
5.7. CREATE INDEX Statement
The CREATE INDEX statement is used to create indexes in tables. Indexes are used to retrieve data
from the database very fast. The users cannot see the indexes; they are just used to speed up
searches/queries.
Note: Updating a table with indexes takes more time than updating a table without (because the indexes
also need an update). So, only create indexes on columns that will be frequently searched against.
CREATE INDEX Syntax: Creates an index on a table. Duplicate values are allowed:
Syntax: CREATE INDEX index_name ON table_name (column1, column2, ...);
CREATE UNIQUE INDEX Syntax: Creates a unique index on a table. Duplicate values are not allowed:
Syntax: CREATE UNIQUE INDEX index_name ON table_name (column1, column2, ...);
Note: The syntax for creating indexes varies among different databases. Therefore: Check the syntax
for creating indexes in your database.
Example: CREATE INDEX Indexlastname ON Person (LastName);
DROP INDEX Statement: The DROP INDEX statement is used to delete an index in a table.
Syntax: ALTER TABLE table_name DROP INDEX index_name;

5.8. Referential Integrity Rule


• Records cannot be inserted into a child table if corresponding records in the parent table don’t exist.
• Records cannot be updated in a child table if corresponding records in the parent table don’t
updated.
• Records of the parent table cannot be deleted if corresponding records in the child table exist.
• Also, there are drop table and truncate table referential rules.

7
Prepared by: Worku Muluye
Example
create CCI database
Create database CCI;
Use CCI;
Create view table from single table.
Create view table from multiple table by using join and set operations reading assignment.
Create department table.
create table department(depid int auto_increment,
depname varchar(60),
location varchar(80),
primary key(depid));
Insert data into department table.
insert into department(depname, location) values('IS', 145), ('CS', 145),('IT', 145), ('SE', 145);
update data into department table.
update department set depid=90, depid =100 where depid = 1 and 4;
Create student table and include DEPID as a foreign key in student table since there is one to many
relationships between department and student table.
create table student (StudID int auto_increment,
Fname varchar(30),
age int,
primary key(StudID),
depid int,
foreign key (depid) references department (depid));
Insert data into student table.
insert into student(fname,Age, depid) values('Abebe', 21, 1),('Abel', 12, 2),('Dawit', 30, 3);
Create instructor table and include DEPID as a foreign key in an instructor table since there is one to
many relationships between department and instructor table.
create table instructor( instid int auto_increment,
Fname varchar(50),
age int,
primary key(instid),
depid int,
foreign key (depid) references department (depid));
Insert data into instructor table.
insert into instructor(fname,Age, depid) values('Abebe', 27, 3),('Abel',28, 2),('Dawit',30, 3);

8
Prepared by: Worku Muluye
Create junction table for student and instructor because there is a many to many relationships between
student and instructor table.
create table studentinstructor(instid int,
Studid int,
foreign key (instid) references instructor(instid),
foreign key (studid) references student(studid));
Insert data into studentinstructor junction table.
insert into studentinstructor (instid, id) values(1, 2),(3, 2),(1, 3);
select all data from student, department, instructor and studentinstructor tables.
select * from student;
select * from department;
select * from instructor;
select * from studentinstructor;
Delete data from parent table and child table and understand referential integrity rule. First delete the
record from child table and then delete records from parent table. Example.
delete from studentinstructor;
delete from instructor;
delete from student;
delete from department;
Truncate from student, department, instructor and studentinstructor tables. You cannot truncate a table
which is referenced by another table. You can truncate the last sub child table(if any) but not the sub
child parent table and the parent table.
Truncate table studentinstructor; -- you can truncate this table.
Truncate table student;
Truncate table instructor;
Truncate table department;
Drop student, department, instructor and studentinstructor tables. First drop sub child table (if any) then
then drop the sub child parent table and then drop the parent table. Example.
Drop table studentinstructor;
Drop table Student;
Drop table instructor;
Drop table department;
5.9. On Delete Cascade and On Update Cascade
On Delete Cascade and On Update Cascade is the first solution to solve the above data inconsistency
problem.
CASCADE: On Delete Cascade and On Update Cascade are used to solve the data inconsistency
problem among parent and child tables i.e. when you delete or update data from a parent table the data
also deleted or updated which is referenced in child or sub child tables.

9
Prepared by: Worku Muluye
Syntax1: FOREIGN KEY (col_name) REFERENCES table_name (col_name) ON DELETE
CASCADE ON UPDATE CASCADE;
Syntax2: FOREIGN KEY (col_name) REFERENCES table_name (col_name) ON DELETE
reference_option ON UPDATE reference_option;
where reference_option=RESTRICT | CASCADE | SET NULL | NO ACTION | SET DEFAULT
SET NULL: Delete or update the row from the parent table, and set the foreign key column or columns
in the child table to NULL. Both ON DELETE SET NULL and ON UPDATE SET NULL clauses are
supported. If you specify a SET NULL action, make sure that you have not declared the columns in the
child table as NOT NULL.
RESTRICT: Rejects the delete or update operation for the parent table. Specifying RESTRICT (or
NO ACTION) is the same as omitting the ON DELETE or ON UPDATE clause.
NO ACTION: A keyword from standard SQL. In MySQL, equivalent to RESTRICT. The MySQL
Server rejects the delete or update operation for the parent table if there is a related foreign key value
in the referenced table. Some database systems have deferred checks, and NO ACTION is a deferred
check. In MySQL, foreign key constraints are checked immediately, so NO ACTION is the same as
RESTRICT.
SET DEFAULT: This action is recognized by the MySQL parser, but both InnoDB and NDB reject
table definitions containing ON DELETE SET DEFAULT or ON UPDATE SET DEFAULT clauses.
For an ON DELETE or ON UPDATE that is not specified, the default action is always RESTRICT.
create WKU database
Create database WKU;
Use WKU;
Create department table.
create table department(depid int auto_increment,
depname varchar(60),
location varchar(80),
primary key(depid));
Insert data into department table.
insert into department(depname, location) values('IS', 145), ('CS', 145),('IT', 145), ('SE', 145);
update data into department table.
Create student table and include DEPID as a foreign key in student table since there is one to many
relationships between department and student table.
create table student (StudID int auto_increment,
Fname varchar(30),
age int,
primary key(StudID),
10
Prepared by: Worku Muluye
depid int,
foreign key (depid) references department (depid) on update cascade on delete cascade);
Insert data into student table.
insert into student(fname,Age, depid) values('Abebe', 21, 1),('Abel', 12, 2),('Dawit', 30, 3);
Create instructor table and include DEPID as a foreign key in an instructor table since there is one to
many relationships between department and instructor table.
create table instructor( instid int auto_increment,
Fname varchar(50),
age int,
primary key(instid),
depid int,
foreign key (depid) references department (depid) on update cascade on delete cascade);
Insert data into instructor table.
insert into instructor(fname,Age, depid) values('Abebe', 27, 3),('Abel',28, 2),('Dawit',30, 3);
Create junction table for student and instructor because there is a many to many relationships between
student and instructor table.
create table studentinstructor(instid int,
Studid int,
foreign key (instid) references instructor(instid on update cascade on delete cascade),
foreign key (studid) references student(studid) on update cascade on delete cascade);
Insert data into studentinstructor junction table.
insert into studentinstructor (instid, id) values(1, 2),(3, 2),(1, 3);
select all data from student, department, instructor and studentinstructor tables.
select * from student;
select * from department;
select * from instructor;
select * from studentinstructor;
If you are used on delete cascade and on update cascade you can delete and update data only from your
parent table.
delete from instructor where instid=1;
delete from student where studid=4;
delete from department where depid>=3;
update department set depid=90, depid =100 where depid = 1 and 4;
Truncate from student, department, instructor and studentinstructor tables. You cannot truncate a table
which is referenced by another table. You can truncate the last sub child table(if any) but not the sub
child parent table and the parent table.
Truncate table studentinstructor; -- you can truncate this table.
Truncate table student;
Truncate table instructor;
Truncate table department;

11
Prepared by: Worku Muluye
Drop student, department, instructor and studentinstructor tables. First drop sub child table (if any) then
then drop the sub child parent table and then drop the parent table. Example.
Drop table studentinstructor;
Drop table Student;
Drop table instructor;
Drop table department;
Summary
A constraint is a rule applied to data being added to a table. It represents business rules, policies, or
procedures. Data violating the constraint isn’t added to the table. A constraint can be included during
table creation as part of the CREATE TABLE command or added to an existing table with the ALTER
TABLE command. A constraint based on composite columns (more than one column) must be created
by using the table-level approach. A NOT NULL constraint can be created only with the column-level
approach. A PRIMARY KEY constraint doesn’t allow duplicate or NULL values in the designated
column. Only one PRIMARY KEY constraint is allowed in a table.
A FOREIGN KEY constraint requires that the column entry match a referenced column entry in the
table or be NULL. A UNIQUE constraint is similar to a PRIMARY KEY constraint, except it allows
storing NULL values in the specified column. A CHECK constraint ensures that data meets a given
condition before it’s added to the table. The condition can’t reference the SYSDATE function or values
stored in other rows. A NOT NULL constraint is a special type of CHECK constraint. If you’re adding
to an existing column, the ALTER TABLE … MODIFY command must be used. A column can be
assigned multiple constraints. The data dictionary views USER_CONSTRAINTS and
USER_CONS_COLUMNS enable you to verify existing constraints. A constraint can be disabled or
enabled with the ALTER TABLE command and the DISABLE and ENABLE keywords. A constraint
can’t be modified. To change a constraint, you must first drop it with the DROP command and then re-
create it.
Review Questions
1. What is the difference between a PRIMARY KEY constraint and a UNIQUE constraint?
2. How can you verify the constraints that exist for a table?
3. A table can have a maximum of how many PRIMARY KEY constraints?
4. How is adding a NOT NULL constraint to an existing table different from adding other types of
constraints?
5. When must you define constraints at the table level rather than the column level?
6. What is the difference between disabling a constraint and dropping a constraint?
7. What is the simplest way to determine whether a particular column can contain NULL values?
Depending on the figure below answer question 8 to question 14:

12
Prepared by: Worku Muluye
8. Write a SQL statement to add a primary key for the columns location_id in the location table.
9. Write a SQL statement to add a primary key for a combination of columns location_id and
country_id?
10. Write a SQL statement to drop the existing primary from the table location on a combination of
columns location_id and country_id?
11. Write a SQL statement to add a foreign key on job_id column of job_history table referencing to
the primary key job_id of job table?
12. Write a SQL statement to add a foreign key constraint named fk_job_id on job_id column of
job_history table referencing to the primary key job_id of job table?
13. Write a SQL statement to drop the existing foreign key fk_job_id from job_history table on job_id
column which is referencing to the job_id of job table?
14. Write a SQL statement to add an index named indx_job_id on job_id column in the table
job_history? Write a SQL statement to drop the index indx_job_id from job_history table?

13
Prepared by: Worku Muluye

You might also like