Constraints are used to restrict the way our data is put in the MySQL table. Constraints are used to ensure data integrity and accuracy.
There are two types of Constraints that we can use:
An example of creating a table with these constraints is as follows:
CREATE TABLE EMPLOYEES(
EMP_ID INT AUTO_INCREMENT,
FIRST_NAME VARCHAR(20) NOT NULL,
LAST_NAME VARCHAR(20) UNIQUE,
BIRTH_DATE DATE DEFAULT '1900-00-00',
HIRE_DATE DATE DEFAULT (CURRENT_DATE()),
PRIMARY KEY(EMP_ID)
);
CREATE TABLE EMPLOYEE_DEPT(
RECORD_ID INT AUTO_INCREMENT PRIMARY KEY,
EMP_ID INT,
DEPT_ID INT,
FROM_DATE DATE,
TO_DATE DATE,
FOREIGN KEY (EMP_ID) REFERENCES EMPLOYEES(EMP_ID) On UPDATE cascade ON DELETE CASCADE,
FOREIGN KEY (DEPT_ID) REFERENCES DEPARTMENTS(DEPT_ID) On UPDATE restrict ON DELETE CASCADE
);
Next, let's see a few examples of the constraints in action.
The Auto-increment generates a series and automatically inserts a value in the table. If no value is specified for a DEFAULT column, the default value we define is inserted.
insert into employees(FIRST_NAME,LAST_NAME)
values('Thorin','Oakenshield');
If the column is defined as "Not NULL" and we try to insert a NULL value in it, MySQL throws an error.
insert into employees(FIRST_NAME,LAST_NAME)
values(NULL,'Oakenshield');
If a column is defined as Null or if no constraint is mentioned in front of it, MySQL allows Null/Not Null values.
insert into employees(FIRST_NAME,LAST_NAME)
values('Thrain',NULL);
A column that is defined as a Primary Key is unique and Not Null. If either of these conditions are not met, MySQL throws an error.
insert into employees
values(2,'Smaug','The Destoyer',default,default);
If we try to insert a record for a foreign key that does not exist in a table, MySQL throws an error.
The foreign_key :: dept_id =10 does not exist.
insert into employee_dept
values(default,1,10,'1200-01-01','2800-10-15');