Skip to content
Advertisement

SQL join table with 12 column composite PK with itself painlessly

I have a table with a composite natural primary key that involves 12 columns (c1, c2, …, c12).

I want to write a self join query:

This join is a pain to write. Is there a better way?

Advertisement

Answer

Personally, if you must have a 12 column “key”, I would DROP that key, and create a computed column that concatenates all the values, and then create the key on that. This is overly simplified, but this should give you the gist:

Then your JOIN becomes as simple as:

Note: this assumes all your columns are NOT NULL. This will likely not work correctly if they can have NULL values.

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