Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I add indexes to MySQL tables?

I've got a very large MySQL table with about 150,000 rows of data. Currently, when I try and run

SELECT * FROM table WHERE id = '1'; 

the code runs fine as the ID field is the primary index. However, for a recent development in the project, I have to search the database by another field. For example:

SELECT * FROM table WHERE product_id = '1'; 

This field was not previously indexed; however, I've added one, so mysql now indexes the field, but when I try to run the above query, it runs very slowly. An EXPLAIN query reveals that there is no index for the product_id field when I've already added one, and as a result the query takes any where from 20 minutes to 30 minutes to return a single row.

My full EXPLAIN results are:

| id | select_type | table | type | possible_keys| key  | key_len | ref  | rows  | Extra       | +----+-------------+-------+------+--------------+------+---------+------+-------+------------------+ |  1 | SIMPLE      | table | ALL  | NULL         | NULL | NULL    | NULL |157211 | Using where | +----+-------------+-------+------+--------------+------+---------+------+-------+------------------+ 

It might be helpful to note that I've just taken a look, and ID field is stored as INT whereas the PRODUCT_ID field is stored as VARCHAR. Could this be the source of the problem?

like image 993
Michael Avatar asked Jun 09 '10 01:06

Michael


People also ask

Can I add index to existing table MySQL?

In MySQL, an index can be created on a table when the table is created with CREATE TABLE command. Otherwise, CREATE INDEX enables to add indexes to existing tables. A multiple-column index can be created using multiple columns. The indexes are formed by concatenating the values of the given columns.

How do I index a table in MySQL?

Generally, we create an index at the time of table creation in the database. The following statement creates a table with an index that contains two columns col2 and col3. If we want to add index in table, we will use the CREATE INDEX statement as follows: mysql> CREATE INDEX [index_name] ON [table_name] (column names)

What is indexing in MySQL with example?

Practically, indexes are also a type of tables, which keep primary key or index field and a pointer to each record into the actual table. The users cannot see the indexes, they are just used to speed up queries and will be used by the Database Search Engine to locate records very fast.


2 Answers

ALTER TABLE `table` ADD INDEX `product_id_index` (`product_id`) 

Never compare integer to strings in MySQL. If id is int, remove the quotes.

like image 137
zerkms Avatar answered Sep 29 '22 05:09

zerkms


ALTER TABLE TABLE_NAME ADD INDEX (COLUMN_NAME); 
like image 32
pabloferraz Avatar answered Sep 29 '22 05:09

pabloferraz