Question

Table definition, note the UNIQUE index:

CREATE TABLE meta
(
  id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
  type SET('tag', 'keyword') NOT NULL,
  name VARCHAR(255) NOT NULL,
  user_id INT UNSIGNED NOT NULL,
  UNIQUE (name, type, user_id),
  FOREIGN KEY (user_id) REFERENCES user (id) ON DELETE CASCADE
);

So MySQL should use the index in searches like WHERE name = 'tag' and type = 'cat' as well as only (leftmost prefixing) WHERE type = 'tag'.

I did:

EXPLAIN SELECT * FROM meta WHERE type = 'tag'

And result is (fifth column is possible_keys):

'1', 'SIMPLE', 'meta', 'ALL', NULL, NULL, NULL, NULL, '1', 'Using where'

I'm sure i'm missing something, but can't find what. Any clue?

Was it helpful?

Solution

This type of explanation probably already exists many times... But in an attempt to explain why a database engine will not typically use an index in the situation described (when the WHERE clause has only the second field in a multi-column index), a simple analogy might help.

You can think of a physical phone book (one of those old-fashioned ones made out of paper) as a type of index. The index key is the name and the data is the phone number. The phone book index is basically of the form "Lastname, Firstname". If you look up a name (e.g., Mark Wilkins) in a phone book, you are looking for the key "Wilkins,Mark". You can also just look up names easily by the lastname and find all the entries for a given last name.

However, searching for Firstname in the phone book "index" is not so easy. If you want find all the entries in the phone book with Firstname=Mark, you have to scan the entire phone book. With standard indexes (e.g., something like a b-tree), a database engine has the exact same problem. If a WHERE clause contains only the second column of a two-column index, it would have to scan the entire index to find the matches. Some database engines may still do that, but it may be faster simply to scan the table itself since it has to read the data in the table anyway for the result set typically.

OTHER TIPS

This topic was already covered by another question.

If you want your SELECTstatement to use the UNIQUE index you defined, type must be the first field of your index (UNIQUE(type, name, user_id)).

See How MySQL Uses Indexes and Multiple-Column Indexes

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top