[Solved] MySQL keeps losing connection when trying to make a query
Looking to automatically optimize YOUR SQL query? Start for free.

EverSQL Database Performance Knowledge Base

MySQL keeps losing connection when trying to make a query

Database type:

I have a table with the following contents in MySQL:

enter image description here

I am to query a DATETIME column called 'trade_time' with a where clause as follows:

SELECT * FROM tick_data.AAPL
WHERE trade_time between '2021-01-01 09:30:00' and '2021-01-01 16:00:00';

What I'm getting is a 2013 error: lost connection to MySQL server after about 30 seconds.

I'm pretty new to SQL so I'm pretty sure I might be doing something wrong here, surely such a simple query shouldn't take longer than 30 seconds?

The data has 298M rows, which is huge, I was under the impression that MySQL should handle this kind of operations.

The table has just 3 columns, which is trade_time, price and volume, I would just want to query data by dates and times in a reasonable time for further processing in Python.

Thanks for any advice.

EDIT: I've put up the timeout limit on MySQL Workbench to 5 minutes, the query described above took 291 seconds to run, just to get 1 day of data, is there some way I can speed up the performance?

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 `AAPL` ADD INDEX `aapl_idx_trade_time` (`trade_time`);
The optimized query:
SELECT
        * 
    FROM
        tick_data.AAPL 
    WHERE
        tick_data.AAPL.trade_time BETWEEN '2021-01-01 09:30:00' AND '2021-01-01 16:00:00'

Related Articles



* original question posted on StackOverflow here.