Re: Disable unique constraint in Postgres

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



On Fri, Nov 25, 2022 at 08:46:22AM +0100, Laurenz Albe wrote:
> On Fri, 2022-11-25 at 12:48 +0530, Nikhil Ingale wrote:
> > We have an alter command to disable any constraints in the oracle db. Similarly do we have any
> > command to disable the UNIQUE constraint in postgres. Most of the postgres db forum suggests
> > dropping the UNIQUE constraint. But, I don't want to drop the constraint here instead just
> > disable the unique constraint.
> > 
> > Need your inputs on the same.
> 
> The db forums were right: you cannot disable a unique constraint in PostgreSQL.

Hi, 

hope, that I've understood the problem correctly...
At least since v13.x  dropping a unique constraint seems to work while 
dropping the related index:

-- two constraints added:
np=#  create table a (i integer unique constraint hu check(i<100));
CREATE TABLE
np=# \d+ a
                                     Table "public.a"
 Column |  Type   | Collation | Nullable | Default | Storage | Stats target | Description 
--------+---------+-----------+----------+---------+---------+--------------+-------------
 i      | integer |           |          |         | plain   |              | 
Indexes:
    "a_i_key" UNIQUE CONSTRAINT, btree (i)
Check constraints:
    "hu" CHECK (i < 100)
Access method: heap

np=# insert into a values(1);
INSERT 0 1
np=# insert into a values(1);
ERROR:  duplicate key value violates unique constraint "a_i_key"
DETAIL:  Key (i)=(1) already exists.
np=# insert into a values(2);
INSERT 0 1
np=# insert into a values(101);
ERROR:  new row for relation "a" violates check constraint "hu"
DETAIL:  Failing row contains (101).

-- So far, so good. It works as expected.
-- Now:

np=#  alter table a drop constraint a_i_key;
ALTER TABLE
np=# \d+ a
                                     Table "public.a"
 Column |  Type   | Collation | Nullable | Default | Storage | Stats target | Description 
--------+---------+-----------+----------+---------+---------+--------------+-------------
 i      | integer |           |          |         | plain   |              | 
Check constraints:
    "hu" CHECK (i < 100)
Access method: heap

-- only constraint i<100 left:

np=# insert into a values(1);
INSERT 0 1
np=# insert into a values(101);
ERROR:  new row for relation "a" violates check constraint "hu"
DETAIL:  Failing row contains (101).

np=# select * from a;
 i 
---
 1
 2
 1

-- have to check that against different postgresql versions and docs...

cheers

/np

> 
> Yours,
> Laurenz Albe
> 





[Index of Archives]     [Postgresql Home]     [Postgresql General]     [Postgresql Performance]     [Postgresql PHP]     [Postgresql Jobs]     [PHP Users]     [PHP Databases]     [PHP Home]     [PHP on Windows]     [Kernel Newbies]     [PHP Classes]     [PHP Databases]     [Yosemite Forum]

  Powered by Linux