X
X
XpeH Petrovich2014-07-11 17:12:26
MySQL
XpeH Petrovich, 2014-07-11 17:12:26

How to properly use indexes in MySQL?

The question is the following. If there is a composite table key on columns col1, col2, col3 and I will start searching by prefix, i.e. WHERE col1=something - will I speed up the selection if I make the condition: WHERE col1=something AND col2=something? Plus, let's imagine that in the case of the first condition and in the case of the second condition, the query will return the same number of rows, i.e. a table with the following content:
+---id---+---col1---+---col2---+---col3---+
| 1 | 1 | 1 | ... |
| 2 | 2 | 2 | ... |
| 3 | 3 | 3 | ... |
| 4 | 4 | 4 | ... |
| 5 | 5 | 5 | ... |
+--------+-----------+-----------+-----------+
etc.
Well, respectively, two options for the request - SELECT * FROM table1 WHERE col1=1and SELECT * FROM table1 WHERE col1=1 AND col2=1.
(PS I apologize for writing the structure and data, I don’t know how to arrange it beautifully here, I tried my best ((()

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Andrey Burov, 2014-07-11
@uakoB

Ideally, you should have a composite index on all fields that are used in conditions.
SELECT * FROM table1 WHERE col1=1Here the index on the field col1
SELECT * FROM table1 WHERE col1=1 AND col2=1will be used Here the composite index on (col1, col2) will be used
Of course, if you have an index on col1 and an index on col2, then MySQL uses them, but the composite will be faster.

C
Calc, 2014-07-11
@Calc

in mysql there is an explain command.
It will display a summary table for you about how your indexes are used.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question