03-03 TABLE Column Constrains

NOT NULL and UNIQUE

01

Constraints can be applied when creating a table, DROP the table and recreate it

CREATE TABLE student(
    student_id INT,
    name VARCHAR(20) NOT NULL,
    major VARCHAR(20) UNIQUE,
    PRIMARY KEY(student_id)
);
INSERT INTO student VALUES(1,'Jack','Biology')
INSERT INTO student VALUES(2,NULL,'Sociology')
INSERT INTO student VALUES(3,'John','Biology')

02

We can add Constraints to the columns when created the table.

Drop the table at the top then recreate the table with the Constraints after the columns you want constricted

NOT NULL means it can't be empty, in this case name can not be null

INSERT INTO student(student_id,major) VALUES(2,'Sociology');

or

INSERT INTO student VALUES(2,NULL,Sociology');

so these lines won't work

03

Same with this one, UNIQUE means the rows in the column must be different, in this example we made the major column UNIQUE

INSERT INTO student VALUE(3,'John','Biology');

The PRIMARY KEY is both NOT NULL andUNIQUE