I have a problem with creating index described in answer for this question: sql unique constraint on a 2 columns combination
I am using MySql, and I received syntax error, my version of this query is as follows:
CREATE UNIQUE INDEX ON friends (LEAST(userID, friendID), GREATEST(userID, friendID));
LEAST and GREATEST functions are available in MySql, but maybe the syntax should be different? I tried to make an ALTER TABLE version, but it does not worked as well.
In MySQL, you can't use functions as the values for indexes.
The documentation does not explicitly state this, however, it is a basic characteristic of an index to only support "fixed" data:
Generally, this "fixed" data is an individual column/field; with string-fields (such as
varchar
ortext
) you can have a prefix-index and not the entire column. Check outCREATE INDEX
for more info on that.The unique index that you're trying to create in you example will have a single record ever; that's not really a beneficial index since it doesn't help for searching the entire table. However, if you index your table on
userID, friendID
, using theLEAST()
andGREATEST()
functions in aSELECT
statement will be optimized thanks to the index itself, so it may be what you're after in this case.