Writing SQL query is easy but it can use lots of server resources which is utmost important for huge databases, where minimization of execution delay is important, like Facebook – if they don’t update your status very frequently it will cost them users. Let’s start:
- Most important for query optimization is INDEX. Make sure you define index in your table for the columns which you use more often than others or create for every possible column.
- Use EXPLAIN statement to determine which indexes are used for a SELECT statement.
These were the general tips. For speeding up queries on MyISAM tables:
- Use ANALYZE TABLE after loading data on it. This updates a value for each index part that indicates the average number of rows that have the same value. For unique obviously it is always 1. MySQL uses this to decide which index to choose when JOIN is used.
- Sorting a table by index is good when reading all rows of the table according to the index.
- Removal of unnecessary parentheses. eg:
(a AND b AND c) OR (a AND b AND c AND d)
((a AND b AND c) OR (a AND b AND c AND d))
- Constant folding eg:
b>5 AND b=c AND a=5
(a<b AND b=c) AND a=5
- Constant expression used by indexes are only used once so try to use them as more as you can.
- COUNT(*) without WHERE clause on a single table fetch the result directly from MyISAM table information which is pretty fast.
- Constant tables are read first before any other tables. Constant table are:
- Empty tables or table with one row.
- A table with which WHERE clause is used on PRIMARY KEY or UNIQUE index.
- JOIN statement is slower that any other. It checks all the possibilities for join to give best result. If ORDER BY or GROUP BY is used and all the columns come from same table then this table is preferred first in joining.
- In some cases, MySQL can read rows from the index without even consulting the data file. If all columns used from the index are numeric, only the index tree is used to resolve the query.
- LIMIT also executes faster than query without it.
I hope you found this helpful. We’ll continue with INSERT statements optimization in next post.