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

DBMS Lab 18 SQL Constraints Combine

Constraints are rules that ensure data integrity and consistency in a database. There are two main types of constraints: data definition language (DDL) constraints and data manipulation language (DML) constraints. DDL constraints include NOT NULL, UNIQUE, PRIMARY KEY, and FOREIGN KEY constraints and are defined when creating tables. NOT NULL ensures columns do not contain NULL values, UNIQUE prevents duplicate values, PRIMARY KEY uniquely identifies rows and prevents NULL/duplicates, and FOREIGN KEY links data between tables.

Uploaded by

Muhammad Aamer
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)
69 views

DBMS Lab 18 SQL Constraints Combine

Constraints are rules that ensure data integrity and consistency in a database. There are two main types of constraints: data definition language (DDL) constraints and data manipulation language (DML) constraints. DDL constraints include NOT NULL, UNIQUE, PRIMARY KEY, and FOREIGN KEY constraints and are defined when creating tables. NOT NULL ensures columns do not contain NULL values, UNIQUE prevents duplicate values, PRIMARY KEY uniquely identifies rows and prevents NULL/duplicates, and FOREIGN KEY links data between tables.

Uploaded by

Muhammad Aamer
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/ 8

Database Management System LAB # 18 Department of Technology

The University of Lahore

LAB No. 18

SQL CONSTRAINTS
(Data Definition Language Constraints)
SQL Constraints
➢ Constraints are rules that are defined within a relational database to ensure the data
integrity and consistency of the data stored in the database.
➢ They act as limitations or restrictions on the data that can be entered, modified, or
deleted in a table.
➢ Constraints play a crucial role in maintaining the accuracy and reliability of the data
within a database system.

Types of Constraints in SQL


There are two main categories of constraints in SQL:

Data Definition Language (DDL) Constraints:


These constraints are defined during the creation of a table using the CREATE TABLE
statement. They specify rules that apply to the structure and organization of the data within the
table.

1) NOT NULL
2) UNIQUE
3) PRIMARY KEY
4) FOREIGN KEY

NOT NULL:
Definition:
The NOT NULL constraint is used to ensure that a column in a relational database table cannot
contain any NULL (missing or undefined) values.

Usage:
When defining a column in a table, you can add the NOT NULL constraint to specify that
values in that column must be provided during insertion, and they cannot be left blank.

CREATE TABLE example (column1 INT NOT NULL, column2 VARCHAR (50));

Error Handling:
If an attempt is made to insert a row without providing a value for a NOT NULL column, or if
an update sets the column to NULL, the database will generate an error.
Database Management System LAB # 18 Department of Technology
The University of Lahore
-- Attempt to insert a row without a value for column1 (will result in an error)
INSERT INTO example (column2) VALUES ('Value');

Adding NOT NULL to Existing Column:


You can use the ALTER TABLE statement to add the NOT NULL constraint to an existing
column.

ALTER TABLE example


MODIFY COLUMN column2 VARCHAR (50) NOT NULL;
Multiple NOT NULL Columns:
You can apply the NOT NULL constraint to multiple columns in a table to enforce non-null
values for those columns.

CREATE TABLE users (user_id INT, username VARCHAR (50) NOT NULL,
email VARCHAR (100) NOT NULL);
Dropping NOT NULL Constraints:
Dropping the NOT NULL constraint from a column involves using the ALTER TABLE
statement. Here's the basic syntax to drop the NOT NULL constraint:

ALTER TABLE one1


MODIFY COLUMN name varchar (10) NULL;
Replace table_name with the name of your table and column_name with the name of the
column from which you want to remove the NOT NULL constraint.
UNIQUE:
Definition:
A unique key constraint in SQL ensures that values in a specified column or set of columns are
unique across all rows in a table. Unlike a primary key, a unique key can contain NULL values.

Syntax:
The unique key constraint is specified when creating a table or altering an existing table.
-- Creating a table with a unique key constraint
CREATE TABLE example (id INT, email VARCHAR (100) UNIQUE,
name VARCHAR (50));
Single and Composite Unique Keys:
A unique key can be applied to a single column or a combination of columns.
-- Single-column unique key
CREATE TABLE example (id INT, username VARCHAR (50) UNIQUE, age INT);
Database Management System LAB # 18 Department of Technology
The University of Lahore
-- Composite unique key
CREATE TABLE example (id INT PRIMARY KEY, email VARCHAR (100),
phone_number VARCHAR (15), UNIQUE (email, phone_number));
Handling NULL Values:
By default, unique constraints allow multiple NULL values in the column(s). This means that
NULL is not considered a duplicate value.

Violating Unique Constraint:


Attempting to insert or update data that violates a unique constraint result in an error.

-- Attempting to insert a duplicate email (will result in an error)


INSERT INTO example (id, email, name) VALUES (1, '[email protected]',
'John Doe');
Deferrable Unique Constraint:
Some database systems support deferrable unique constraints, which allow checking the
uniqueness condition at the end of a transaction rather than immediately when the data is
modified.

-- Deferrable unique constraint (PostgreSQL syntax)


CREATE TABLE example (id INT PRIMARY KEY,
email VARCHAR (100) UNIQUE DEFERRABLE INITIALLY DEFERRED,
name VARCHAR (50));
Multiple Unique Constraints:
A table can have multiple unique constraints, each on different columns.

CREATE TABLE example (id INT, email VARCHAR (100) UNIQUE,


username VARCHAR (50) UNIQUE, name VARCHAR (50));
Dropping Unique Constraint:
You can drop a unique constraint from a table using the DROP CONSTRAINT statement.

-- Dropping a unique constraint


ALTER TABLE example
DROP CONSTRAINT unique_email;
Understanding unique key constraints is essential for ensuring data integrity by preventing the
presence of duplicate values in specified columns. Whether applied to a single column or a
combination of columns, unique key constraints play a critical role in maintaining the
consistency of database records.
Database Management System LAB # 18 Department of Technology
The University of Lahore
PRIMARY KEY:
Definition:
A primary key is a constraint that uniquely identifies each record in a table. It ensures that the
values in the specified column or set of columns are unique and not null.

Syntax:
When creating a table, you define a primary key using the PRIMARY KEY constraint.

CREATE TABLE example (id INT PRIMARY KEY, name VARCHAR (50));

Single Column Primary Key:


A primary key can be a single column.

CREATE TABLE example (user_id INT PRIMARY KEY,


username VARCHAR (50));
Composite Primary Key:
A primary key can consist of multiple columns.

CREATE TABLE example (order_id INT, product_id INT,


PRIMARY KEY (order_id, product_id));
Auto-incrementing Primary Key:
The AUTO_INCREMENT attribute (or equivalent, depending on the database system) can be
used to automatically generate unique values for the primary key.

CREATE TABLE example (id INT PRIMARY KEY AUTO_INCREMENT,


name VARCHAR (50));
Handling NULL Values:
A primary key column cannot contain NULL values.

CREATE TABLE example (id INT PRIMARY KEY,


name VARCHAR (50) NOT NULL);
Violating Primary Key Constraint:
Attempting to insert or update data that violates a primary key constraint result in an error.

-- Attempting to insert a duplicate id (will result in an error)


INSERT INTO example (id, name) VALUES (1, 'John Doe');
Database Management System LAB # 18 Department of Technology
The University of Lahore
Deferrable Primary Key Constraint:
Some database systems support deferrable primary key constraints, allowing checking the
uniqueness condition at the end of a transaction rather than immediately when the data is
modified.

CREATE TABLE example (


id INT PRIMARY KEY DEFERRABLE INITIALLY DEFERRED,
name VARCHAR (50));
Adding Primary Key to Existing Table:
You can use the ALTER TABLE statement to add a primary key constraint to an existing table.

ALTER TABLE example


ADD PRIMARY KEY (id);
Dropping Primary Key Constraint:
You can use the ALTER TABLE statement to drop a primary key constraint from a table.

ALTER TABLE example


DROP PRIMARY KEY;
Naming Primary Key Constraints:
You can explicitly name a primary key constraint for easier reference.

CREATE TABLE example (id INT, name VARCHAR (50),


CONSTRAINT pk_example_id PRIMARY KEY (id)

Understanding primary key constraints is fundamental in relational database design. Primary


keys uniquely identify records and facilitate the creation of relationships between tables. They
ensure data integrity and play a crucial role in maintaining a consistent and reliable database
structure.

FOREIGN KEY:
Definition:
A foreign key is a constraint that establishes a link between two tables in a relational database.
It ensures that values in a column (or a set of columns) of one table match the values in the
primary key column(s) of another table.

Syntax:
When creating a table, you define a foreign key using the FOREIGN KEY constraint.

CREATE TABLE orders (order_id INT PRIMARY KEY, customer_id INT,


FOREIGN KEY (customer_id) REFERENCES customers(customer_id));
Database Management System LAB # 18 Department of Technology
The University of Lahore
Referencing Primary Key:
The foreign key column in one table typically references the primary key column of another
table.

Single and Composite Foreign Keys:


A foreign key can consist of a single column or multiple columns.

-- Single-column foreign key


CREATE TABLE orders (order_id INT PRIMARY KEY, customer_id INT,
FOREIGN KEY (customer_id) REFERENCES customers(customer_id));
-- Composite foreign key
CREATE TABLE order_items (order_id INT, product_id INT,
PRIMARY KEY (order_id, product_id),
FOREIGN KEY (order_id) REFERENCES orders(order_id),
FOREIGN KEY (product_id) REFERENCES products(product_id));
ON DELETE and ON UPDATE Actions:
You can specify actions to be taken when a referenced row is deleted or updated. Common
options include CASCADE, SET NULL, SET DEFAULT, and RESTRICT.

CREATE TABLE orders (order_id INT PRIMARY KEY, customer_id INT,


FOREIGN KEY (customer_id) REFERENCES customers(customer_id)
ON DELETE CASCADE);
Deferrable Foreign Key Constraint:
Some database systems support deferrable foreign key constraints, allowing checking the
referential integrity condition at the end of a transaction rather than immediately when the data
is modified.

CREATE TABLE orders (order_id INT PRIMARY KEY, customer_id INT,


FOREIGN KEY (customer_id) REFERENCES customers(customer_id)
DEFERRABLE INITIALLY DEFERRED);
Self-Referencing Foreign Key:
A table can have a foreign key that references its own primary key, creating a self-referencing
relationship.
CREATE TABLE employees (employee_id INT PRIMARY KEY, manager_id INT,
FOREIGN KEY (manager_id) REFERENCES employees(employee_id));
Database Management System LAB # 18 Department of Technology
The University of Lahore
Understanding foreign key constraints is crucial for establishing relationships between tables
and ensuring referential integrity within a relational database. They play a key role in
maintaining consistency and preventing orphaned or inconsistent data.
Practice Questions
Create a Table:
1) Create a table named employees with columns employee_id (integer) and
employee_name (varchar) where employee_name cannot be NULL.

Insert Records:
2) Insert three records into the employees table, ensuring that each record has a value for
employee_id and employee_name.

Update Records:
3) Update the employees table to set the employee_name to 'Unknown' where the
employee_name is currently NULL.

Add NOT NULL Constraint:


4) Alter the employees table to add a NOT NULL constraint on the employee_id column.

Conditional Insert:
5) Create a table named students with columns student_id and student_name. Add a NOT
NULL constraint on student_id and allow student_name to be NULL. Insert a record
with a value for student_id but without providing a value for student_name and write
your reviews.

Multiple Constraints:
6) Create a table named inventory with columns product_id, product_name, and quantity.
Add a NOT NULL constraint on both product_id and product_name. Insert a record
with a value for product_id but without providing a value for product_name and write
your review.

Create a Table with a Unique Constraint:


7) Create a table named employees with columns employee_id (integer) and email
(varchar). Add a UNIQUE constraint on the email column.

Insert Records:
8) Insert three records into the employees table, ensuring that each record has a unique
email value.
Database Management System LAB # 18 Department of Technology
The University of Lahore
Update Unique Value:
9) Update the email of the employee with employee_id 1 to a new unique value.

Attempt to Insert Duplicate Value:


10) Try to insert a record with an email value that already exists in the employee’s table.
Observe the error message.

Composite Unique Constraint:


11) Modify the employees table to include a composite unique constraint on columns
department and position

Defer Unique Constraint Check:


12) Create a table named orders with columns order_id and customer_id. Add a UNIQUE
constraint on customer_id with deferred checking.

Alter Table to Add Unique Constraint:


13) Add a unique constraint on the phone_number column of the existing table contacts

Drop Unique Constraint:


14) Remove the unique constraint on the email column in the employee’s table.

You might also like