[Solved] DATE() MONTH() etc. functions slow down query

EverSQL Database Performance Knowledge Base

DATE() MONTH() etc. functions slow down query

I have a table Posts with a lot of records. I want to show user today posts, it is about 3-4 k.

creation_date - DATETIME field. This field has index.

In my query i simple filter records with query:

 SELECT posts.title AS post_title
 WHERE date(posts.creation_date) = DATE('2016-06-11')

This query performing 14 seconds.

Then i changed it to:

SELECT posts.title AS post_title 
WHERE pending_posts.creation_date > CONVERT('2016-06-11', DATETIME) 
AND pending_posts.creation_date < CONVERT('2016-06-11', DATETIME) + INTERVAL 1 DAY

And it takes 0.2 seconds...

Why this happens ? And how do i convert MONTH(posts.creation_date) or YEAR(posts.creation_date) because they slow down queries too, but i need show posts per month and per year.

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. 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.
The optimized query:
SELECT
        posts.title AS post_title 
    WHERE
        posts.date_creation_date = DATE('2016-06-11')

Related Articles



* original question posted on StackOverflow here.