[Solved] Fastest way to SELECT through MySQL table records backwards from a certain row?
Looking to automatically optimize YOUR SQL query? Start for free.

EverSQL Database Performance Knowledge Base

Fastest way to SELECT through MySQL table records backwards from a certain row?

Database type:

With a table over 18 million rows:

SELECT * FROM tbl WHERE id > 10000000 LIMIT 30

Took 0.0724 sec.

SELECT * FROM tbl WHERE id < 10000000 ORDER BY id DESC LIMIT 30

Took 0.0565 sec.

Is this the fastest way to SELECT certain number of records before a certain row in MySQL?

It seems good enough but doesn't MySQL have to first order those 10 million rows in descending order before SELECT-ing the 30 rows?

I'm asking this is because I'm not so sure of this query I came up. It does seem work and fast enough but looking at the grammatical semantics, I'm not so sure.

Is MySQL intelligent enough to know that it doesn't have to order all those 10 million rows?

Or is there any better way to achieve this?

How to optimize this SQL query?

The following recommendations will help you in your SQL tuning process.
You'll find 3 sections below:

  1. Description of the steps you can take to speed up the query.
  2. The optimal indexes for this query, which you can copy and create in your database.
  3. An automatically re-written query you can copy and execute in your database.
The optimization process and recommendations:
  1. Avoid Selecting Unnecessary Columns (query line: 2): Avoid selecting all columns with the '*' wildcard, unless you intend to use them all. Selecting redundant columns may result in unnecessary performance degradation.
  2. Create Optimal Indexes (modified query below): The recommended indexes are an integral part of this optimization effort and should be created before testing the execution duration of the optimized query.
Optimal indexes for this query:
ALTER TABLE `tbl` ADD INDEX `tbl_idx_id` (`id`);
The optimized query:
        tbl.id > 10000000 LIMIT 30

Related Articles

* original question posted on StackOverflow here.