DEV Community

Kiruthiga S
Kiruthiga S

Posted on

PostgreSQL(part-6)

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);
Enter fullscreen mode Exit fullscreen mode
insert into student values (1, 'Keerthi');
Enter fullscreen mode Exit fullscreen mode
insert into student values(2,NULL);
Enter fullscreen mode Exit fullscreen mode

2.UNIQUE
column cannot contain duplicate values

 create table student(id int NOT NULL UNIQUE,name varchar(30));
Enter fullscreen mode Exit fullscreen mode

3.PRIMARY KEY
Both NOT NULL and UNIQUE

 create table student(id int PRIMARY,name varchar(30));
Enter fullscreen mode Exit fullscreen mode

4.FOREIGN KEY
Used to combine two tables

CREATE TABLE department (
    dept_id INT PRIMARY KEY,
    dept_name VARCHAR(30)
);
Enter fullscreen mode Exit fullscreen mode
CREATE TABLE employee (
    emp_id INT PRIMARY KEY,
    emp_name VARCHAR(30),
    dept_id INT,
    FOREIGN KEY (dept_id)
    REFERENCES department(dept_id)
);
Enter fullscreen mode Exit fullscreen mode

5.CHECK
Checks if the condition is satisfied

CREATE TABLE student (
    id INT,
    age INT CHECK (age >= 18)
);
Enter fullscreen mode Exit fullscreen mode
CREATE TABLE student (
    id INT,
    age INT CHECK (age >= 18)
);
Enter fullscreen mode Exit fullscreen mode
INSERT INTO student VALUES (1, 20);
Enter fullscreen mode Exit fullscreen mode
INSERT INTO student VALUES (2, 15);
Enter fullscreen mode Exit fullscreen mode

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'
);
Enter fullscreen mode Exit fullscreen mode
INSERT INTO employee (id, name)
VALUES (101, 'Keerthi');
Enter fullscreen mode Exit fullscreen mode

101 | Keerthi | Active

Top comments (0)