Skip to content
Advertisement

PostgreSQL Composite Foreign Key ‘columns list must not contain duplicates’

This is my example schema:

If I run this command, I get:

ERROR: number of referencing and referenced columns for foreign key disagree

And If I add ... REFERENCES users (userid, userid) ON DELETE CASCADE

I get:

ERROR: foreign key referenced-columns list must not contain duplicate

I know it works if I type in each line their respective references, but it would be better to not repeat myself.

How can I achieve that with composite foreign keys using the same dependency?

Advertisement

Answer

Though I prefer the syntax shown by Gordon, if you want a one liner you can compress it as:

The down side of this short hand notation is that the FKs don’t have names. It could be tricky to manage them in the future should you need to remove them or modify them. Experience has shown me that it’s better to name them, and for that you need to use the full syntax, as in:

…just to get the fk1 and fk2 identifiers.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement