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

102 views Asked by At

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?

1

There are 1 answers

0
Rick James On BEST ANSWER

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.