I need to put a constraint which will restrict DUPLICATE entries in combination of 2 columns.
So I have a customers table, with the below mentioned columns
id, first_name, last_name, date_of_birth, gender, email_address, primary_number, secondary_number.
What I am expecting is to have primary_number value unique for 2 columns. i.e. primary_number & secondary_number.
Eg.
primary_number | secondary_number |
---|---|
123456789 | 987654321 |
********** | 123456789 |
987654321 | ********** |
So, "123456789" should not be allowed in secondary_number, if it is already available in primary_number
As well, "987654321" should not be allowed in primary_number, if it already available in secondary_number
2
Answers
If your MySQL version is 8.0.17 or higher then you may use unique multivalued index.
DEMO
fiddle
I understand your question in that way only "pairs" like for example
123456789, 987654321
and987654321, 123456789
should pre prevented by the unique constraint. If the row123456789, 987654321
already exists, I assume rows like111111111, 987654321
or123456789,222222222
should still be allowed.If this is correct so far and if your two columns are numbers, we can use
LEAST
andGREATEST
:This will only prevent such duplicated "pairs".
Try out here
If this assumption is incorrect and also the other rows should be prevented, I would use a trigger here rather than constraints or use Akina’s idea if possible.