0% found this document useful (0 votes)
6 views11 pages

Assignment 3

Constraints in MySQL define rules for data integrity in tables, including NOT NULL, UNIQUE, PRIMARY KEY, FOREIGN KEY, and DEFAULT constraints. The NOT NULL constraint ensures a column must have a value, UNIQUE ensures all values are distinct, PRIMARY KEY uniquely identifies records, FOREIGN KEY maintains relationships between tables, and DEFAULT assigns a default value when none is provided. These constraints help maintain the reliability and accuracy of data in a database.

Uploaded by

macos47119
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as ODT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views11 pages

Assignment 3

Constraints in MySQL define rules for data integrity in tables, including NOT NULL, UNIQUE, PRIMARY KEY, FOREIGN KEY, and DEFAULT constraints. The NOT NULL constraint ensures a column must have a value, UNIQUE ensures all values are distinct, PRIMARY KEY uniquely identifies records, FOREIGN KEY maintains relationships between tables, and DEFAULT assigns a default value when none is provided. These constraints help maintain the reliability and accuracy of data in a database.

Uploaded by

macos47119
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as ODT, PDF, TXT or read online on Scribd

What are Constraints in MySQL?

Constraints in MySQL is used to define rules for what values can be stored in rows and
columns in a table. It is used to limit the data that can be inserted into a table. The action is
canceled if there is a conflict between the constraint and the data action. This also helps in
maintaining the reliability and accuracy of the data.

NOT NULL Constraint in MySQL

NOT NULL is a constraint in MySQL that ensures a column must always have a value and
cannot store NULL (empty) values.
In simple words: the field is mandatory.

column_name datatype NOT NULL;

In the above syntax, it can be seen that NOT NULL is used after the column name and data
type of that column in the column definition.

For example -

Let's create a table named students.

CREATE TABLE students(


reg_no INT NOT NULL,
name VARCHAR(255) NOT NULL,
admission_date DATE
);

The above statements after execution create a table named students.

In the table students, there are three columns reg_no, name, and admission_date. For reg_no
and name, it is defined that none of the values in that column can be NULL but the
admission_date column is not defined with NOT NULL constraint, so it can contain NULL
values.

It is considered good practice to add the NOT NULL constraint to every column in a table.
We can also add the NOT NULL constraint to an existing column. NOT NULL Constraint
in MySQL

NOT NULL is a constraint in MySQL that ensures a column must always have a value and
cannot store NULL (empty) values.
In simple words: the field is mandatory.

column_name datatype NOT NULL;

In the above syntax, it can be seen that NOT NULL is used after the column name and data
type of that column in the column definition.

For example -NOT NULL Constraint in MySQLNOT NULL Constraint in MySQL


Column Name Data Type Constraint Meaning

reg_no INT NOT NULL Student registration number

name VARCHAR(255) NOT NULL Student name

admission_date DATE Optional Date of admission

UNIQUE Constraint
Ensures that all values in a column (or a combination of columns) are different. A table can
have multiple UNIQUE constraints.

 During Table Creation:

sql

CREATE TABLE Products (


ProductID int NOT NULL UNIQUE,
ProductName varchar(255),
ProductCode varchar(50),
CONSTRAINT UC_ProductCode UNIQUE (ProductCode)
);

Column Name Data Type Constraint Meaning

Must have a value and cannot be


ProductID INT NOT NULL, UNIQUE
duplicate

Product name (can be NULL or


ProductName VARCHAR(255) None
duplicate)

ProductCode VARCHAR(50) UNIQUE Product code must be unique

-- Or for multiple columns:


CREATE TABLE Suppliers (
SupplierID int NOT NULL,
Name varchar(255),
Address varchar(255),
CONSTRAINT uc_name_address UNIQUE (Name, Address)
);

Column Name Data Type Constraint Meaning

SupplierID INT NOT NULL Supplier ID must have a value

Name VARCHAR(255) Part of UNIQUE Supplier name


Column Name Data Type Constraint Meaning

Address VARCHAR(255) Part of UNIQUE Supplier address

The PRIMARY KEY constraint in MySQL

The PRIMARY KEY constraint is used to uniquely identify each record in a table and does
not allow NULL or duplicate values.

 The primary key can't contain NULL values.


 If we try to insert NULL value to a primary key column, it will cause an error.
 A primary key must contain unique values. For a set of columns, the combination of
columns must be unique.

Primary Key definition in CREATE TABLE

The primary key can be defined while creating a table in a CREATE TABLE statement.

Syntax:

Single column as primary key

CREATE TABLE table_name(


column_name datatype PRIMARY KEY
);

A set of columns as primary key

CREATE TABLE table_name(


column_name datatype,
.....,
PRIMARY KEY (column_list)
);

For example - Let's make reg_no the primary key of the students table given above.

CREATE TABLE students(


reg_no INT PRIMARY KEY
);

Add primary key constraints using ALTER TABLE

We can add a primary key to an existing table using ALTER TABLE statement.

Syntax:

ALTER TABLE table_name


ADD PRIMARY KEY(column_list);
For example –Implementing primary key

ALTER TABLE students


ADD PRIMARY KEY(reg_no, name);
CREATE TABLE Students (
StudentID int NOT NULL,
LastName varchar(255),
FirstName varchar(255),
CONSTRAINT PK_Student PRIMARY KEY (StudentID)
);

Column Name Data Type Constraint Meaning

StudentID INT PRIMARY KEY Unique student ID

LastName VARCHAR(255) None Student last name

FirstName VARCHAR(255) None Student first name

-- The constraint can also be defined at the column level:


CREATE TABLE Persons (
ID int NOT NULL PRIMARY KEY,
Name varchar(45)
);

Column Name Data Type Constraint Meaning

ID INT PRIMARY KEY Unique person ID

Name VARCHAR(45) None Person name

-- Or for a composite primary key:


CREATE TABLE Enrollments (
StudentID int NOT NULL,
CourseID int NOT NULL,
CONSTRAINT PK_Enrollment PRIMARY KEY (StudentID, CourseID)
);

Column Name Data Type Constraint Meaning

StudentID INT Part of PRIMARY KEY Student ID

CourseID INT Part of PRIMARY KEY Course ID

(StudentID, CourseID) — PRIMARY KEY Unique student-course combination

The FOREIGN KEY constraint in MySQL

FOREIGN KEY is a constraint used to establish a relationship between two tables and
maintain referential integrity by referencing the primary key of another table.
A table can have one or more foreign keys and each foreign key references the primary key
of other different parent tables.

Sometimes, the parent table and child table can be the same when the foreign key references
the primary key of the same table.

The syntax of the foreign key constraint used with CREATE TABLE or ALTER TABLE is
shown below.

[CONSTRAINT constraint_name]
FOREIGN KEY [foreign_key_name] (column_list)
REFERENCES parent_table(column_list)
[ON DELETE reference_option]
[ON UPDATE reference_option]

In the above syntax:

 First, specify the name of the foreign key constraint that we want to create after the
CONSTRAINT keyword, it is optional if we omit this MySQL automatically
generates a name for this.
 Then, column_list is specified after the FOREIGN KEY keyword and the
foreign_key_name is optional.
 Then, the parent table and the list of columns of the parent table are specified after the
REFERENCES keyword.
 Then, the reference option is specified after the ON DELETE and ON UPDATE
clause to maintain the referential integrity between the child and parent tables.

These are the reference options in MySQL.

1. RESTRICT - It restricts the deletion of the rows from the parent table having
matching rows in the child table.
2. CASCADE - It updates/deletes the values of the matching rows in the child table if a
row in the parent table is updated/deleted.
3. SET NULL - It set the value of the foreign key to NULL if the matching row in the
parent table is deleted.
4. NO ACTION - It is the same as the RESTRICT.

If the ON DELETE and ON UPDATE clause is not specified, the default action is
RESTRICT.

Example of foreign key -

Let's create a table named result as shown below.

CREATE TABLE result(


roll_no INT,
reg_no INT,
marks INT
FOREIGN KEY (reg_no)
REFERENCES students(reg_no)
);
Column Name Data Type Constraint Meaning

roll_no INT None Roll number of student

reg_no INT FOREIGN KEY Refers to students.reg_no

marks INT None Student marks

In the above

example, the students table is the parent table and the result is the child table. The reg_no in
the result table is the foreign key column referencing the reg_no column in the students table.

DROP foreign key constraints in MySQL

We can drop the foreign key constraint using the ALTER TABLE statement. The syntax for
this is shown below.

ALTER TABLE table_name


DROP FOREIGN KEY constraint_name;

In the above syntax:

 The table_name is the name of the table from which we are dropping the foreign key
constraint.
 The constraint name is then specified after the DROP FOREIGN KEY keywords.

Students Table (Parent)

reg_no
Name
(PK)

101 Rahul

102 Amit

Result Table (Child)


roll_no reg_no (FK) marks

1 101 85

2 102 90

After Dropping FOREIGN KEY

roll_no reg_no marks

1 105 85

 Now reg_no can store invalid values because the foreign key constraint is removed.

UNIQUE constraint in MySQL

The UNIQUE constraint is used in MySQL to ensure uniqueness in the values of a column or
set of columns in a table. When a duplicate value is inserted in a column with a unique
constraint, MySQL rejects that insertion and issues an error.

Add UNIQUE KEY in CREATE TABLE statement

The unique key can be defined while creating a table using CREATE TABLE statement. The
syntax for this is shown below.

Syntax:

Add the UNIQUE constraint to a single column

CREATE TABLE table_name(


column_name data_type UNIQUE
);

In the above syntax, the unique keyword is added after the column definition of the column in
which it is added.

Add the UNIQUE constraint to a set of columns

CREATE TABLE table_name(


column_name1 data_type,
column_name2 data_type,
UNIQUE (column_list)
);
Column Name Data Type Constraint Meaning

Name VARCHAR(255) None Student name

Email VARCHAR(100) Part of UNIQUE Email must be unique with phone

Phone VARCHAR(15) Part of UNIQUE Phone must be unique with email

In the above syntax, the UNIQUE keyword with the list of columns is added at the end.

For example -

CREATE TABLE students(


reg_no INT NOT NULL,
name VARCHAR(255) NOT NULL,
admission_date DATE,
UNIQUE (reg_no, name)
);

Column Name Data Type Constraint Meaning

reg_no INT NOT NULL Registration number is mandatory

name VARCHAR(255) NOT NULL Student name is mandatory

admission_date DATE None Admission date (can be NULL)

Combination of reg_no and name must be


(reg_no, name) — UNIQUE
unique

Add the UNIQUE constraint to an existing table

The syntax for adding the UNIQUE constraint to an existing table is shown below.

ALTER TABLE table_name


ADD CONSTRAINT constraint_name
UNIQUE (column_list);

Drop UNIQUE constraint from a column in a table

The UNIQUE constraint can be dropped from a column of a table using the following syntax.

ALTER TABLE table_name


DROP INDEX index_name;

or

DROP index_name ON table_name;

DEFAULT constraint in MySQL


The DEFAULT constraint in MySQL is used to assign a default value to a column when no
value is specified during data insertion.

The syntax for this is shown below.

Syntax:

column_name data_type DEFAULT default_value;

In the above syntax:

 default_value is specified after the DEFAULT keyword in the column definition.


 The default value must be a literal constant like a number or a string.

Set DEFAULT constraint in CREATE TABLE statement

The DEFAULT constraint can be set while creating a table. For example:

CREATE TABLE result


(

reg_no INT,

name VARCHAR(255),

marks INT DEFAULT 0


);

Column Name Data Type Constraint Meaning

reg_no INT None Student registration number

name VARCHAR(255) None Student name

marks INT DEFAULT 0 If marks are not given, it will be 0 automatically

Add DEFAULT constraint to an existing table

We can add DEFAULT constraint to an existing table also using the following syntax.

ALTER TABLE table_name


ALTER COLUMN column_name SET DEFAULT default_value;

Remove DEFAULT constraint from a column

To remove the DEFAULT constraint from a column in a table, we use the following syntax.

ALTER TABLE table_name


ALTER column_name DROP DEFAULT;

In the above syntax, the DROP DEFAULT keyword is used after the column_name from
which the DEFAULT constraint is being dropped.
For example -

ALTER TABLE result


ALTER marks DROP DEFAULT;

In the above example, the above statement will drop the DEFAULT constraint from the
marks column in the result table.

Example: Student Management System

Parent Table (for FOREIGN KEY)


CREATE TABLE Courses (
CourseID INT PRIMARY KEY,
CourseName VARCHAR(100) NOT NULL
);

Column Name Data Type Constraint Meaning

Unique ID for each course, cannot be


CourseID INT PRIMARY KEY
duplicate or NULL

CourseName VARCHAR(100) NOT NULL Course name is mandatory

Main Table with ALL Constraints


CREATE TABLE Students (
StudentID INT AUTO_INCREMENT PRIMARY KEY, -- PRIMARY KEY
RegNo INT NOT NULL UNIQUE, -- NOT NULL + UNIQUE
Name VARCHAR(100) NOT NULL, -- NOT NULL
Age INT CHECK (Age >= 18), -- CHECK constraint
AdmissionDate DATE DEFAULT CURRENT_DATE, -- DEFAULT
CourseID INT, -- FOREIGN KEY column

FOREIGN KEY (CourseID) REFERENCES Courses(CourseID) -- FOREIGN KEY


);

Column Name Data Type Constraints Applied Meaning

PRIMARY KEY, Unique student ID generated


StudentID INT
AUTO_INCREMENT automatically

Registration number must be


RegNo INT NOT NULL, UNIQUE
unique and cannot be empty

Name VARCHAR(100) NOT NULL Student name is mandatory

Age INT CHECK (Age ≥ 18) Age must be 18 or above

DEFAULT Automatically stores today’s date if


AdmissionDate DATE
CURRENT_DATE not given
Column Name Data Type Constraints Applied Meaning

CourseID INT FOREIGN KEY Links student to Courses table

Example :

StudentID RegNo Name Age AdmissionDate CourseID

1 201 Rahul 20 2026-02-13 101

2 202 Priya 19 2026-02-13 102

You might also like