[Solved] Comparison of TIMESTAMP column for large table

EverSQL Database Performance Knowledge Base

Comparison of TIMESTAMP column for large table

Database type:

I have a MySQL(InnoDB) table in which I have a large number of rows(a couple of million). I'm doing queries as such:

SELECT  SQL_CALC_FOUND_ROWS `a` 
FROM  `logs`  
WHERE  `connect_timestamp`  > 10000 
ORDER  BY  `connect_timestamp`  DESC 
LIMIT 1

I have a normal index added to the column, however a query like this takes up to 20 seconds, is there a better way?

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 using SQL_CALC_FOUND_ROWS (query line: 2): Including SQL_CALC_FOUND_ROWS statements tend to slow down queries significantly as it doesn't scale well. It's recommended to split this query to two: a data selection query and a counting query.
  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 `logs` ADD INDEX `logs_idx_connect_timestamp` (`connect_timestamp`);
The optimized query:
SELECT
        SQL_CALC_FOUND_ROWS `logs`.`a` 
    FROM
        `logs` 
    WHERE
        `logs`.`connect_timestamp` > 10000 
    ORDER BY
        `logs`.`connect_timestamp` DESC LIMIT 1

Related Articles



* original question posted on StackOverflow here.