Understanding the use of NOT NULL and Primary Key

For Complete YouTube Video: Click Here

In this class, we will be Understanding the use of NOT NULL and Primary Key.

We have already discussed the concepts of CREATE TABLE command and INSERT INTO command.

Understanding the use of NOT NULL and Primary Key

In creating the employee table, we have given the attributes NOT NULL to some of the columns, and we have considered SSN as the primary key.

The image below shows the use of NOT NULL and PRIMARY KEY.

Understanding the use of NOT NULL and Primary Key 1
Understanding the use of NOT NULL and Primary Key 1

These two are the constraints imposed on the values while inserting them into the tables.

This class will see how the SQL will behave if we try to violate those constraints.

Violating PRIMARY KEY constraint

The image below is the employee table with its values.

INSERT INTO command in SQL 3
Understanding the use of NOT NULL and Primary Key 1

In the above image, the SSN of the employee is 888665555.

Now we will try to insert the same employee again into the database, as shown below.

INSERT INTO employee (Fname, Minit, Lname, SSN, Bdate, Address, Sex, Salary, Dno) VALUES (‘James’, ‘E’, ‘Borg’, 888665555, ’10-NOV-1937′, ‘430 Stone, Houston, TX’, ‘M’, 55000, 1);

The image is the error message generated by the SQL.

Understanding the use of NOT NULL and Primary Key 2
Understanding the use of NOT NULL and Primary Key 2

The error shows that the unique key constraint is violated.

Violating NOT NULL constraint

As shown below, we will try to insert a NULL value in a column specified as NOT NULL.

INSERT INTO employee (Fname, Minit, Lname, SSN, Bdate, Address, Sex, Salary, Dno) VALUES (‘NULL’, ‘E’, ‘Borg’, 888665555, ’10-NOV-1937′, ‘430 Stone, Houston, TX’, ‘M’, 55000, 1);

The image below is the error message generated by the SQL.

Understanding the use of NOT NULL and Primary Key 3
Understanding the use of NOT NULL and Primary Key 3

The error shows that the NULL constraint is violated.