SQL Not Null Constraint

w‮igi.ww‬ftidea.com

In SQL, the NOT NULL constraint is used to ensure that a column in a table cannot contain null values. This is useful for columns that require data to be entered and for ensuring data integrity.

Here is an example of how to create a NOT NULL constraint on a column:

CREATE TABLE customers (
    customer_id INT,
    customer_name VARCHAR(50) NOT NULL,
    customer_email VARCHAR(50)
);

In this example, the customer_name column is designated as NOT NULL. This means that when data is inserted into the customers table, a value must be entered for the customer_name column. If a null value is entered or no value is entered, an error will be returned.

You can also add a NOT NULL constraint to an existing table using the ALTER TABLE command:

ALTER TABLE customers
ALTER COLUMN customer_name VARCHAR(50) NOT NULL;

In this example, we are adding a NOT NULL constraint to the customer_name column of the customers table using the ALTER TABLE command.

By using the NOT NULL constraint, you can help ensure that important data is entered correctly and prevent errors or inconsistencies in the data.