Optimization of a slow query with a function in front of a date-type field in a Where condition _ function

Source: Internet
Author: User
Tags create index

When an index is created on a field, the index is invalidated when the column is preceded by a function in the Where condition. Sometimes it can be optimized by overwriting SQL.

Such as:

Select COUNT (*) from T_synclog where To_days (now ())-to_days (Create_time) = 0 and status=0 and entity_type= ' org ';

Infer that the SQL implication is to view the number of record bars that were created today.

Table records have 40多万条. The table does not create an index on the create_time. Test on your own virtual machine, it takes about 30 seconds to execute the query.


Workaround: Create an index and then overwrite SQL (avoid using functions before index fields)

Create INDEX Ind_cre on T_synclog (create_time);
Only check the log records created that day: use
EIP;
SELECT COUNT (*) from T_synclog WHERE create_time BETWEEN curdate () and now () and status=0 ' org ';
Check the log records that were created the day before: use
EIP;
SELECT COUNT (*) from T_synclog WHERE create_time BETWEEN date_sub (Curdate (), INTERVAL N Day) and
Date_sub (Date_sub ( Curdate (), INTERVAL n-1 Day), INTERVAL 1 SECOND) and
status=0 and entity_type= ' org ';

The effect is as follows:

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.