You are on page 1of 9

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, and NOT
NULL constraints and understand the correct use of each constraint
 Understand how to create constraints when creating a table or modifying an existing table
 Distinguish between creating constraints at the column level and the table level
 Create PRIMARY KEY constraints for a single column and a composite primary key
 Create a FOREIGN KEY constraint
 Create a UNIQUE constraint
 Create a CHECK constraint
 Create a NOT NULL constraint with the ALTER TABLE … MODIFY command
 Include constraints during table creation
 Add multiple constraints on a single column
 View constraint information
 Use the DISABLE and ENABLE commands with constraints
 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.
1
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.
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(
S_Id int NOT NULL,
LastName varchar (255) NOT NULL,
FirstName varchar (255),
Address varchar (255),
City varchar (255),
PRIMARY KEY (StudentID));
SQL Server, Oracle, MS Access:
CREATE TABLE Student (
StudentID int NOT NULL PRIMARY KEY,
LastName varchar (255) NOT NULL,
FirstName varchar (255),
Address varchar (255),
City varchar (255));
5.1.2. Primary Key for Multiple Columns
MySQL, SQL Server, Oracle, MS Access:
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).

2
5.1.3. Primary key 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. Primary key on one column:
Syntax: ALTER TABLE Student ADD PRIMARY KEY (StudentID)
Primary key on multiple column:
Syntax: ALTER TABLE Student ADD CONSTRAINT PK StudentID 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 Constraint
How to DROP a PRIMARY KEY constraint? If you want to DROP (remove) a primary key
constraint, you should use following syntax: MySQL:
Syntax: ALTER TABLE Student DROP PRIMARY KEY;
SQL Server / Oracle / MS Access:
Syntax: ALTER TABLE Student DROP CONSTRAINT PK-StudentID;
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 students 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

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));
SQL Server /Oracle / MS Access:
CREATE TABLE Order(
OrderID int NOT NULL PRIMAY KEY,
OrderNo int NOT NULL,
StudentID int FOREIGN KEY REFERENCES Student (StudentID));
5.2.2. Foreign Key Constraint for 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: Defining a foreign key constraint on
single column:
MySQL / SQL Server / Oracle / MS Access:
Syntax: ALTER TABLE Order ADD CONSTRAINT FK-PerOrder FOREIGN KEY(StudentID
REFERENCES Students (StudentID)
5.2.3. Drop Syntax for Foreign Key Constraint
If you want to drop a FOREIGN KEY constraint, use the following syntax:
MySQL:
4
Syntax: ALTER TABLE Order ROP FOREIGN KEY FK-PerOrder
SQL Server / Oracle / MS Access:
Syntax: ALTER TABLE Order DROP CONSTRAINT FK-PerOrder
5.2.4. Primary Key Vs Foreign Key in SQL
These are some important difference 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. In other words, we can say that, composite key is a
key which is the combination of more than one field or column of a given table. It may be a
candidate key or primary 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:

5
CREATE TABLE SAMPLE_TABLE (COL1 int,
COL2 varchar(30),
COL3 varchar(50),
PRIMARY KEY (COL1, COL2));
Oracle:
CREATE TABLE SAMPLE_TABLE (COL1 int,
COL2 varchar(30),
COL3 varchar(50),
PRIMARY KEY (COL1, COL2));
MS SQL Server:
CREATE TABLE SAMPLE_TABLE (COL1 int,
COL2 nvarchar(30),
COL3 nvarchar(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 SQL syntax: (Defining a unique key constraint on single column):
SQL Server / Oracle / MS Access:
CREATE TABLE Student(
StudentID int NOT NULL UNIQUE,
LastName varchar (255) NOT NULL,
FirstName varchar (255),
City varchar (255));
MySQL:
CREATE TABLE student(
StudentID int NOT NULL,
6
LastName varchar (255) NOT NULL,
FirstName varchar (255),
City varchar (255),
UNIQUE (StudentID));
(Defining a unique key constraint on multiple columns):
MySQL / SQL Server / Oracle / MS Access:
CREATE TABLE Student(
S_Id int NOT NULL,
LastName varchar (255) NOT NULL,
FirstName varchar (255),
City varchar (255),
CONSTRAINT UC-StudentID 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 SQL syntax: (Defining a unique key constraint on single column):
MySQL / SQL Server / Oracle / MS Access:
ALTER TABLE student ADD UNIQUE (StudentID);
(Defining a unique key constraint on multiple columns):
MySQL / SQL Server / Oracle / MS Access:
ALTER TABLE student ADD CONSTRAINT UC-StudentID UNIQUE (StudentID, LastName);
5.4.3. Drop Foreign Key Constraint
If you want to drop a UNIQUE constraint, use the following SQL syntax:
MySQL: ALTER TABLE student DROP INDEX UC-StudentID;
SQL Server/Oracle/MS Access: ALTER TABLE student DROP CONSTRAINT UC-
StudentID;
5.5. Alternate Key in SQL
Alternate key is a secondary key it can be simple to understand by an example: Let's take an
example of student it can contain NAME, ROLL_NO., ID and CLASS. Here ROLL_NO. is
primary key and rest of all columns like NAME, ID and CLASS are alternate keys. If a table has
more than one candidate key, one of them will become the primary key and rest of all are called
alternate keys. In simple words, you can say that any of the candidate key which is not part of
primary key is called an alternate key. So when we talk about alternate key, the column may not
7
be primary key but still it is a unique key in the column. An alternate key is just a candidate key
that has not been selected as the primary key.

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. to make certain the category for a book is included when a new book is added to inventory?
5. How is adding a NOT NULL constraint to an existing table different from adding other types
of constraints?
6. When must you define constraints at the table level rather than the column level?
7. What is the difference between disabling a constraint and dropping a constraint?
8. What is the simplest way to determine whether a particular column can contain NULL values?
8
Depending on the figure below answer question 9 to question 16:

9. Write a SQL statement to add a primary key for the columns location_id in the location table.
Here is the sample table employee?
10. Write a SQL statement to add a primary key for a combination of columns location_id and
country_id?
11. Write a SQL statement to drop the existing primary from the table location on a combination
of columns location_id and country_id?
12. 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?
13. 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?
14. 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?
15. 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?
9

You might also like