I have a table with a dozen or so columns and no primary key defined for it. There are several million rows stored in it. Is there a SQL query I could use that would return the combination of columns that will give a unique key for the table? It is specifically an Oracle database.
Oracle – SQL Query to Find Columns Creating Unique Key for Table
oracleunique-constraint
Related Question
- MySQL – Why InnoDB Table Uses UNIQUE Constraint Instead of PRIMARY KEY by Default
- MySQL – Set Unique Key Checks to 0
- SQL Server – How to Find Minimum Set of Fields for Unique Composite Key
- Oracle Error ORA-02270 – No Matching Unique or Primary Key
- Unique combination of values
- MySQL Index – Benefit of Creating Index Key with Existing Unique Key
- Oracle – How to Create Stored Procedure That Returns Query Result
Best Answer
First, it seems like the wrong way of approaching the problem. I would start by investigation what is supposed to be unique according to the business rules.
Nevertheless, you will have to investigate the power set of column combinations. The cardinality of the power set on n is 2^n, but the empty set can be ignored. So if you have 10 columns this means 2^10-1=1023 combinations to investigate. It's probably easiest to use a host language to generate the sql, but you can use group by cube to get the combinations. Assuming columns c1, c2, c3:
Now you can generate the sql by looping over this result set:
if no rows exists the column combination is a candidate for a key. Just verify that no sub set of this combination is also a candidate.