简体   繁体   中英

How to rewrite SQL queries who give better performance in MySQL

I have a project where all SQL queries was already written. Most of them can be improved, and I want to do that.

But how I can check and analyze the both queries [pre-written and I write same queries using different way].

I want to analyze the queries if I rewrite them then I can check if I did right or if old query is better than mine.

I need a queries analyzer tool for Mysql based RDBMS.

[if any mistake goes then edit it]

When you have a good RDMBS engine, the query parser should determine the most performant execution plan for your query, no matter how it is written.
I mean: the order of the tables in your from and join clauses, or the order of your filter-criteria should not matter.

The first thing to do, is look at the execution plan and analyze it. Check wether you've to add indexes, or modify indexes for instance.

Your question is also a bit vague. Can you give a sample of a query which you'd like to refactor ?

MySQL has an EXPLAIN statement, which tells you what execution path the engine will follow. You can use that to determine what changes to make:

EXPLAIN SELECT foo,bar from glurch WHERE baz > 1 ORDER BY foo;

See: http://dev.mysql.com/doc/refman/5.0/en/explain-output.html

Pay special attention to the rows column, which shows how many table rows need to be examined to execute that part of the query, as well as the Extra column, which show more importantly, how the query gets executed.

For example, if you see "Using temporary" in the Extra column, that usually means that the DB will need to write the query results out to a temporary table (possibly on disk), sort them, and then re-read them (or at least some of them).

You can avoid temporary tables and other nasty performance killers by providing appropriate indexes. And not just enough indexes, but rather the correct indexes. Just because you've indexed a column doesn't mean that index can be used in your query.

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