Constraints
Constraints is conditions or rules applied to a table to make sure that only valid and correct data is stored
1.NOT NULL
column must have a value and cannot be NULL
create table student(id int,name varchar(30) NOT NULL);
insert into student values (1, 'Keerthi');
insert into student values(2,NULL);
2.UNIQUE
column cannot contain duplicate values
create table student(id int NOT NULL UNIQUE,name varchar(30));
3.PRIMARY KEY
Both NOT NULL and UNIQUE
create table student(id int PRIMARY,name varchar(30));
4.FOREIGN KEY
Used to combine two tables
CREATE TABLE department (
dept_id INT PRIMARY KEY,
dept_name VARCHAR(30)
);
CREATE TABLE employee (
emp_id INT PRIMARY KEY,
emp_name VARCHAR(30),
dept_id INT,
FOREIGN KEY (dept_id)
REFERENCES department(dept_id)
);
5.CHECK
Checks if the condition is satisfied
CREATE TABLE student (
id INT,
age INT CHECK (age >= 18)
);
CREATE TABLE student (
id INT,
age INT CHECK (age >= 18)
);
INSERT INTO student VALUES (1, 20);
INSERT INTO student VALUES (2, 15);
this is false because 15>=18 is not satisfied the condition
DEFAULT
Automatically gives a value when you don't provide one
CREATE TABLE employee (
id INT,
name VARCHAR(30),
status VARCHAR(20) DEFAULT 'Active'
);
INSERT INTO employee (id, name)
VALUES (101, 'Keerthi');
101 | Keerthi | Active
Top comments (0)