There is no direct support for this, but you can use a workaround to create a bidirectional key: you need a unique key in an ordered version of your two columns.
Fortunately, you can do this very easily. MySQL 5.7.6+ supports created columns and unique indexes for them, which you can use to order two values ββand to ensure uniqueness.
create table testBiDirKey ( a varchar(100), b varchar(100), a_ordered varchar(100) as (least(a, b)) STORED, b_ordered varchar(100) as (greatest(a, b)) STORED, unique key unqBi_test_ab (a_ordered, b_ordered) ); insert into testBiDirKey(a,b) values('a', 'b'); insert into testBiDirKey(a,b) values('b', 'a'); Error Code: 1062. Duplicate entry 'ab' for key 'unqBi_test_ab'
This will handle null just like your current regular unique key, therefore
insert into testBiDirKey(a,b) values('a', null); insert into testBiDirKey(a,b) values('a', null); insert into testBiDirKey(a,b) values(null, 'a');
all are allowed. You can add coalesce(x,'') for just one empty value (or null OR '' ) if you want. If you check your values ββbefore adding them (for example, if they do not contain , ), you can combine these two columns with only one combined with , - albeit with a slight advantage, except that you have only 1 additional column .
For 5.7.8+, you no longer need the STORED keyword to use these columns in the index. This keyword is valid if values ββare saved (using disk space) or calculated if necessary (default).
Before MySQL 5.7.6, you can use a trigger (for update and insert ) to update two columns with these values, the same logic applies, this is just a little more code.