Search code examples
mysqlindexingcomposite-index

Does a MySQL database use a composite index when one of the fields in the WHERE clause is null?


Say I have a composite index consisting of the fields (commentId, journalEntryId, owning_comment_id ).

Now let's say that I have the following query:

UPDATE comments c 
    SET c.acceptedAsAnswer = isAnswer 
WHERE c.id = commentId
AND c.journal_entry_id = journalEntryId 
AND c.owning_comment_id IS NULL; 

As you can see c.owning_comment_id should be NULL. Will the database still use the composite index in this case?


Solution

  • This does not work as expected:

    c.owning_comment_id = NULL
    

    Instead, use

    c.owning_comment_id IS NULL
    

    Otherwise, the composite index should work. (And the order of columns in that index does not matter.)

    The query you presented is incomplete -- what is cd? Please fix the query and qualify every column. There may be other issues.