HiveBrain v1.2.0
Get Started
← Back to all entries
patternsqlMajor

Modify table constraint in PostgreSQL

Submitted by: @import:stackexchange-dba··
0
Viewed 0 times
postgresqltablemodifyconstraint

Problem

Say I have a constraint

ALTER TABLE distributors ADD CONSTRAINT zipchk CHECK (char_length(zipcode) = 5);


that needs to be modified so that zipcode length is 6.

Do I have the drop the constraint zipchk first and then recreate it ?

ALTER TABLE distributors DROP CONSTRAINT zipchk;
ALTER TABLE distributors ADD CONSTRAINT zipchk CHECK (char_length(zipcode) = 6);


or is there a MODIFY (like) command :

ALTER TABLE distributors MODIFY CONSTRAINT zipchk CHECK (char_length(zipcode) = 6);

Solution

To sum up the comments:

Like @ypercube hinted, you can do it in a single command, which is cheaper and safer:

ALTER TABLE distributors
  DROP CONSTRAINT zipchk
, ADD  CONSTRAINT zipchk CHECK (length(zipcode) = 6);


ALTER CONSTRAINT in Postgres 9.4 or later (like you found) can only change the "deferability" of a FK constraints. So not what you are looking for. Other than that, there is no "MODIFY" command for constraints (referring to MySQL's MODIFY I assume).

Details in the manual for ALTER TABLE, like @a_horse mentioned.

Code Snippets

ALTER TABLE distributors
  DROP CONSTRAINT zipchk
, ADD  CONSTRAINT zipchk CHECK (length(zipcode) = 6);

Context

StackExchange Database Administrators Q#122689, answer score: 36

Revisions (0)

No revisions yet.