[Solved] Subquery is faster?

EverSQL Database Performance Knowledge Base

Subquery is faster?

Database type:

If I need to perform a complex calculation based on row data, and then alias it, in a query that might only need to operate on 10 of 10000 rows because of restrictive where clauses, is it best to use a subquery in the FROM clause, instead of using a single query?

An example is probably easier:

FROM t1 
WHERE c2 > 5 AND c3 < 10 AND C6 = 4 AND c7 > 50
HAVING a1 > 100
LIMIT 1000;


    (SELECT * FROM t1
     WHERE c2 > 5 AND c3 < 10 AND C6 = 4 AND c7 > 50
     LIMIT 1000) as ta1
HAVING a1 > 100;

Which query would be faster? I guess the real question is - will MySQL apply the WHERE clauses before performing the COMPLEX_CALC on all rows?

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 `t1` ADD INDEX `t1_idx_c6_c2` (`C6`,`c2`);
The optimized query:
        COMPLEX_CALC(t1.c10) AS a1 
        t1.c2 > 5 
        AND t1.c3 < 10 
        AND t1.C6 = 4 
        AND t1.c7 > 50 
        a1 > 100 LIMIT 1000

Related Articles

* original question posted on StackOverflow here.