Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

index with multiple columns - ok when doing query on only one column?

If I have an table

create table sv ( id integer, data text )

and an index:

create index myindex_idx on sv (id,text)

would this still be usefull if I did a query

select * from sv where id = 10

My reason for asking is that i'm looking through a set of tables with out any indexes, and seeing different combinations of select queries. Some uses just one column other has more than one. Do I need to have indexes for both sets or is an all-inclusive-index ok? I am adding the indexes for faster lookups than full table scans.

Example (based on the answer by Matt Huggins):

select * from table where col1 = 10
select * from table where col1 = 10 and col2=12
select * from table where col1 = 10 and col2=12 and col3 = 16

could all be covered by index table (co1l1,col2,col3) but

select * from table where col2=12

would need another index?

like image 465
svrist Avatar asked Dec 08 '09 08:12

svrist


People also ask

Can a column have multiple 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.

Can an index be defined for a single column?

The most common type of index involves a single column, storing copies of the values from that column in a data structure, allowing fast lookups for the rows with the corresponding column values.

Why we shouldn't index every column in the SQL table?

It is not a good idea to indexes all the columns in a table. While this will make the table very fast to read from, it also becomes much slower to write to.

Which column are not good for indexing?

A GUID column is not the best candidate for indexing. Indexes are best suited to columns with a data type that can be given some meaningful order, ie sorted (integer, date etc). It does not matter if the data in a column is generally increasing.


1 Answers

It should be useful since an index on (id, text) first indexes by id, then text respectively.

  • If you query by id, this index will be used.
  • If you query by id & text, this index will be used.
  • If you query by text, this index will NOT be used.

Edit: when I say it's "useful", I mean it's useful in terms of query speed/optimization. As Sune Rievers pointed out, it will not mean you will get a unique record given just ID (unless you specify ID as unique in your table definition).

like image 191
Matt Huggins Avatar answered Sep 27 '22 18:09

Matt Huggins