2

I have a table like so

        CREATE TABLE IF NOT EXISTS link_data (
            id                  UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
            connection_id UUID NOT NULL,
            the_link TEXT NOT NULL,
            UNIQUE (connection_id, the_link),
            FOREIGN KEY (connection_id)
              REFERENCES connection(id)
              ON DELETE CASCADE
        );

I need to modify the table so it's only unique on connection_id, I.E. UNIQUE (connection_id) how do I alter the table to do it?

3
  • drop the existing constraint, create a new one Commented Nov 25, 2020 at 14:44
  • 1
    How can I drop the constraint without the name of it? Commented Nov 25, 2020 at 14:46
  • stackoverflow.com/questions/5273717/… Commented Nov 25, 2020 at 14:48

2 Answers 2

1

First drop it by:

ALTER TABLE link_data 
DROP CONSTRAINT constraint_name;

then :

ALTER TABLE link_data 
ADD CONSTRAINT constraint_name UNIQUE (connection_id);

you can check table constraint by :

SELECT con.*
       FROM pg_catalog.pg_constraint con
            INNER JOIN pg_catalog.pg_class rel
                       ON rel.oid = con.conrelid
            INNER JOIN pg_catalog.pg_namespace nsp
                       ON nsp.oid = connamespace
       WHERE nsp.nspname = '<schema name>'
             AND rel.relname = 'link_data ';
Sign up to request clarification or add additional context in comments.

6 Comments

In my case I don't have direct access to the production DB. So I can't check the table constraint name. Or is the constraint name always the same so I can run it locally?
@Marc Yes, if the CREATE TABLE/ADD CONSTRAINT statement didn't specify a name itself, the inferred default names are deterministic. (Not certain whether across versions, better check the documentation about that).
@Marc I guess the constraint name will be same.
So I tested ``` BEGIN; ALTER TABLE link_data DROP CONSTRAINT constraint_name; ALTER TABLE link_data ADD CONSTRAINT constraint_name UNIQUE (connection_id); COMMIT; ``` But it did not work, I got the error "could not create unique index "constraint_name"" Where the constraint name was fetched in a local build. I then tried using the same constraint name in our testing environment where this crash happened.
@Marc did you check constraint name by the last query?
|
1

First find out the name of the unique constraint:

SELECT constraint_name
FROM information_schema.table_constraints
WHERE table_name = 'link_data'
  AND constraint_type = 'UNIQUE';

or, using psql, simply type

\d link_data

Then drop the constraint with

ALTER TABLE link_data DROP CONSTRAINT whatever_name_you_found;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.