SQL Tutorial

SQL Introduction SQL Aggregate Functions SQL Aliases SQL And SQL Any All SQL Avg SQL Between SQL Case SQL Comments SQL Count SQL Delete SQL Distinct SQL Exists SQL Groupby SQL Having SQL In SQL Insert_into SQL Is Not Null SQL Join SQL Full Outer Join SQL Inner Join SQL Left Join SQL Right Join SQL Self Join SQL Like SQL Min Max SQL NOT Operator SQL Null SQL Operators SQL OR operator SQL OrderBy SQL Select SQL Select Into SQL Top Limit Fetch SQL Store Procedures SQL Sum SQL Union SQL Update SQL Where SQL Wildcards

SQL Database

SQL Alter Table SQL Auto increment SQL BackupDB SQL Check SQL Constrains SQL Create View SQL CreateDB SQL CreateTable SQL Data types SQL Dates SQL DefaultConstrain SQL DropDB SQL DropTable SQL Foreign Key SQL Hosting SQL Index SQL injections SQL Not NULL SQL PrimaryKey SQL Unique SQL Views

SQL NOT NULL Constraint Tutorial

Example Table

We will create a table named employees to demonstrate the SQL NOT NULL constraint:


        CREATE TABLE employees (
            employee_id INT PRIMARY KEY,
            first_name VARCHAR(50) NOT NULL,
            last_name VARCHAR(50) NOT NULL,
            department VARCHAR(50)
        );
        

Creating the Table

To create the table, use the following SQL command:


        CREATE TABLE employees (
            employee_id INT PRIMARY KEY,
            first_name VARCHAR(50) NOT NULL,
            last_name VARCHAR(50) NOT NULL,
            department VARCHAR(50)
        );
        

Result:

Command CREATE TABLE employees (employee_id INT PRIMARY KEY, first_name VARCHAR(50) NOT NULL, last_name VARCHAR(50) NOT NULL, department VARCHAR(50));
Result
  • A table named employees is created with first_name and last_name columns set to NOT NULL.

Inserting Data

To insert data into the table, use the following SQL command:


        INSERT INTO employees (employee_id, first_name, last_name, department) 
        VALUES (1, 'John', 'Doe', 'HR');
        

Result:

Command INSERT INTO employees (employee_id, first_name, last_name, department) VALUES (1, 'John', 'Doe', 'HR');
Result
  • Data is inserted into the employees table.

Attempting to Insert NULL Values

If you try to insert a NULL value into a NOT NULL column, you will get an error:


        INSERT INTO employees (employee_id, first_name, last_name, department) 
        VALUES (2, NULL, 'Smith', 'Finance');
        

Result:

Command INSERT INTO employees (employee_id, first_name, last_name, department) VALUES (2, NULL, 'Smith', 'Finance');
Result
  • Error: Column 'first_name' cannot be null.

Important Considerations

When using the NOT NULL constraint, consider the following: