100 Days of SQL

sql

Day 35 – SQL NOT NULL Constraint

SQL NOT NULL constraint is used to ensure that a column in a table cannot have a NULL value. When you define a column with the NOT NULL constraint, it means that the column must have a value for every row in the table.

Here’s an example of how to create a table with a NOT NULL constraint on a column:


CREATE TABLE employees (
   id INT NOT NULL,
   name VARCHAR(50) NOT NULL,
   age INT,
   salary DECIMAL(10, 2) NOT NULL
);

In this example, the “id”, “name”, and “salary” columns have the NOT NULL constraint. This means that a value must be provided for these columns for every row inserted into the “employees” table. The “age” column does not have a NOT NULL constraint, which means that it can have a NULL value.

If you try to insert a row into the “employees” table without providing a value for a column with the NOT NULL constraint, SQL Server will return an error. For example, the following statement would fail:


INSERT INTO employees (id, name, salary)
VALUES (1, 'John', 5000.00);

This is because the “age” column does not have a value specified, and it has a NOT NULL constraint. To avoid this error, you need to provide a value for the “age” column in the INSERT statement or remove the NOT NULL constraint on the “age” column.