Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a better way to index multiple columns than creating an index for each permutation?

Suppose I have a database table with columns a, b, and c. I plan on doing queries on all three columns, but I'm not sure which columns in particular I'm querying. There's enough rows in the table that an index immensely speeds up the search, but it feels wrong to make all the permutations of possible indexes (like this):

a
b
c
a, b
a, c
b, c
a, b, c

Is there a better way to handle this problem? (It's very possible that I'll be just fine indexing a, b, c alone, since this will cut down on the number of rows quickly, but I'm wondering if there's a better way.)

If you need more concrete examples, in the real-life data, the columns are city, state, and zip code. Also, I'm using a MySQL database.

like image 986
Dan Lew Avatar asked Jul 07 '09 03:07

Dan Lew


People also ask

Is it good to have multiple indexes on a table?

A general rule of thumb is that the more indexes you have on a table, the slower INSERT, UPDATE, and DELETE operations will be. This is why adding indexes for performance is a trade off, and must be balanced properly.

Can you index multiple columns?

A composite index is an index on multiple columns. MySQL allows you to create a composite index that consists of up to 16 columns. A composite index is also known as a multiple-column index.

What will happen if you apply index on multiple column?

An index with more than one column aggregates the contents.

What is it called when index is created on multiple columns then index?

The two types of indexes are single-column indexes and multicolumn indexes. A single-column index is an index based on the values in one column of a table. A multicolumn index is an index based on the values in multiple columns of a table.


1 Answers

In MS SQL the index "a, b, c" will cover you for scenarios "a"; "a, b"; and "a, b, c". So you would only need the following indexes:

a, b, c
b, c
c

Not sure if MySQL works the same way, but I would assume so.

like image 138
Todd Ropog Avatar answered Sep 28 '22 03:09

Todd Ropog