PostgreSQL – How to Add a NOT NULL Constraint
To add a NOT NULL
constraint to an existing column in a PostgreSQL table, you can use the ALTER TABLE
statement with the ALTER COLUMN
clause. Here’s the basic syntax:
ALTER TABLE table_name ALTER COLUMN column_name SET NOT NULL;
where table_name
is the name of the table you want to modify, and column_name
is the name of the column you want to add the NOT NULL
constraint to.
Here’s an example of adding a NOT NULL
constraint to an existing column:
ALTER TABLE users ALTER COLUMN email SET NOT NULL;
After executing this SQL statement, the “email” column in the “users” table will be constrained to contain only non-null values. and PostgreSQL will prevent any future inserts or updates that would violate this constraint.
When adding a NOT NULL
constraint to an existing column, you should ensure that there are no NULL values in that column. The operation will fail if there are null values. You will need to either update or delete rows with NULL values before adding the constraint.