Search code examples
mysqlunique-constraint

Does unique key order matters if the WHERE statement have all columns?


Assume people in another planet have unique combination in gender,age,name

gender:0~1

age:0~100

name:unlimited possibilities

And my query will use these 3 columns, so always return one(or zero) person,

So which unique key order is best?

  1. ADD CONSTRAINT UNIQUE (gender, age, name)
  2. ADD CONSTRAINT UNIQUE (name, age, gender)
  3. Doesn't matters

Solution

  • For purposes of enforcing uniqueness, it doesn't matter.

    But a unique constraint is implemented in MySQL (and likely most other SQL database products) by an index.

    The order of columns of an index do matter. Not for uniqueness, but for optimizing searching and sorting.

    In the case of a query that checks for 1 specific row, i.e. comparing the three columns to specific unique values, it still doesn't matter what order the columns are in. The conditions of a boolean expression support the commutative principle.

    ... WHERE gender = 1 AND age = 39 AND name = 'Bob'
    

    This will return true equally well, and search the index with nearly equal performance, regardless of the order of columns you define for the index.

    But another query that uses inequality or range conditions work better if the columns are in a specific order. Conditions of equality first, then one column in some other type of condition.

    ... WHERE gender = 1 AND age < 39 AND name = 'Bob'
    

    For this example, the best order would be (gender, name, age) because the column used in an inequality condition is after those columns in equality conditions. The order (name, gender, age) would also be just as good.

    The order of terms in your expression doesn't matter either. MySQL's optimizer knows how to reorder the terms to match the order of columns in the index.

    So while it doesn't matter and does no harm to use any order of columns for uniqueness, it might be important to have a specific order of columns for another type of query.

    See my answer to Does Order of Fields of Multi-Column Index in MySQL Matter

    P.S.: Some people claim that you need to put the most selective columns first, but I think that's in the category of micro-optimization. If you can measure a difference, I'd be surprised.