PostgreSQL – Not Null Constraint

In PostgreSQL, the NOT NULL constraint is used to ensure that a column in a table does not contain any NULL values. If you attempt to insert a NULL value into a column with the NOT NULL constraint, PostgreSQL will raise an error and prevent the insertion.

To apply the NOT NULL constraint to a column in a PostgreSQL table, you can use the below syntax:

CREATE TABLE table_name (
    column_name data_type NOT NULL,
    ...
);

You can add the NOT NULL constraint to an existing column using the ALTER TABLE command as shown below:

ALTER TABLE table_name
ALTER COLUMN column_name SET NOT NULL;

Once the constraint is in place, any attempt to insert a NULL value into the column will result in an error. Adding the NOT NULL constraint to an existing column requires you to first update any existing NULL values to a non-null value before the constraint can be applied.

When creating a table, you can specify the NOT NULL constraint after data_type of the column.

CREATE TABLE table_name (
    column1_name data_type NOT NULL,
    column2_name data_type NOT NULL,
    ...
);

If you want to remove the NOT NULL constraint from a column, you can use the ALTER TABLE command with the DROP CONSTRAINT clause:

ALTER TABLE table_name
ALTER COLUMN column_name DROP NOT NULL;

Similar Posts