[Solved] show query data grouped horizontally

How to optimize this SQL query?

In case you have your own slow SQL query, you can optimize it automatically here.

For the query above, the following recommendations will be helpful as part of the 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 Date Functions In Conditions (query line: 8): When a function is used directly on an indexed column, the database's optimizer won’t be able to use the index. An alternative way is to use a range condition instead of a function call.
  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.
  3. Explicitly ORDER BY After GROUP BY (modified query below): By default, the database sorts all 'GROUP BY col1, col2, ...' queries as if you specified 'ORDER BY col1, col2, ...' in the query as well. If a query includes a GROUP BY clause but you want to avoid the overhead of sorting the result, you can suppress sorting by specifying 'ORDER BY NULL'.
  4. Index Function Calls Using Generated Columns (modified query below): When a function is used directly on an indexed column, the database's optimizer won’t be able to use the index to optimize the search. Creating and indexing a generated column (supported in MySQL 5.7) will allow MySQL to optimize the search.
  5. Use Numeric Column Types For Numeric Values (modified query below): When the database is required to cast values, an index can't be used to enhance performance. It's recommended not to compare numeric columns to quoted values, as the quotes will result in a cast that will prevent index usage.
Optimal indexes for this query:
ALTER TABLE `traslados` ADD INDEX `traslados_idx_month_fecha_fecha` (`month_fecha`,`fecha`);
ALTER TABLE `traslados` ADD INDEX `traslados_idx_month_fech_day_fecha_movil` (`month_fecha`,`day_fecha`,`movil`);
The optimized query:
        traslados.fecha BETWEEN '2016-01-01 00:00:00' AND '2016-12-31 23:59:59' 
        AND traslados.month_fecha = 07 
        AND traslados.movil IS NOT NULL 

Related Articles

* original question posted on StackOverflow here.