简体   繁体   中英

MySQL preprocessor optimization

Does anybody know if MySQL has any pre-processor optimizations involved before launching a query?

Consider following query:

string query = "SELECT giveaway_id FROM giveaways WHERE status >= @minStatus AND status <= @maxStatus AND type >= @minType AND type <= @maxType";

If @minStatus and @maxStatus are equal, as well as @minType and @maxType , we can write above query in more optimized form:

string query = "SELECT giveaway_id FROM giveaways WHERE status = @minStatus AND type = @minType";

I'm wondering if MySQL is smart enough to do above itself, or I should help it in writing proper optimized statements prior to launching them in my C# application.

Thanks.

It depends on the index you have. INDEX(status), INDEX(type) is pretty useless. INDEX(status, type) (or the opposite order) may work well.

It depends on what version you are using. Newer versions use "Index Condition Pushdown", which may be smarter in this case.

Older version may see the inequalities and decide it is a "range". Then it will say "2 ranges, so I can't make use of both parts of INDEX(status, type) ".

EXPLAIN FORMAT=JSON SELECT ... (5.6 or newer) will give you some clues of what is going on.

FLUSH STATUS;
SELECT ...;
SHOW SESSION STATUS LIKE 'Handler%';

(in any version) will give you a stronger clue. If Handler_read_next has a value approximately equal to the number of rows returned, then it is running as efficiently as possible.

Another possible wrinkle... @ variables don't always work like literals, so also test with literal values.

This is too long for a comment.

The step that you are referring to is not "pre-processing" but "compiling and optimizing". And, yes, MySQL does do various optimizations, described here .

However, the implication of your question is that a single equality comparison = is going to be much faster than two inequalities. That is generally not the case. The bigger issue is whether an index is available on status and type . The use of the index will be the major factor in performance -- and multiple inequalities could prevent MySQL from finding the best index.

My advice would be to create the correct indexes for your queries. Then write the queries to be sure they take advantage of the indexes.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM