4 Leave Cover
4 Leave Cover

Reputation: 1276

Fastest result when checking date range

User will select a date e.g. 06-MAR-2017 and I need to retrieve hundred thousand of records for date earlier than 06-MAR-2017 (but it could vary depends on user selection).

From above case, I am using this querySELECT col from table_a where DATE_FORMAT(mydate,'%Y%m%d') < '20170306' I feel that the record is kind of slow. Are there any faster or fastest way to get date results like this?

Upvotes: 0

Views: 40

Answers (2)

Thorsten Kettner
Thorsten Kettner

Reputation: 94914

With 100,000 records to read, the DBMS may decide to read the table record for record (full table scan) and there wouldn't be much you could do.

If on the other hand the table contains billions of records, so 100,000 would just be a small part, then the DBMS may decide to use an index instead.

In any way you should at least give the DBMS the opportunity to select via an index. This means: create an index first (if such doesn't exist yet).

You can create an index on the date column alone:

create index idx on table_a (mydate);

or even provide a covering index that contains the other columns used in the query, too:

create index idx on table_a (mydate, col);

Then write your query such that the date column is accessed directly. You have no index on DATE_FORMAT(mydate,'%Y%m%d'), so above indexes don't help with your original query. You'd need a query that looks up the date itself:

select col from table_a where mydate < date '2017-03-06';

Whether the DBMS then uses the index or not is still up to the DBMS. It will try to use the fastest approach, which very well can still be the full table scan.

Upvotes: 2

Diogo Sgrillo
Diogo Sgrillo

Reputation: 2701

If you make a function call in any column at the left side of comparison, MySql will make a full table scan.

The fastest method would be to have an index created on mydate, and make the right side ('20170306') the same datatype of the column (and the index)

Upvotes: 1

Related Questions