RELATIONAL MODELS
IV
Learning Objectives
1. Explain the Constraints Types (check
constraints, NOT NULL Constraints)
2. Introduction to constraints (Integrity, Primary
Key constraints, Foreign key constraints,
unique constraints).
CONSTRAINTS
Constraints are the rules enforced on data
columns table to limit the type of data that can
go into a table.
Constraints could be column level or table level.
Constraints Types
NOT NULL Constraints: Ensures that a column cannot have
NULL value.
DEFAULT Constraint: Provides a default value for a column
when non is specified.
UNIQUE Constraint: Ensure that all values in a column are
different.
PRIMARY Key: Uniquely identifies each row/column in a
database table.
FOREIGN Key: Uniquely identifies a row/column in any
other database table.
CHECK Constraint: This ensures that all values in a
column satisfy certain conditions .
INDEX: Used to create and retrieve data from the
database very quickly.
Integrity Constraints
Integrity constraints are used to ensure accuracy
and consistency of data in a relational database.
Data integrity is handled in a relational database
through the concept of referential integrity.
All the constraints mentioned above play a role
in referential integrity.
Create Primary Key
Below is the syntax to define ID attribute as a primary key in a
CUSTOMERS table:
CREATE TABLE CUSTOMERS(
ID INT NOT NULL,
NAME VARCHAR (20) NOT NULL,
AGE INT NOT NULL,
ADDRESS CHAR (25),
SALARY DECIMAL (18, 2),
PRIMARY KEY (ID));
A table can have only one primary key which may
consist of single or multiple fields.
Activity
When multiple fields are used as a primary
key, they are called _________.
When multiple fields are used as a primary key, they
are called Composite key.
SAMPLE:
CREATE TABLE CUSTOMERS(
ID INT NOT NULL,
NAME VARCHAR (20) NOT NULL,
AGE INT NOT NULL,
ADDRESS CHAR (25),
SALARY DECIMAL (18, 2),
PRIMARY KEY (ID, NAME));
To create a PRIMARY KEY constraints on the “ID”
and “NAME” columns when CUSTOMERS table
already exist, use the SQL syntax:
ALTER CONTRAINTS PK_CUSTID PRIMARY KEY
(ID, NAME);
Delete Primary Key
Syntax:
ALTER TABLE CUSTOMERS DROP PRIMARY KEY;
Evaluation
1. What is the meaning of the syntax
SQL> ALTER CONTRAINTS PK_CUSTID
PRIMARY KEY (ID, NAME);
Assignment
Explain the commonly used constraints in SQL.