Lab 3 (DBMS)
Lab 3 (DBMS)
SQL constraints
Objective: To be familiar with constraints in SQL
Theory:
SQL constraints are used to specify rules for the data in a table.
Constraints are used to limit the type of data that can go into a table.
This ensures the accuracy and reliability of the data in the table. If there is any violation
between the constraint and the data action, the action is aborted.
The following constraints are commonly used in SQL:
NOT NULL - Ensures that a column cannot have a NULL value
UNIQUE - Ensures that all values in a column are different
PRIMARY KEY - A combination of a NOT NULL and UNIQUE. Uniquely identifies each row in a
table
FOREIGN KEY - Prevents actions that would destroy links between tables
CHECK - Ensures that the values in a column satisfies a specific condition
DEFAULT - Sets a default value for a column if no value is specified
NOT NULL
By default, a column can hold NULL values.
The NOT NULL constraint enforces a column to NOT accept NULL values.
This enforces a field to always contain a value, which means that you cannot insert a
new record without adding a value to this field.
UNIQUE
The UNIQUE constraint ensures that all values in a column are different.
PRIMARY KEY
The PRIMARY KEY constraint uniquely identifies each record in a table.
Primary keys must contain UNIQUE values, and cannot contain NULL values.
Example
CREATE TABLE Colleges (
college_id INT,
college_code VARCHAR(20) ,
college_name VARCHAR(50),
CONSTRAINT CollegePK PRIMARY KEY (college_id)
);
//Create Colleges table with primary key college_id
Add the PRIMARY KEY constraint to a column in an existing table
Example
DEFAULT
the DEFAULT constraint is used to set a default value if we try to insert an empty value
into a column.
However if the user provides value then the particular value will be stored.
FOREIGN KEY
The FOREIGN KEY constraint in SQL establishes a relationship between two tables by linking
columns in one table to those in another.
Here, the customer_id field in the Orders table is a FOREIGN KEY that references the
customer_id field in the Customers table.
This means that the value of the customer_id (of the Orders table) must be a value from
the customer_id column (of the Customers table).
use customer_db;
2) create a table named customers with following columns adding constraints following
constraints
Customer_id: Primary key
Name: not null
And order_id is primary key and customer_id as foreign key for customer
Try to insert customer_id in orders table that does not exist in customers table
insert into orders values(6,'drone',120000,6);
This cannot be inserted