Search code examples
mysqlindexingmyisam

Is the primary key stored implicitly in other keys in mysql myisam engine?


My problem: imagine a table with millions of rows, like

CREATE TABLE a {
id INT PRIMARY KEY,
column2..,
column3..,
many other columns..
..
INDEX (column2);

and a query like this:

SELECT id FROM a WHERE column2 > 10000 LIMIT 1000 OFFSET 5000;

My question: does mysql only use the index "column2" (so the primary key id is implicitly stored as a reference in other indexes), or does it have to fetch all rows to get also the id, which is selected for output? In that case the query should be much faster with a key declared as:

INDEX column2(column2, id)

Solution

  • An index on column2 is required. Your suggestion with id in the index will prevent table scans and should be very efficient.

    Further more it is faster to do this assuming that column2 is a continuous sequence:

    SELECT id FROM a WHERE column2 > 15000 LIMIT 1000;
    

    This is because to work with the offset it would just have to scan the next 5000 records (MySQL does not realize that you are actually offsetting column2).