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

MySQL Unit-4 Constraints

Uploaded by

Queen Style
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views

MySQL Unit-4 Constraints

Uploaded by

Queen Style
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 8

ECS-II|MySQLUnit-4

MySQL constraints
 Applying data constraints- column level and table level
 Types of Data constraints- I/O constraints, Business rule constraints
 NOT NULL constraint, UNIQUE constraint, CHECK constraint
 Primary key and Foreign key constraint
 Disable foreign key checks
 Adding, Modify and drop constraints using alter table command
------------------------------------------------------------------------------------------------------------------------
MySQL constraint is used to specify the rule that allows or restricts what values/data will be stored
in the table. They provide a suitable method to ensure data accuracy and integrity inside the table. It
also helps to limit the type of data that will be inserted inside the table. If any interruption occurs
between the constraint and data action, the action is failed.
 Constraints are the rules. These can be specified at the time of table creation or can be added after
table creations by using alter table statement.
 Constraints prevent the table from deletion, if there is any dependency
 Applying data constraints
Constraints can be divided into following two types:
1) The constraints can be specified immediately after the column definition is called column-level
definition.
2) The constraints can be specified after all columns and end of table is called table-level definition.
Data Integrity:
 Entity Integrity ensures that no duplicate rows in a table. Ex: Unique, Primary Key
 Domain Integrity enforces valid entries for a given column by restricting the type, the format, or
the range of possible values. Ex: check, Null, Not Null
 Referential integrity ensures that rows cannot be deleted, which are used by other records. Ex:
Foreign Key
 User-Defined Integrity enforces some specific business rules on entity, domain, or referential
integrity customer.
Constraints are:
 Not Null Constraint: Ensures that a column have not NULL value.
 Default Constraint: Provides a default value for a column when none is specified.
 Unique Constraint: Ensures that all values in a column are different (unique).
 Primary Key: Uniquely identified each rows/records in a database table.
 Foreign Key: Uniquely identified a rows/records in any another database table.
 Check Constraint: Ensures that all values in a column must satisfy certain conditions.
Not Null Constraint
 By default, table columns are null, You should manually define NOT NULL constraint
 NOT NULL constraint enforces a column to not accept NULL values. i.e. column cannot have
NULL or empty values.
 NOT NULL constraint prevents inserting NULL values into a column.
 If you try to insert or update a NULL value in the column, then database engine will reject the
change and issue an error.
 NOT NULL constraint applied only at column level not table level.
 When a column is defined as not null, that column becomes a mandatory column. It force to
user enter data into the column.
Principles of NULL values
 NULL value is different from a blank or zero.
 NULL means unknown or missing information.
 NULL value can be inserted into the columns of any Data type.
Syntax: column_name data_type NOT NULL;
1 | SHK
ECS-II|MySQLUnit-4
Example: To create an emp_info table and enforces "Name" column to not null
create table emp_info (emp_no int(3) primary key, emp_name char(10) not null, address varchar(20));
desc emp_info;
| Field | Type | Null | Key | Default | Extra |
+----------+----------+------+-----+---------+-------+
| emp_no | int(3) | NO | PRI | NULL | |
| emp_name | char(10) | NO | | NULL | |
| address |varchar(10) | YES | | NULL | |
+----------+----------+------+-----+---------+-------+
 Add NOT NULL constraint in existing table column
Alter table emp_info modify address varchar(30) not null;
Desc emp_info;
| Field | Type | Null | Key | Default | Extra |
+----------+----------+------+-----+---------+-------+
| emp_no | int(3) | NO | PRI | NULL | |
| emp_name | char(10) | NO | | NULL | |
| address varchar(10) | NO | | NULL | |
+----------+----------+------+-----+---------+-------+
 Drop NOT NULL constraint from existing table column
Alter table emp_info modify address varchar (30) null;
Desc emp_info;
Unique Key Constraint
 A UNIQUE constraint is an integrity constraint that ensures values in a column or group of
columns to be unique.
 The UNIQUE constraint is used for uniquely identify each record in a database. It requires that
each value in a column should be unique.
 It provides uniqueness guarantee of a column or set of columns. It cannot allow duplicate
values but unique key allow NULL (blank) values.
 You can assign many unique key constraints in one table.
 UNIQUE constraint can be applied at column level and table level.
Syntax: Column-Level Table-Level
create table table_name ( create table table_name (
column_name data_type, column_name1 data_type (size),
column_name data_type UNIQUE, column_name2 data_type (size),
... ); ...,
UNIQUE (column_name1, column_name2) );
Example: To create an emp_info table and enforces "Name" column to not null
unique key at column level Unique key at table level
create table emp_info (emp_no int(3) primary key, create table emp_info (emp_no int(3) primary key,
email_id varchar(20) unique, email_id varchar(20),
mobile_no varchar(15)); mobile_no varchar(15),
unique(email_id, mobile_no) );
desc emp_info;
+-----------+--------------+------+------+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-----------+---------------+------+-----+---------+-------+
| emp_no | int(3) | NO | PRI | NULL | |
| email_id | varchar(20) | YES | UNI | NULL | | --Unique key Assigned
| mobile_no| varchar(15) | YES | | NULL | |

2 | SHK
ECS-II|MySQLUnit-4
Now we are inserting record into this table to check unique key how to work
Example: try to insert same email id fire error for unique constraint violated.
insert into emp_info values(1,'[email protected]',9874563210);
insert into emp_info values(2,'[email protected]',9870263210);
ERROR 1062 (23000): Duplicate entry '[email protected]' for key 2
 UNIQUE KEY constraint on ALTER TABLE:
 Defining a unique key constraint on single column:
alter table student add unique (PRN_no);
 Defining a unique key constraint on multiple columns:
alter table student add constraint uniqcon_student unique (email_id, mobile_no);
Primary Key Constraints:
MySQL primary key is a single or combination of the field, which is used to identify each record in
a table uniquely. MySQL automatically creates an index named "Primary" after defining a primary
key into the table. Since it has an associated index, we can say that the primary key makes the query
performance fast.
 Primary Key apply on columns for uniquely identifies each record from the table.
 Primary Key constraint column cannot accept duplicate data and NULL values.
 Each table can have only ONE primary key.
 MySQL does not allow us to insert a new row with the existing primary key.
 A primary key is assigned one or more columns in a table is called composite primary key.
 It defines a mandatory column and data through the column must be unique.
 Primary key constraint create automatic index file for identifying unique records.
 Primary key constraint can be defined at the column and table level.
 Primary key constraint combination of NOT NULL and UNIQUE Constraints
When we specify a primary key constraint for column, database engine automatically creates a
unique index file for identify unique records.
at table level (primary key for single columns) At (single) column level
CREATE TABLE table_name ( CREATE TABLE table_name(
Column1 Column _definition, Column1 data type(size) PRIMARY KEY,
Column2 Column_definition, Column2 data type (size),
... ...
PRIMARY KEY (column_name(s)) ); );
create table doctor (did int(5), create table doctor (did int (5) primary key,
dname char(20), age int(2), dname char(20),
contact_no varchar(15), age int(2), contact_no varchar(15));
primary key(sid));
 Primary key with Auto_increment attribute:
When you insert a new row into the table, the primary key column can also use
the AUTO_INCREMENT attribute to generate a sequential number for that row
automatically.
create table patient( pid int (5) auto_increment primary key,
pname char(20));
insert into stud (pname) values(‘Abhi’);
insert into stud (pname) values(‘Nayan’);
select * from patient;
 Primary key on single column:
alter table users_info add primary key (uid);
 Primary key on multiple columns:
alter table users_info add constraint pk_users_id primary key (uid, username);
 Drop Primary Key constraint

3 | SHK
ECS-II|MySQLUnit-4
alter table stud drop primary key;
alter table stud drop constraint pk_users_id ;
 Enable or Disable a Primary Key
alter table students disable constraint pk_users_id;
alter table students enable constraint pk_users_id;
Foreign Key (referential) Constraint
 A foreign key is a column or group of columns in a table that links to a column or group of
columns in another table.
 Foreign key represents relationship between one or more tables. FOREIGN KEY applies on
columns that references values in another table column.
 FOREIGN KEY constraints also known as relationship (referential) constraints.
 A foreign key is a column whose values are derived from the primary key of the other table.
 FOREIGN KEY constraint applied column must have same data type as they reference on
another table column.
Syntax: FOREIGN KEY (column_name, ...) REFERENCES parent_table (colunm_name,...)
OR
[CONSTRAINT constraint_name] FOREIGN KEY [foreign_key_name] (column_name, ...) REFERENCES
parent_table (colunm_name,...) [ON DELETE reference_option] [ON UPDATE reference_option]
 MySQL has five reference options:
MySQL fully supports three actions: RESTRICT, CASCADE and SET NULL.
 CASCADE: if a row from the parent table is deleted or updated, the values of the matching
rows in the child table automatically deleted or updated.
 SET NULL: if a row from the parent table is deleted or updated, the values of the foreign key
columns in the child table are set to NULL.
 RESTRICT: if a row from the parent table has a matching row in the child table, MySQL
rejects deleting or updating rows in the parent table. If you don’t specify the ON
DELETE and ON UPDATE clause, the default action is RESTRICT.
 NO ACTION: is the same as RESTRICT.
 SET DEFAULT: is recognized by the MySQL parser.
Create two tables Customer and bill:
create table customer (cust_id int auto_increment primary key,
cust_name char(10));
create table bill (bill_no int auto_increment primary key,
bill_amount int,
cust_id int,
foreign key (cust_id) references cust(cust_id));
mysql> desc customer;
+-----------+---------+------+-----+---------+---------------+
| Field | Type | Null |Key | Default | Extra |
+-----------+---------+------+-----+---------+---------------+
| cust_id | int(11) | NO | PRI | NULL | |
| cust_name | char(10) | YES | | NULL | |
mysql> desc bill;
+-----------+---------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-----------+---------+------+-----+---------+-------+
| bill_no | int(11) | NO | PRI | NULL | |
| bill_amount | int(11) | NO | | NULL | |
| cust_id | int(11) | YES | MUL | NULL | | --- Foreign key column

4 | SHK
ECS-II|MySQLUnit-4
The cust_id in the bill table is the foreign key column that refers to the cust_id column in the
customer table.
 Restrict Action.
1) Insert two rows into the customer table:
insert into customer (cust_name) values ('smita'), ('sanjay');
select * from customer;
2) Insert a new row into the bill table:
insert into bill (bill_amount, cust_id) values(2000,1);
It works because the cust_id 1 exists in the customer table.
3) Insert a new row into the bill table with a cust_id value does not exist in the customer table:
insert into bill (bill_amount, cust_id) values(4000,3);
MySQL issued the following error:
Error Code: 1452. Cannot add or update a child row: a foreign key constraint fails (`bcs`.`bill`, FOREIGN
KEY (`cust_id`) REFERENCES `customer` (`cust_id`) ON DELETE RESTRICT ON UPDATE RESTRICT)
4) Update the value in the cust_id column in the customer table to 100:
update customer set cust_id = 100 where cust_id = 1;
MySQL issued this error:
Error Code: 1451. Cannot delete or update a parent row: a foreign key constraint fails (`bcs`.`bill`,
CONSTRAINT FOREIGN KEY (`cust_id`) REFERENCES `customer` (`cust_id`) ON DELETE RESTRICT ON
UPDATE RESTRICT)
Because of the RESTRICT option, you cannot delete or update cust_id 1 since it is referenced by
the bill_no 1 in the bill table.
 Cascade Action: show how on update cascade and on delete cascade actions work.
1) Drop the bill table:
drop table bill;
2) Create the bill table with the on update cascade and on delete cascade options for the foreign key:
create table bill(
bill_no int auto_increment primary key,
bill_amount int(11),
cust_id int,
foreign key (cust_id) references customer(cust_id) on update cascade on delete cascade ) ;
3) Insert four rows into the bill table:
insert into bill(bill_amount, cust_id) values (2000, 1),
(2500,1),
(3000,2),
(4000,2);
select * from bill;
4) Update cust_id 1 to 100 in the customer table:
update customer set cust_id = 100 where cust_id = 1;
select * from customer;
select * from bill;
you can see, two rows with value 1 in the cust_id column of the bill table were automatically
updated to 100 because of the ON UPDATE CASCADE action.
5) Delete cust_id 2 from the customer table:
delete from customer where cust_id = 2;
select * from customer;
select * from bill;
All bill with cust_id 2 from the bill table were automatically deleted because of the on delete cascade
action.

5 | SHK
ECS-II|MySQLUnit-4
 Set Null Action
How the on update set null and on delete set null actions work.
1) Drop both customer and bill tables:
drop table if exists customer;
drop table if exists bill;
2) Create the customer and bill tables:
create table customer(
cust_id int auto_increment primary key,
cust_name char(10));
create table bill(
bill_no int auto_increment primary key,
bill_amount int,
cust_id int,
foreign key (cust_id) references customer(cust_id) on update set null on delete set null );
The foreign key in the bill table changed to on update set null and on delete set null options.
3) Insert rows into the customer table:
insert into customer(cust_name) values ('smita'), ('sanjay');
4) Insert rows into the bill table:
insert into bill(bill_amount, cust_id) values (2000, 1),
(2500,1),
(3000,2),
(4000,2);
5) Update cust_id from 1 to 100 in the customer table:
update customer set cust_id = 100 where cust_id = 1;
select * from customer;
select * from bill;
The rows with the cust_id 1 in the bill table were automatically set to null due to the on update set
null action.
6) Delete the cust_id 2 from the customer table:
delete from customer where cust_id = 2;
select * from bill;
The values in the cust_id column of the rows with cust_id 2 in the bill table were automatically set
to null due to the on delete set null action.
 To add foreign key in existing table
When you adding foreign key constraint, SQL check any existing data violate the foreign key
constraint or not. If not violate constraint added successfully otherwise you have to update invalid
data to prevent foreign key constraint violating.
alter table bill add foreign key (cust_id) references customer(cust_id);
 Drop Foreign Key Constraints
To drop a foreign key constraint, you use the alter table statement:
alter table table_name drop foreign key constraint_name;
To obtain the generated constraint name of a table, you use the show create table statement:
show create table table_name;
Example, to see the foreign keys of the bill table, you use the following statement:
show create table bill;
Drops the foreign key constraint of the bill table:
alter table bill drop foreign key;
To ensure that the foreign key constraint has been dropped, you can view the structure of the bill table:
show create table bill;

6 | SHK
ECS-II|MySQLUnit-4
 Disabling and Enabling Foreign Key Checks
it is very useful to disable foreign key checks e.g., when you import data from a csv file into a table.
if you don’t disable foreign key checks, you have to load data into a proper order i.e., you have to
load data into parent tables first and then child tables, which can be tedious.
Disable foreign key
set foreign_key_checks = 0;
Enable foreign key
set foreign_key_checks = 1;
Primary key Foreign key
Primary key cannot be null Foreign key can be null.
Primary key is always unique. It uniquely Foreign key can be duplicated Because foreign key is
identify a record in a table a field refer primary key in another table.
only one primary key in the table More than one foreign key in the table.
Check Constraints:
 Check constraint is used to check the value which is entered into a record. It is used to define
condition which each row must satisfy.
 If the condition value evaluates to false, then the record violates the constraint and you cannot
enter it into the table.
 We cannot define check constraint in SQL view, sub queries or sequences.
 It performs check on the values, before storing them into the database. It’s like condition
checking before saving data into a column.
 The constraint can be applied for a single column or a group of columns.
Syntax: [CONSTRAINT constraint name] CHECK (condition)
 Define CHECK constraint at column level with other column attributes
create table student_info(stu_code varchar(6) primary key check (stu_code like 'st%'),
name varchar (30) check(name=upper(name)),
city varchar (30) check(city in('mumbai','pune','delhi','chennai')),
scholarship int(5) check (scholarship between 5000 and 20000),
class varchar(15));
insert into student_info values ('st001','NAYANTARA','pune',8900,'ecs-II');
We are creating new student_info table name with following check constraints:
1. Values inserted into stu_code column must be start with the lower letter 'ST'.
2. Values inserted into name column must be capitalized.
3. Values inserted into city column only allow 'Mumbai','Pune','Delhi','Chennai' as valid legal
values.
4. Values inserted into scholarship column between 5000 and 20000.
 CHECK constraint apply in table level.
Create table student_info(stu_code varchar(10) primary key,
Name varchar(30),
city varchar (30), scholarship int(5), class varchar(10),
check(stu_code like'st%'),
check (name = upper(name)),
check(city in('mumbai','pune','delhi','chennai')),
check (scholarship between5000and20000));
insert into student_info values ('st002','NAYAN','delhi',9000,'bca-II');
 To add CHECK constraint in existing table column
alter table student_info add constraint check_namecheck(class=upper(class));
 To drop CHECK constraint in existing table column

7 | SHK
ECS-II|MySQLUnit-4
Alter table student_info drop constraint check_name;
Default Constraint:
 DEFAULT constraint is used to set a default value for a column. When the insert into statement
does not provide a specific value.
 Default constraint helps you assign a particular default value to every row of a column.
 DEFAULT constraint specified only at column level.
Syntax: create table table_name (
column1 column1_definition DEFAULT default_value,
column2 column2_definition,
...
);
Example: Create table stud_info (roll_no int(3) primary key,
stud_name char(30) not null,
class varchar(15) default 'M.Sc.(CS)',
fee int(5));
insert into stud (roll_no,stud_name,fee) values (1,'Omkar',5000);
select * from stud;
+---------+-----------+-----------+----------+
| roll_no | stud_name | class | fee |
+---------+-----------+-----------+----------+
| 1 | Omkar | M.Sc.(CS) | 5000 |
 Alter table add DEFAULT constraint with default value in existing table column
Syntax: alter table table_name alter column_name set default default_value;
Example: Alter table stud_info modify fee int(5) default 15000;
desc stud_info;
+-----------+-------------+------+-----+-----------+-------+
| Field | Type | Null | Key | Default | Extra |
+-----------+-------------+------+-----+-----------+-------+
| roll_no | int(3) | NO | PRI | NULL | |
| stud_name | char(30) | NO | | NULL | |
| class | varchar(15) |YES | | M.Sc.(CS) | | --Default value columns
| fee | int(5) | YES | | 15000 | |
 To remove DEFAULT constraint in existing table column
If you need to remove default value for column.
Syntax: ALTER TABLE table_name ALTER column_name DROP DEFAULT;
Example: Alter table stud_info alter fee drop default;
desc stud_info;
+-----------+-------------+------+-----+-----------+-------+
| Field | Type | Null | Key | Default | Extra |
+-----------+-------------+------+-----+-----------+-------+
| roll_no | int(3) | NO | PRI | NULL | |
| stud_name | char(30) | NO | | NULL | |
| class | varchar(15) |YES | | M.Sc.(CS) | |
| fee | int(5) | YES | | NULL | | --Default value of columns removed.

8 | SHK

You might also like