Indexes (MySQL)

Uit De Vliegende Brigade
Naar navigatie springen Naar zoeken springen
Wauw: Na toevoeging van een index via alter table dimensions_tmp add index sku(sku); is executietijd van 3,3 minuten teruggebracht naar 2 seconde! En da's niet de eerste keer dat ik zo'n dramatische verbetering meemaak!

[1]:

Basically an index on a table works like an index in a book (that's where the name came from):

Let's say you have a book about databases and you want to find some information about, say, storage. Without an index (assuming no other aid, such as a table of contents) you'd have to go through the pages one by one, until you found the topic (that's a full table scan). On the other hand, an index has a list of keywords, so you'd consult the index and see that storage is mentioned on pages 113-120,231 and 354. Then you could flip to those pages directly, without searching (that's a search with an index, somewhat faster).

Of course, how useful the index will be, depends on many things - a few examples, using the simile above:

  • If you had a book on databases and indexed the word "database", you'd see that it's mentioned on pages 1-59,61-290, and 292 to 400. In such case, the index is not much help and it might be faster to go through the pages one by one (in a database, this is "poor selectivity").
  • For a 10-page book, it makes no sense to make an index, as you may end up with a 10-page book prefixed by a 5-page index, which is just silly - just scan the 10 pages and be done with it.
  • The index also needs to be useful - there's generally no point to index e.g. the frequency of the letter "L" per page.

Zo dus

alter table dimensions_tmp add index sku(sku);

Waarschijnlijk een handige vuistregel:

Voeg altijd indexes toe aan tabellen,
op velden die in joins gebruikt worden. 

Verder:

  • Als je dit commando nu opnieuw uitvoert, krijg je een foutmelding
  • TXT- & BLOB-velden kunnen niet geïndexeerd worden
  • PK-velden zijn altijd geïndexeerd
  • Het lijkt erop, dat als je een index aanbrengt in een tabel zonder PK, dat die kolom dan automatisch de PK wordt - Hmm, lijkt me eigenlijk nogal sterk.

Zie ook

Bronnen