[Solved] How to optimze mysql subquery?

EverSQL Database Performance Knowledge Base

How to optimze mysql subquery?

Database type:

Need help to optimize my query, currently it runs approximately 22secs and I have 1.1 million rows in that table. Here is my query. This query is returning the users latest time in.

    t.id, t.user_id, t.created
    timesheets t
    t.user_id IN (41649 , 41901,41899,41482,41648,41897,41652,
    AND t.id = (SELECT 
                    timesheets AS sub_t
                    sub_t.user_id = t.user_id
                AND sub_t.description = 'in')

I also have table indexes for this table (id, user_id, created, description). Any suggestion is very much appreciated. Thanks

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 Subselect When Selecting MAX/MIN Per Group (query line: 12): Constant subquery results are usually not cached by the database, especially in non-recent database versions. Therefore, a constant subquery in a WHERE clause will be fully evaluated for every row the WHERE clause will examine, which can significantly impact query performance. Use the method mentioned in the example instead.
  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 `timesheets` ADD INDEX `timesheets_idx_id_descriptio_user_id` (`id`,`description`,`user_id`);
The optimized query:
        timesheets AS timesheets1 
        timesheets AS timesheets2 
            ON (
                timesheets2.user_id = timesheets1.user_id 
                AND timesheets2.description = 'in'
            AND (
                timesheets1.id < timesheets2.id
            timesheets1.user_id IN (
                41649, 41901, 41899, 41482, 41648, 41897, 41652, 41483, 41900, 41143, 41907, 16, 42191, 42195, 42194, 42136, 42193, 42190, 42484, 42485, 42486, 42504, 42052, 42797, 42997, 42868, 42847, 42505, 42964
            AND 1 = 1
        AND (
            timesheets2.id IS NULL

Related Articles

* original question posted on StackOverflow here.