dbms lab 7 updated
dbms lab 7 updated
Objectives
SQL Constraints are rules used to limit the type of data that can go into a table, to
maintain the accuracy and integrity of the data inside table. Constraints can be divided
into the following two types,
Constraints are used to make sure that the integrity of data is maintained in the database.
Following are the most used constraints that can be applied to a table.
NOT NULL
UNIQUE
PRIMARY KEY
FOREIGN KEY
1
CSC-252: Database Management System Lab 08: To Work with SQL Constraints
Department of Computer Science
CHECK
AUTO_INCREMENT
DEFAULT
PRIMARY KEY: Defines a column (or combination of columns) that uniquely identifies
each row in a table.
FOREIGN KEY: Establishes a link between data in two tables, enforcing referential
integrity.
CHECK: Specifies a condition that must be met for the data to be valid.
NOT NULL constraint restricts a column from having a NULL value. Once NOT NULL
constraint is applied to a column, you cannot pass a null value to that column. It enforces a
column to contain a proper value.
One important point to note about this constraint is that it cannot be defined at table level.
Example:
CSC-252: Database Management System Lab 08: To Work with SQL Constraints
2
Department of Computer Science
);
Example to check:
UNIQUE Constraint
UNIQUE constraint ensures that a field or column will only have unique values. A UNIQUE
constraint field will not have duplicate data. This constraint can be applied at column level or
table level.
Example:
FirstName VARCHAR(50),
CSC-252: Database Management System Lab 08: To Work with SQL Constraints
3
Department of Computer Science
LastName VARCHAR(50)
);
The above query will declare that the StudentID field of Student table will only have unique
values.
Example to check:
The above query specifies that s_id field of Student table will only have unique value. You
cannot add this constraint to column that already have duplicate values.
CSC-252: Database Management System Lab 08: To Work with SQL Constraints
4
Department of Computer Science
Primary key constraint uniquely identifies each record in a database. A Primary Key must
contain unique value and it must not contain null value. Usually, Primary Key is used to index
the data inside the table.
Example:
CustomerID INT,
OrderDate DATE
);
Example to check:
INSERT INTO Orders (OrderID, CustomerID, OrderDate) VALUES (1, 1001, '2022-04-01');
INSERT INTO Orders (OrderID, CustomerID, OrderDate) VALUES (1, 1002, '2022-04-02'); --
This should fail due to duplicate PRIMARY KEY constraint on OrderID
CSC-252: Database Management System Lab 08: To Work with SQL Constraints
5
Department of Computer Science
OrderDate DATE,
);
FOREIGN KEY is used to relate two tables. FOREIGN KEY constraint is also used to restrict
actions that would destroy links between tables. To understand FOREIGN KEY, let's see its
use, with help of the below tables:
Customer_Detail Table
Order Table
CSC-252: Database Management System Lab 08: To Work with SQL Constraints
6
Department of Computer Science
10 ProductID 10
11 Mobile 103
12 Order3 102
In Customer_Detail table, cid is the primary key which is set as foreign key in Order table.
The value that is entered in cid which is set as foreign key in Order table must be present in
Customer_Detail table where it is set as primary key. This prevents invalid data to be
inserted into cid column of Order table.
If you try to insert any incorrect data, DBMS will return error and will not allow you to insert
the data.
Example:
FirstName VARCHAR(50),
LastName VARCHAR(50)
);
CSC-252: Database Management System Lab 08: To Work with SQL Constraints
7
Department of Computer Science
CustomerID INT,
);
Example to check:
To create composite foreign key, you must create a composite primary key column using
CSC-252: Database Management System Lab 08: To Work with SQL Constraints
8
Department of Computer Science
ord_no INT,
book_id VARCHAR(10),
order_date DATE,
);
-- Create tables
CommonAttribute VARCHAR(50),
-- Other attributes
);
CSC-252: Database Management System Lab 08: To Work with SQL Constraints
9
Department of Computer Science
CommonAttribute VARCHAR(50),
-- Other attributes
);
CommonAttribute VARCHAR(50),
-- Other attributes
);
To show FK:
When two tables are connected with Foreign key, and certain data in the main table is
deleted/updated, for which a record exists in the child table, then we must have some
mechanism to save the integrity of data in the child table.
MySQL allows creating a table with CASCADE, SET NULL and RESTRICT options.
CASCADE: When a row in the parent table (containing the primary key) is deleted or updated,
the corresponding rows in the child table (containing foreign keys referencing the primary
key) are also automatically deleted or updated, respectively.
CSC-252: Database Management System Lab 08: To Work with SQL Constraints
10
Department of Computer Science
SET NULL: When a row in the parent table is deleted or updated, the foreign key columns in
the child table are set to NULL. This is useful when you want to disassociate the child records
from the parent records without deleting them.
RESTRICT: This option prevents the deletion or modification of rows in the parent table if
there are matching rows in the child table. It acts as a constraint to enforce referential
integrity and prevents operations that would result in orphaned records in the child table.
CASCADE option:
FirstName VARCHAR(50),
LastName VARCHAR(50)
);
TeacherID INT,
DetailInfo VARCHAR(255),
);
CSC-252: Database Management System Lab 08: To Work with SQL Constraints
11
Department of Computer Science
INSERT INTO Teachers (TeacherID, FirstName, LastName) VALUES (1, 'Ahmed', 'Khan');
INSERT INTO TeacherDetails (DetailID, TeacherID, DetailInfo) VALUES (101, 1, 'Detail info
for Ahmed Khan');
RESTRICT option:
FirstName VARCHAR(50),
LastName VARCHAR(50)
CSC-252: Database Management System Lab 08: To Work with SQL Constraints
12
Department of Computer Science
);
LecturerID INT,
DetailInfo VARCHAR(255),
);
INSERT INTO Lecturers (LecturerID, FirstName, LastName) VALUES (2, 'Fatima', 'Hussain');
INSERT INTO LecturerDetails (DetailID, LecturerID, DetailInfo) VALUES (102, 2, 'Detail info
for Fatima Hussain');
DELETE FROM Lecturers WHERE LecturerID = 2; -- This should fail due to RESTRICT option
SELECT * FROM LecturerDetails; -- This should still return the related record
CSC-252: Database Management System Lab 08: To Work with SQL Constraints
13
Department of Computer Science
UPDATE Lecturers SET LastName = 'Hussain' WHERE LecturerID = 2; -- This should fail due to
RESTRICT option
SELECT * FROM LecturerDetails; -- This should still return the related record
CHECK Constraint
CHECK constraint is used to restrict the value of a column between a range. It performs check
on the values, before storing them into the database. It’s like condition checking before saving
data into a column.
-- Create a table with a CHECK constraint to ensure that age is greater than or equal to 18
FirstName VARCHAR(50),
LastName VARCHAR(50),
Age INT,
);
INSERT INTO Students (StudentID, FirstName, LastName, Age) VALUES (1, 'Ali', 'Khan', 20); --
Valid
CSC-252: Database Management System Lab 08: To Work with SQL Constraints
14
Department of Computer Science
INSERT INTO Students (StudentID, FirstName, LastName, Age) VALUES (2, 'Sana', 'Ahmed',
16); -- Invalid, will fail due to CHECK constraint
Example:
-- Create a table with a CHECK constraint to ensure that salary is greater than 0
FirstName VARCHAR(50),
LastName VARCHAR(50),
);
INSERT INTO Employees (EmployeeID, FirstName, LastName, Salary) VALUES (1, 'Ahmed',
'Ali', 50000.00); -- Valid
INSERT INTO Employees (EmployeeID, FirstName, LastName, Salary) VALUES (2, 'Fatima',
'Khan', -1000.00); -- Invalid, will fail due to CHECK constraint
CSC-252: Database Management System Lab 08: To Work with SQL Constraints
15
Department of Computer Science
MySQL CHECK CONSTRAINT can be applied to a column of a table, to set a limit for storing
values within a range, along with IN operator.
name VARCHAR(30),
phone INT(15),
);
You can use CHECK CONSTRAINT with LIKE, OR & AND operator and also with CASE
statement.
AUTO_INCREMENT Constraint
MySQL allows you to set AUTO_INCREMENT to a column. Doing so will increase the value of
that column by 1 automatically, each time a new record is added.
Example:
ProductName VARCHAR(255),
Price DECIMAL(10, 2)
);
Example to check:
CSC-252: Database Management System Lab 08: To Work with SQL Constraints
16
Department of Computer Science
Example:
The above command will modify the id column of the customer table, to an auto increment.
DEFAULT Constraint
Title VARCHAR(100),
Author VARCHAR(100),
);
INSERT INTO Books (Title, Author) VALUES ('To Kill a Mockingbird', 'Harper Lee'); -- Genre
will default to 'Fiction'
INSERT INTO Books (Title, Author, Genre) VALUES ('1984', 'George Orwell', 'Dystopian'); --
Explicit genre value provided
INSERT INTO Books (Title, Author) VALUES ('Pride and Prejudice', 'Jane Austen'); -- Genre
will default to 'Fiction'.
Exercises (Class)
Exercises (Weekly)
CSC-252: Database Management System Lab 08: To Work with SQL Constraints
17
Department of Computer Science
DEPTNO.
EMPNO number, ENAME varchar(10),SAL number, DEPTNO number. Apply FOREIGN KEY
constraint on DEPTNO referencing the DEPARTMENT table created in question 1 and
PRIMARY KEY constraint on EMPNO and DEPTNO.
3. ALTER table EMPLOYEE created in question 2 and apply the constraint CHECK on
ENAME attribute such that ENAME should always be inserted in capital letters.
4. ALTER table DEPARTMENT created in question 1 and apply constraint on DNAME such
that DNAME should not be entered empty.
5. ALTER table EMPLOYEE created in question 2 and apply the constraint on SAL attribute
such that no two salaries of the employees should be similar.
6. ALTER table EMPLOYEE created in question 2 and apply the constraint on DEPTNO
attribute such that on update, update a child value and on delete set null value to a child.
CSC-252: Database Management System Lab 08: To Work with SQL Constraints
18