SQL Not Null Constraint - How to use Not Null in SQL



SQL NOT NULL Constraint

  • The NOT NULL constraint ensures that a column cannot store NULL values.
  • It mandates that a field must always have a value, preventing the insertion of a new record or the update of an existing record without providing a value for that field.

SQL NOT NULL on CREATE TABLE

  • The SQL statement below ensures that the "ID," "Student Name," "Mark," and "Age" columns will not accept NULL values when creating the "Wikitechy" table:

Syntax

    CREATE TABLE tbl_Wikitechy (
        ID int NOT NULL,
        Student_Name varchar(50) NOT NULL,
        Mark int NOT NULL,
        Age int
    );
    

Output

Step 1:

sql-not-null-output

Step 2:

sql-not-null-output-2
  • This indicates an error occurs when attempting the operation due to the absence of a value in the 'Mark' column. Subsequently, after entering a value for 'Mark,' the operation is accepted
sql-not-null-error-output

SQL NOT NULL on ALTER TABLE

  • To add a NOT NULL constraint to the "Age" column in the existing "Persons" table, use the following SQL:

Syntax

    ALTER TABLE tbl_Wikitechy
    ALTER COLUMN Age int NOT NULL; 
    

Output

Step 1:

sql-not-null-alter-output

Step 2:

sql-not-null-alter-output-2

Related Searches to SQL Not Null Constraint - How to use Not Null in SQL