Blog Archives

optimizing MySQL databases via indexing tutorial


Optimizing MySQL: Queries and Indexes You know the scene. The database is just too slow. Queries are queuing up, backlogs growing, users being refused connection. Management is ready to spend millions on “upgrading” to some other system, when the problem is really that MySQL is simply not being used properly. Badly defined or non-existent MySQL indexes are one of the primary reasons for poor performance, and fixing these can often lead to phenomenal improvements. Consider an extreme example: CREATE TABLE employee ( employee_number char(10) NOT NULL, firstname varchar(40), surname varchar(40), address text, tel_no varchar(25), salary int(11), overtime_rate int(10) NOT NULL ); To find employee Fred Jone’s salary(employee number 101832), you run: SELECT salary FROM employee WHERE employee_number = ‘101832’; MySQL has no clue where to find this record. It doesn’t even know that if it does find one matching, that there will not be another matching one, so it has to look through the entire table, potentially thousands of records, to find Fred’s details. A MySQL index is a separate file that is sorted, and contains only the field/s you’re interested in sorting on. If you create an index on employee_number, MySQL can find the corresponding record very quickly (Indexes work in very similar ways to an index in a book. Imagine paging through a technical book looking for the topic “Optimizing MySQL”. An index saves you an immense amount of time! Before we repair the table structure above, let me tell you about a most important little secret for anyone serious about optimizing their queries: EXPLAIN. EXPLAIN shows (explains!) how your queries are being used. By putting it before a SELECT, you can see whether indexes are being used properly, and what kind of join is being performed… For example: EXPLAIN SELECT employee_number,firstname,surname FROM employee WHERE employee_number= ‘10875’; +———-+——+—————+——+———+——+——+————+ | table    | type | possible_keys | key  | key_len | ref  | rows | Extra      | +———-+——+—————+——+———+——+——+————+ | employee | ALL  | NULL          | NULL |    NULL | NULL |    2 | where used | +———-+——+—————+——+———+——+——+————+

Tagged with: , , , , , , , , , , , , , , , ,
Posted in Optimizing MySQL database through indexing tutorial
Follow Tutorial on WordPress.com
categories
Calendar
May 2024
M T W T F S S
 12345
6789101112
13141516171819
20212223242526
2728293031  
Follow me on Twitter
Blog Stats
  • 88,191 hits