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:
Step 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 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;