Базы данныхИнтернетКомпьютерыОперационные системыПрограммированиеСетиСвязьРазное
Поиск по сайту:
Подпишись на рассылку:

Назад в раздел

Go to the first, previous, next, last section, table of contents.


10 Getting maximum performance from MySQL

Optimization is a complicated task since it ultimately requires understanding of the whole system. While it may be possible to do some local optimizations with small knowledge of your system/application, the more optimal you want your system to become the more you will have to know about it.

So this chapter will try to explain and give some examples of different ways to optimize MySQL. But remember that there are always some (increasingly harder) ways to make the system even faster left to do.

10.1 Optimization overview

The most important part for getting a system fast is of course the basic design. You also need to know that kinds of things your system will be doing. That is your bottlenecks are.

The most common bottlenecks are.

  • Disk seeks It takes time for the disk to find a piece of data. With modern disk in 1999 the mean time for this is usually lower than 10ms. So we can in theory do about 1000 seeks a second. This time improves slowly with new disks and is very hard to optimize for a single table. The way to optimize this is to spread the data on more than one disk.
  • Disk reading/writing When the disk is at the correct position we need to read the data. With modern disks in 1999 one disks delivers something like 10-20Mb/s. This is easier to optimize than seeks since you can read in parallel from multiple disks.
  • CPU cycles When we have got the data into main memory (or if it already where there) we need to process it to get to our result. When we have small tables compared to the memory this is the most common limiting factor. But then with small tables speed is usually not the problem.
  • Memory bandwidth When the CPU needs more data than that fits in the cpu cache the main memory bandwidth becomes a bottleneck. This is a uncommoon bottleneck for most systems but one should be aware of it.

10.2 System/Compile time and startup parameter tuning

We start with the system level things sine some of these decisions have to be made very early. In other cases a fast look at this part may suffice since it not that important for the big gains. But it is always nice to have a feeling about how much one gould gain by chancing things at this level.

The default OS to use is really important! To get the most use of multiple CPU machines one should use Solaris (because the threads works really nice) or Linux (because the 2.2 kernel has really good SMP support). Also on 32bit machines Linux has a 2G file size limit by default. Hopefully this will be fixed soon when new filesystems is released (XFS).

Since we have not run production MySQL on that many platforms we advice you to test your intended platform before choosing it if possible.

Other tips:

  • If you have enough ram, you could remove all swap devices. Some operating systems will use a SWAP device in some contexts even if you have free memory.
  • Use the --skip-locking MySQL option to avoid external locking. Note that this will not impact MySQL functionality as long that only run one server. Just remember to take down the server (or lock relevant parts) before you run myisamchk. On some system this switch is mandatory since the external locking does not work in any case. The --skip-locking option is on by default when compiling with MIT-pthreads, because flock() isn't fully supported by MIT-pthreads on all platforms. The only case when you can't use --skip-locking is if you run multiple MySQL SERVERS (not clients) on the same data. Or run myisamchk on the table without first flushing and locking the mysqld server tables first. You can still use LOCK TABLES / UNLOCK TABLES even if you are using --skip-locking

10.2.1 How compiling and linking affects the speed of MySQL

Most of the following tests are done on Linux and with the MySQL benchmarks, but they should give some indication for other operating systems and workloads.

You get the fastest executable when you link with -static. Using Unix sockets rather than TCP/IP to connect to a database also gives better performance.

On Linux, you will get the fastest code when compiling with pgcc and -O6. To compile `sql_yacc.cc' with these options, you need about 200M memory because gcc/pgcc needs a lot of memory to make all functions inline. You should also set CXX=gcc when configuring MySQL to avoid inclusion of the libstdc++ library (it is not needed).

By just using a better compiler and/or better compiler options you can get a 10-30 % speed increase in your application. This is particularly important if you compile the SQL server yourselves!

On Intel you should for example use pgcc or the Cygnus CodeFusion compiler to get maximum speed. We have tested the new Fujitsu compiler but it is not yet bug free enough to compile MySQL with optimizations on.

Here is a list of some mesurements that we have done:

  • If you use pgcc and compile everything with -O6, the mysqld server is 11% faster than with gcc versions older than gcc 2.95.2.
  • If you link dynamically (without -static), the result is 13% slower. Note that you still can use a dynamic linked MySQL library. It is only the server that is critical for performance.
  • If you connect using TCP/IP rather than Unix sockets, the result is 7.5% slower.
  • On a Sun SPARCstation 10, gcc 2.7.3 is 13% faster than Sun Pro C++ 4.2.
  • On Solaris 2.5.1, MIT-pthreads is 8-12% slower than Solaris native threads on a single processor. With more load/cpus the difference should get bigger.

The MySQL-Linux distribution provided by TcX is compiled with pgcc and linked statically.

10.2.2 Disk issues

  • As mentioned before disks seeks are a big performance bottleneck. This problems gets more and more apparent when the data starts to grow so large that effective caching becomes impossible. For large databases, where you access data more or less random, you can count on that you will need at least one disk seek to read and a couple of disk seeks to write things. To minimize this problem use disks with low seek times.
  • To increase the number of available disk spindles (and thereby reduce the seek overhead) it is possible to either symlink files to different disks or stripe the disks.
    Using symbolic links
    This means that you symlink the index or/and data file(s) from the normal data directory to another disk (that may also be striped). This makes both the seek and read times better (if the disk are not used for other things). See section 10.2.2.1 Using symbolic links for databases and tables.
    Striping
    Striping means that you have many disks and put the first block on the first disk, the second block on the second disk, and the Nth on the (Nth mod number_of_disks) disk, and so on. This means if your normal data size is less than the stripe size (or perfectly aligned) you will get much better performance. Note that striping if very dependent on the OS and stripe-size. So benchmark your application with different stripe-sizes. See section 10.8 Using your own benchmarks. Note that the speed difference for striping is very dependent on the parameters. Depending on how you set the striping parameters and number of disks you may get difference in orders of magnitude. Note that you have to choose to optimize for random or sequential access.
  • For reliability you may want to use RAID 0+1 (striping + mirroring), but in this case you will need 2*N drives to hold N drives of data. This is probably the best option if you have the money for it! You may however also have to invest in some volume management software to handle it efficiently.
  • A good option is to have semi-important data (that can be re-generated) on RAID 0 disk while store really important data (like host information and logs) on a RAID 0+1 or RAID N disks. RAID N can be a problem if you have many writes because of the time to update the parity bits.
  • You may also set the parameters for the file system that the database uses. One easy change is to mount the file system with the noatime option. That makes it skip the updating of the last access time in the inode and by this will avoid some disk seeks.

10.2.2.1 Using symbolic links for databases and tables

You can move tables and databases from the database directory to other locations and replace them with symbolic links to the new locations. You might want to do this, for example, to move a database to a file system with more free space.

If MySQL notices that a table is a symbolically-linked, it will resolve the symlink and use the table it points to instead. This works on all systems that support the realpath() call (at least Linux and Solaris support realpath())! On systems that don't support realpath(), you should not access the table through the real path and through the symlink at the same time! If you do, the table will be inconsistent after any update.

MySQL doesn't support linking of databases by default. Things will work fine as long as you don't make a symbolic link between databases. Suppose you have a database db1 under the MySQL data directory, and then make a symlink db2 that points to db1:

shell> cd /path/to/datadir
shell> ln -s db1 db2

Now, for any table tbl_a in db1, there also appears to be a table tbl_a in db2. If one thread updates db1.tbl_a and another thread updates db2.tbl_a, there will be problems.

If you really need this, you must change the following code in `mysys/mf_format.c':

if (!lstat(to,&stat_buff))  /* Check if it's a symbolic link */
    if (S_ISLNK(stat_buff.st_mode) && realpath(to,buff))

Change the code to this:

if (realpath(to,buff))

10.2.3 Tuning server parameters

You can get the default buffer sizes used by the mysqld server with this command:

shell> mysqld --help

This command produces a list of all mysqld options and configurable variables. The output includes the default values and looks something like this:

Possible variables for option --set-variable (-O) are:
back_log              current value: 5
connect_timeout       current value: 5
delayed_insert_timeout  current value: 300
delayed_insert_limit  current value: 100
delayed_queue_size    current value: 1000
flush_time            current value: 0
interactive_timeout   current value: 28800
join_buffer_size      current value: 131072
key_buffer_size       current value: 1048540
lower_case_table_names  current value: 0
long_query_time       current value: 10
max_allowed_packet    current value: 1048576
max_connections       current value: 100
max_connect_errors    current value: 10
max_delayed_threads   current value: 20
max_heap_table_size   current value: 16777216
max_join_size         current value: 4294967295
max_sort_length       current value: 1024
max_tmp_tables        current value: 32
max_write_lock_count  current value: 4294967295
net_buffer_length     current value: 16384
query_buffer_size     current value: 0
record_buffer         current value: 131072
sort_buffer           current value: 2097116
table_cache           current value: 64
thread_concurrency    current value: 10
tmp_table_size        current value: 1048576
thread_stack          current value: 131072
wait_timeout          current value: 28800

If there is a mysqld server currently running, you can see what values it actually is using for the variables by executing this command:

shell> mysqladmin variables

Each option is described below. Values for buffer sizes, lengths and stack sizes are given in bytes. You can specify values with a suffix of `K' or `M' to indicate kilobytes or megabytes. For example, 16M indicates 16 megabytes. Case of suffix letters does not matter; 16M and 16m are equivalent.

You can also see some statistics from a running server by the command SHOW STATUS. See section 7.21 SHOW syntax (Get information about tables, columns,...).

ansi_mode.
Is ON if mysqld was started with --ansi. See section 5.2 Runnning MySQL in ANSI mode.
back_log
The number of outstanding connection requests MySQL can have. This comes into play when the main MySQL thread gets VERY many connection requests in a very short time. It then takes some time (although very little) for the main thread to check the connection and start a new thread. The back_log value indicates how many requests can be stacked during this short time before MySQL momentarily stops answering new requests. You need to increase this only if you expect a large number of connections in a short period of time. In other words, this value is the size of the listen queue for incoming TCP/IP connections. Your operating system has its own limit on the size of this queue. The manual page for the Unix listen(2) system call should have more details. Check your OS documentation for the maximum value for this variable. Attempting to set back_log higher than your operating system limit will be ineffective.
concurrent_inserts
If ON (the default), MySQL will allow you to use INSERT on MyISAM tables at the same time as you run SELECT queries on them. You can turn this option off by starting mysqld with --safe or --skip-new.
connect_timeout
The number of seconds the mysqld server is waiting for a connect packet before responding with Bad handshake.
delayed_insert_timeout
How long a INSERT DELAYED thread should wait for INSERT statements before terminating.
delayed_insert_limit
After inserting delayed_insert_limit rows, the INSERT DELAYED handler will check if there are any SELECT statements pending. If so, it allows these to execute before continuing.
delay_key_write
If enabled (is on by default), MySQL will honor the delay_key_write option CREATE TABLE. This means that the key buffer for tables with this option will not get flushed on every index update, but only when a table is closed. This will speed up writes on keys a lot but you should add automatic checking of all tables with myisamchk --fast --force if you use this. Note that if you start mysqld with the --delay-key-write_for_all_tables option this means that all tables will be treated as if they where created with the delay_key_write option. You can clear this flag by starting mysqld with --skip-new or --safe-mode.
delayed_queue_size
How big a queue (in rows) should be allocated for handling INSERT DELAYED. If the queue becomes full, any client that does INSERT DELAYED will wait until there is room in the queue again.
flush_time
If this is set to a non-zero value, then every flush_time seconds all tables will be closed (to free up resources and sync things to disk).
init_file
The name of the file specified with the --init-file option when you start the server. This is a file of SQL statements you want the server to execute when it starts.
interactive_timeout
The number of seconds the server waits for activity on a interactive connection before closing it. An interactive client is defined as a client that uses the CLIENT_INTERACTIVE option to mysql_real_connect(). See also wait_timeout.
join_buffer_size
The size of the buffer that is used for full joins (joins that do not use indexes). The buffer is allocated one time for each full join between two tables. Increase this value to get a faster full join when adding indexes is not possible. (Normally the best way to get fast joins is to add indexes.)
key_buffer_size
Index blocks are buffered and are shared by all threads. key_buffer_size is the size of the buffer used for index blocks. Increase this get better index handling (for all reads and multiple writes) to as much as you can afford. If you make this too big the system will starte to page and go REAL slow. Remember that since MySQL does not cache data read that you will have to leave some room for the OS filesystem cache. To get even more speed when writing many rows at the same time use LOCK TABLES. See section 7.24 LOCK TABLES/UNLOCK TABLES syntax.
long_query_time
If a query takes longer than this (in seconds), the Slow_queries counter will be incremented.
max_allowed_packet
The maximum size of one packet. The message buffer is initialized to net_buffer_length bytes, but can grow up to max_allowed_packet bytes when needed. This value by default is small to catch big (possibly wrong) packets. You must increase this value if you are using big BLOB columns. It should be as big as the biggest BLOB you want to use.
max_connections
The number of simultaneous clients allowed. Increasing this value increases the number of file descriptors that mysqld requires. See below for comments on file descriptor limits. See section 18.2.4 Too many connections error.
max_connect_errors
If there is more than this number of interrupted connections from a host this host will be blocked for further connections. You can unblock a host with the command FLUSH HOSTS.
max_delayed_threads
Don't start more than this number of threads to handle INSERT DELAYED statements. If you try to insert data in a new table after all INSERT DELAYED threads are in use, the row will be inserted as if the DELAYED attribute wasn't specified.
max_join_size
Joins that are probably going to read more than max_join_size records return an error. Set this value if your users tend to perform joins without a WHERE clause that take a long time and return millions of rows.
max_sort_length
The number of bytes to use when sorting BLOB or TEXT values (only the first max_sort_length bytes of each value are used; the rest are ignored).
max_tmp_tables
(This option doesn't yet do anything). Maximum number of temporary tables a client can keep open at the same time.
net_buffer_length
The communication buffer is reset to this size between queries. This should not normally be changed, but if you have very little memory, you can set it to the expected size of a query. (That is, the expected length of SQL statements sent by clients. If statements exceed this length, the buffer is automatically enlarged, up to max_allowed_packet bytes.)
net_retry_count
If a read on a communication port is interrupted, retry this many times before giving up. This value should be quite high on FreeBSD as internal interrupts is sent to all threads.
record_buffer
Each thread that does a sequential scan allocates a buffer of this size for each table it scans. If you do many sequential scans, you may want to increase this value.
skip_show_databases
This prevents people from doing SHOW DATABASES, if they don't have the PROCESS_PRIV privilege. This can improve security if you're concerned about people being able to see what databases and tables other users have.
sort_buffer
Each thread that needs to do a sort allocates a buffer of this size. Increase this value for faster ORDER BY or GROUP BY operations. See section 18.5 Where MySQL stores temporary files.
table_cache
The number of open tables for all threads. Increasing this value increases the number of file descriptors that mysqld requires. MySQL needs two file descriptors for each unique open table. See below for comments on file descriptor limits. For information about how the table cache works, see section 10.2.4 How MySQL opens and closes tables.
tmp_table_size
If a temporary table exceeds this size, MySQL generates an error of the form The table tbl_name is full. Increase the value of tmp_table_size if you do many advanced GROUP BY queries.
thread_concurrency
On Solaris, mysqld will call thr_setconcurrency() with this value. thr_setconcurrency() permits the application to give the threads system a hint, for the desired number of threads that should be run at the same time.
thread_stack
The stack size for each thread. Many of the limits detected by the crash-me test are dependent on this value. The default is large enough for normal operation. See section 10.8 Using your own benchmarks.
wait_timeout
The number of seconds the server waits for activity on a connection before closing it. See also interactive_timeout.

MySQL uses algorithms that are very scalable, so you can usually run with very little memory or give MySQL more memory to get better performance.

If you have much memory and many tables and want maximum performance with a moderate number of clients, you should use something like this:

shell> safe_mysqld -O key_buffer=16M -O table_cache=128 
           -O sort_buffer=4M -O record_buffer=1M &

If you have little memory and lots of connections, use something like this:

shell> safe_mysqld -O key_buffer=512k -O sort_buffer=100k 
           -O record_buffer=100k &

or even:

shell> safe_mysqld -O key_buffer=512k -O sort_buffer=16k 
           -O table_cache=32 -O record_buffer=8k -O net_buffer=1K &

If there are very many connections, ``swapping problems'' may occur unless mysqld has been configured to use very little memory for each connection. mysqld performs better if you have enough memory for all connections, of course.

Note that if you change an option to mysqld, it remains in effect only for that instance of the server.

To see the effects of a parameter change, do something like this:

shell> mysqld -O key_buffer=32m --help

Make sure that the --help option is last; otherwise, the effect of any options listed after it on the command line will not be reflected in the output.

10.2.4 How MySQL opens and closes tables

table_cache, max_connections and max_tmp_tables affect the maximum number of files the server keeps open. If you increase one or both of these values, you may run up against a limit imposed by your operating system on the per-process number of open file descriptors. However, you can increase the limit on many systems. Consult your OS documentation to find out how to do this, because the method for changing the limit varies widely from system to system.

table_cache is related to max_connections. For example, for 200 open connections, you should have a table cache of at least 200 * n, where n is the maximum number of tables in a join.

The cache of open tables can grow to a maximum of table_cache (default 64; this can be changed with with the -O table_cache=# option to mysqld). A table is never closed, except when the cache is full and another thread tries to open a table or if you use mysqladmin refresh or mysqladmin flush-tables.

When the table cache fills up, the server uses the following procedure to locate a cache entry to use:

  • Tables that are not currently in use are released, in least-recently-used order.
  • If the cache is full and no tables can be released, but a new table needs to be opened, the cache is temporarily extended as necessary.
  • If the cache is in a temporarily-extended state and a table goes from in-use to not-in-use state, it is closed and released from the cache.

A table is opened for each concurrent access. This means that if you have two threads accessing the same table or access the table twice in the same query (with AS) the table needs to be opened twice. The first open of any table takes two file descriptors; each additional use of the table takes only one file descriptor. The extra descriptor for the first open is used for the index file; this descriptor is shared among all threads.

10.2.5 Drawbacks of creating large numbers of tables in the same database

If you have many files in a directory, open, close and create operations will be slow. If you execute SELECT statements on many different tables, there will be a little overhead when the table cache is full, because for every table that has to be opened, another must be closed. You can reduce this overhead by making the table cache larger.

10.2.6 Why so many open tables?

When you run mysqladmin status, you'll see something like this:

Uptime: 426 Running threads: 1 Questions: 11082 Reloads: 1 Open tables: 12

This can be somewhat perplexing if you only have 6 tables.

MySQL is multithreaded, so it may have many queries on the same table simultaneously. To minimize the problem with two threads having different states on the same file, the table is opened independently by each concurrent thread. This takes some memory and one extra file descriptor for the data file. The index file descriptor is shared between all threads.

10.2.7 How MySQL uses memory

The list below indicates some of the ways that the mysqld server uses memory. Where applicable, the name of the server variable relevant to the memory use is given.

  • The key buffer (variable key_buffer_size) is shared by all threads; Other buffers used by the server are allocated as needed. See section 10.2.3 Tuning server parameters.
  • Each connection uses some thread specific space; A stack (default 64K, variable thread_stack) a connection buffer (variable net_buffer_length), and a result buffer (variable net_buffer_length). The connection buffer and result buffer are dynamically enlarged up to max_allowed_packet when needed. When a query is running a copy of the current query string is also allocated.
  • All threads share the same base memory.
  • Nothing is memory-mapped yet (except compressed tables, but that's another story). This is because the 32-bit memory space of 4GB is not large enough for most large tables. When systems with a 64-bit address-space become more common we may add general support for memory-mapping.
  • Each request doing a sequential scan over a table allocates a read buffer (variable record_buffer).
  • All joins are done in one pass and most joins can be done without even using a temporary table. Most temporary tables are memory-based (HEAP) tables. Temporary tables with a big record length (calculated as the sum of all column lengths) or that contain BLOB columns are stored on disk. One problem in MySQL versions before 3.23.2 is that if a HEAP table exceeds the size of tmp_table_size, you get the error The table tbl_name is full. In newer versions this is handled by automatically changing the in-memory (HEAP) table to a disk-based (MyISAM) table as necessary. To work around this problem, you can increase the temporary table size by setting the tmp_table_size option to mysqld, or by setting the SQL option SQL_BIG_TABLES in the client program. See section 7.25 SET OPTION syntax. In MySQL 3.20, the maximum size of the temporary table was record_buffer*16, so if you are using this version, you have to increase the value of record_buffer. You can also start mysqld with the --big-tables option to always store temporary tables on disk, however, this will affect the speed of many complicated queries.
  • Most requests doing a sort allocate a sort buffer and one or two temporary files. See section 18.5 Where MySQL stores temporary files.
  • Almost all parsing and calculating is done in a local memory store. No memory overhead is needed for small items and the normal slow memory allocation and freeing is avoided. Memory is allocated only for unexpectedly large strings (this is done with malloc() and free()).
  • Each index file is opened once and the data file is opened once for each concurrently-running thread. For each concurrent thread, a table structure, column structures for each column, and a buffer of size 3 * n is allocated (where n is the maximum row length, not counting BLOB columns). A BLOB uses 5 to 8 bytes plus the length of the BLOB data.
  • For each table having BLOB columns, a buffer is enlarged dynamically to read in larger BLOB values. If you scan a table, a buffer as large as the largest BLOB value is allocated.
  • Table handlers for all in-use tables are saved in a cache and managed as a FIFO. Normally the cache has 64 entries. If a table has been used by two running threads at the same time, the cache contains two entries for the table. See section 10.2.4 How MySQL opens and closes tables.
  • A mysqladmin flush-tables command closes all tables that are not in use and marks all in-use tables to be closed when the currently executing thread finishes. This will effectively free most in-use memory.

ps and other system status programs may report that mysqld uses a lot of memory. This may be caused by thread-stacks on different memory addresses. For example, the Solaris version of ps counts the unused memory between stacks as used memory. You can verify this by checking available swap with swap -s. We have tested mysqld with commercial memory-leakage detectors, so there should be no memory leaks.

10.2.8 How MySQL locks tables

All locking in MySQL is deadlock-free. This is managed by always requesting all needed locks at once at the beginning of a query and always locking the tables in the same order.

The locking method MySQL uses for WRITE locks works as follows:

  • If there are no locks on the table, put a write lock on it.
  • Otherwise, put the lock request in the write lock queue.

The locking method MySQL uses for READ locks works as follows:

  • If there are no write locks on the table, put a read lock on it.
  • Otherwise, put the lock request in the read lock queue.

When a lock is released, the lock is made available to the threads in the write lock queue, then to the threads in the read lock queue.

This means that if you have many updates on a table, SELECT statements will wait until there are no more updates.

To work around this for the case where you want to do many INSERT and SELECT operations on a table, you can insert rows in a temporary table and update the real table with the records from the temporary table once in a while.

This can be done with the following code:

mysql> LOCK TABLES real_table WRITE, insert_table WRITE;
mysql> insert into real_table select * from insert_table;
mysql> delete from insert_table;
mysql> UNLOCK TABLES;

You can use the LOW_PRIORITY options with INSERT if you want to prioritize retrieval in some specific cases. See section 7.14 INSERT syntax.

You could also change the locking code in `mysys/thr_lock.c' to use a single queue. In this case, write locks and read locks would have the same priority, which might help some applications.

10.2.9 Table locking issues

The table locking code in MySQL is deadlock free.

MySQL uses table locking (instead of row locking or column locking) to achieve a very high lock speed. For large tables, table locking is for most applications MUCH better than row locking, but there are of course some pitfalls.

In MySQL 3.23.7 and above, you can insert rows into MyISAM tables at the same time as other threads are reading from the table. Note that currently this only works if there are no deleted rows in the table.

Table locking enables many threads to read from a table at the same time, but if a thread wants to write to a table, it must first get exclusive access. During the update all others threads that want to access this particular table will wait until the update is ready.

As updates of databases normally are considered to be more important than SELECT, all statements that update a table have higher priority than statements that retrieve information from a table. This should ensure that updates are not 'starved' because one issues a lot of heavy queries against a specific table.

Starting from MySQL 3.23.7 one can use the max_write_lock_count variable to force MySQL to issue a SELECT after a specific number of inserts on a table.

One main problem with this is the following:

  • A client issues a SELECT that takes a long time to run.
  • Another client then issues an UPDATE on a used table; This client will wait until the SELECT is finished
  • Another client issues another SELECT statement on the same table; As UPDATE has higher priority than SELECT, this SELECT will wait for the UPDATE to finish. It will also wait for the first SELECT to finish!

Some possible solutions to this problem are:

  • Try to get the SELECT statements to run faster; You may have to create some summary tables to do this.
  • Start mysqld with --low-priority-updates. This will give all statements that update (modify) a table lower priority than a SELECT statement. In this case the last SELECT statement in the previous scenario would execute before the INSERT statement.
  • You can give a specific INSERT,UPDATE or DELETE statement lower priority with the LOW_PRIORITY attribute.
  • Start mysqld with a low value for max_write_lock_count to give READ locks after a certain number of WRITE locks.
  • You can specify that all updates from a specific thread should be done with low priority by using the SQL command: SET SQL_LOW_PRIORITY_UPDATES=1. See section 7.25 SET OPTION syntax.
  • You can specify that a specific SELECT is very important with the HIGH_PRIORITY attribute. See section 7.12 SELECT syntax.
  • If you have problems with INSERT combined with SELECT, switch to use the new MyISAM tables as these supports concurrent SELECTs and INSERTs.
  • If you mainly mix INSERT and SELECT statements, the DELAYED attribute to INSERT will probably solve your problems. See section 7.14 INSERT syntax.
  • If you have problems with SELECT and DELETE, the LIMIT option to DELETE may help. See section 7.11 DELETE syntax.

10.3 Get your data as small as possible

One of the most basic optimization is to get your data (and indexes) to take as little space on the disk (and in memory) as possible. This can give huge improvements since disk reads are faster and normally less main memory will also be used. Indexing also takes less resources if done on smaller columns.

You can get better performance on a table and minimize storage space using the techniques listed below:

  • Use the most efficient (smallest) types possible. MySQL has a many specialized types that save disk space and memory.
  • Use the smaller integer types if possible to get smaller tables. For example, MEDIUMINT is often better than INT.
  • Declare columns to be NOT NULL if possible. It makes everything faster and you save one bit per column. Note that if you really need NULL in your application you should definitely use it. Just avoid haveing it on all columns by default.
  • If you don't have any variable-length columns (VARCHAR, TEXT or BLOB columns), a fixed-size record format is used. This is faster but unfortunately may waste some space. See section 10.6 Choosing a table type.
  • Each table should have as short as possible primary index. This makes identification of one row easy and efficient.
  • For each table you have to decide which storage/index method to use. See section 9.4 MySQL table types. See also See section 10.6 Choosing a table type.
  • Only create the indexes that you really need. Indexes are good for retrieval but bad when you need to store things fast. If you mostly access a table by searching on a combination of columns, make an index on them. The first index part should be the most used column. If you are ALWAYS using many columns you should use the column with more duplicates first to get better compression of the index.
  • If its very likely that an index has unique prefix on the first number of characters, it's better that only index this prefix. MySQL supports an index on a part of a character column. Shorter indexes is faster not only because they take less disk space but also because they will give you more hits in the index cache and thus fewer disk seeks. See section 10.2.3 Tuning server parameters.
  • In some circumstances it can be beneficial to split a table that is scanned very often into two. Especially if it is a dynamic format table and it is possible to a smaller static format table that can be used to find the relevant rows then scanning.

10.4 MySQL index use

Indexes are used to find find a row with a specific calue on one column fast. Without a index MySQL has to start with the first record and then read through the whole table until it find the relevent rows. The bigger the table the more this costs. If the table has a index for the colums in question MySQL can get fast a possition to seek to in the middle of the data file without having to look at all data. If a table have 1000 rows this is at least 100 times faster than reading sequentially. Note that is you need to access almost all 1000 rows it is faster to read sequentially since we when avoid disk seeks.

All MySQL indexes (PRIMARY, UNIQUE and INDEX) are stored in B-trees. Strings are automatically prefix- and end-space compressed. See section 7.27 CREATE INDEX syntax.

Indexes are used to:

  • Quickly find the rows that match a WHERE clause.
  • Retrieve rows from other tables when performing joins.
  • Find the MAX() or MIN() value for a specific indexed column.
  • Sort or group a table if the sorting or grouping is done on a leftmost prefix of a usable key (e.g., ORDER BY key_part_1,key_part_2 ). The key is read in reverse order if all key parts are followed by DESC.
  • In some cases a querey can be optimized to retrieve values without consulting the data file. If all used columns for some table are numeric and form a leftmost prefix for some key, the values may be retrieved from the index tree for greater speed.

Suppose you issue the following SELECT statement:

mysql> SELECT * FROM tbl_name WHERE col1=val1 AND col2=val2;

If a multiple-column index exists on col1 and col2, the appropriate rows can be fetched directly. If separate single-column indexes exist on col1 and col2, the optimizer tries to find the most restrictive index by deciding which index will find fewer rows and using that index to fetch the rows.

If the table has a multiple-column index, any leftmost prefix of the index can be used by the optimizer to find rows. For example, if you have a three-column index on (col1,col2,col3), you have indexed search capabilities on (col1), (col1,col2) and (col1,col2,col3).

MySQL can't use a partial index if the columns don't form a leftmost prefix of the index. Suppose you have the SELECT statements shown below:

mysql> SELECT * FROM tbl_name WHERE col1=val1;
mysql> SELECT * FROM tbl_name WHERE col2=val2;
mysql> SELECT * FROM tbl_name WHERE col2=val2 AND col3=val3;

If an index exists on (col1,col2,col3), only the first query shown above uses the index. The second and third queries do involve indexed columns, but (col2) and (col2,col3) are not leftmost prefixes of (col1,col2,col3).

MySQL also uses indexes for LIKE comparisons if the argument to LIKE is a constant string that doesn't start with a wildcard character. For example, the following SELECT statements use indexes:

mysql> select * from tbl_name where key_col LIKE "Patrick%";
mysql> select * from tbl_name where key_col LIKE "Pat%_ck%";

In the first statement, only rows with "Patrick" <= key_col < "Patricl" are considered. In the second statement, only rows with "Pat" <= key_col < "Pau" are considered.

The following SELECT statements will not use indexes:

mysql> select * from tbl_name where key_col LIKE "%Patrick%";
mysql> select * from tbl_name where key_col LIKE other_col;

In the first statement, the LIKE value begins with a wildcard character. In the second statement, the LIKE value is not a constant.

Searching using column_name IS NULL will use indexes if column_name is a index.

MySQL normally uses the index that finds least number of rows. An index is used for columns that you compare with the following operators: =, >, >=, <, <=, BETWEEN and a LIKE with a non-wildcard prefix like 'something%'.

Any index that doesn't span all AND levels in the WHERE clause is not used to optimize the query. In other words: To be able to use an index, a prefix of the index must be used in every AND group.

The following WHERE clauses use indexes:

... WHERE index_part1=1 AND index_part2=2 AND other_column=3
... WHERE index=1 OR A=10 AND index=2      /* index = 1 OR index = 2 */
... WHERE index_part1='hello' AND index_part_3=5
          /* optimized like "index_part1='hello'" */
... WHERE index1=1 and index2=2 or index1=3 and index3=3;
          /* Can use index on index1 but not on index2 or index 3 */

These WHERE clauses do NOT use indexes:

... WHERE index_part2=1 AND index_part3=2  /* index_part_1 is not used */
... WHERE index=1 OR A=10                  /* Index is not used in both AND parts */
... WHERE index_part1=1 OR index_part2=10  /* No index spans all rows */

10.5 Speed of queries that access or update data

First, one thing that affects all queries: The more complex permission system setup you have, the more overhead you get.

If you do not have any GRANT statements done MySQL will optimize the permission checking somewhat. So if you have a very high volume it may be worth the time to avoid grants. Otherwise more permission check results in a larger overhead.

If your problem is with some explicit MySQL function, you can always time this in the MySQL client:

mysql> select benchmark(1000000,1+1);
+------------------------+
| benchmark(1000000,1+1) |
+------------------------+
|                      0 |
+------------------------+
1 row in set (0.32 sec)

The above shows that MySQL can execute 1,000,000 + expressions in 0.32 seconds on a PentiumII 400MHz.

All MySQL functions should be very optimized, but there may be some exceptions and the benchmark(loop_count,expression) is a great tool to find if this is a problem with your query.

10.5.1 Estimating query performance

In most cases you can estimate the performance by counting disk seeks. For small tables you can usually find the row in 1 disk seek (as the index is probably cached). For bigger tables, you can estimate that, (using B++ tree indexes), you will need: log(row_count) / log(index_block_length / 3 * 2 / (index_length + data_pointer_length)) + 1 seeks to find a row.

In MySQL an index block is usually 1024 bytes and the data pointer is usually 4 bytes, which gives for a 500,000 row table with a index length of 3 (medium integer) gives you: log(500,000)/log(1024/3*2/(3+4)) + 1 = 4 seeks.

As the above index would require about 500,000 * 7 * 3/2 = 5.2M, (assuming that the index buffers are filled to 2/3 (which is typical) you will probably have much of the index in memory and you will probably only need 1-2 calls to read data from the OS to find the row.

For writes you will however need 4 seek requests (as above) to find where to place the new index and normally 2 seeks to update the index and write the row.

Note that the above doesn't mean that your application will slowly degenerate by N log N! As long as everything is cached by the OS or SQL server things will only go marginally slower while the table gets bigger. After the data gets too big to be cached, things will start to go much slower until your applications is only bound by disk-seeks (which increase by N log N). To avoid this increase the index cache as the data grows. See section 10.2.3 Tuning server parameters.

10.5.2 Speed of SELECT queries

In general, when you want to make a slow SELECT ... WHERE faster, the first thing to check is whether or not you can add an index. See section 10.4 MySQL index use. All references between different tables should usually be done with indexes. You can use the EXPLAIN command to determine which indexes are used for a SELECT. See section 7.22 EXPLAIN syntax (Get information about a SELECT).

Some general tips:

  • To help MySQL optimize queries better, run myisamchk --analyze on a table after it has been loaded with relevant data. This updates a value for each index that indicates the average number of rows that have the same value. (For unique indexes, this is always 1, of course.)
  • To sort an index and data according to an index, use myisamchk --sort-index --sort-records=1 (if you want to sort on index 1). If you have a unique index from which you want to read all records in order according to that index, this is a good way to make that faster. Note however that this sorting isn't written optimally and will take a long time for a large table!

10.5.3 How MySQL optimizes WHERE clauses

The where optimizes are put in the SELECT part here since they are mostly used there. But the same optimizations are used for there in DELETE and UPDATE statements.

Also note that this section is incomplete. MySQL does many optimizations and we have not had time to document them all.

Some of the optimizations performed by MySQL are listed below:

  • Removal of unnecessary parentheses:
       ((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:
       (a<b AND b=c) AND a=5
    -> b>5 AND b=c AND a=5
    
  • Constant condition removal (needed because of constant folding):
       (B>=5 AND B=5) OR (B=6 AND 5=5) OR (B=7 AND 5=6)
    -> B=5 OR B=6
    
  • Constant expressions used by indexes are evaluated only once.
  • COUNT(*) on a single table without a WHERE is retrieved directly from the table information. This is also done for any NOT NULL expression when used with only one table.
  • Early detection of invalid constant expressions. MySQL quickly detects that some SELECT statements are impossible and returns no rows.
  • HAVING is merged with WHERE if you don't use GROUP BY or group functions (COUNT(), MIN()...)
  • For each sub join, a simpler WHERE is constructed to get a fast WHERE evaluation for each sub join and also to skip records as soon as possible.
  • All constant tables are read first, before any other tables in the query. A constant table is:
    • An empty table or a table with 1 row.
    • A table that is used with a WHERE clause on a UNIQUE index, or a PRIMARY KEY, where all index parts are used with constant expressions and the index parts are defined as NOT NULL.
    All the following tables are used as constant tables:
    mysql> SELECT * FROM t WHERE primary_key=1;
    mysql> SELECT * FROM t1,t2
               WHERE t1.primary_key=1 AND t2.primary_key=t1.id;
    
  • The best join combination to join the tables is found by trying all possibilities :(. If all columns in ORDER BY and in GROUP BY come from the same table, then this table is preferred first when joining.
  • If there is an ORDER BY clause and a different GROUP BY clause, or if the ORDER BY or GROUP BY contains columns from tables other than the first table in the join queue, a temporary table is created.
  • If you use SQL_SMALL_RESULT, MySQL will use an in-memory temporary table.
  • As DISTINCT is converted to a GROUP BY on all columns, DISTINCT combined with ORDER BY will in many cases also need a temporary table.
  • Each table index is queried and the best index that spans fewer than 30% of the rows is used. If no such index can be found, a quick table scan is used.
  • 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, then only the index tree is used to resolve the query.
  • Before each record is output, those that do not match the HAVING clause are skipped.

Some examples of queries that are very fast:

mysql> SELECT COUNT(*) FROM tbl_name;
mysql> SELECT MIN(key_part1),MAX(key_part1) FROM tbl_name;
mysql> SELECT MAX(key_part2) FROM tbl_name
           WHERE key_part_1=constant;
mysql> SELECT ... FROM tbl_name
           ORDER BY key_part1,key_part2,... LIMIT 10;
mysql> SELECT ... FROM tbl_name
           ORDER BY key_part1 DESC,key_part2 DESC,... LIMIT 10;

The following queries are resolved using only the index tree (assuming the indexed columns are numeric):

mysql> SELECT key_part1,key_part2 FROM tbl_name WHERE key_part1=val;
mysql> SELECT COUNT(*) FROM tbl_name
           WHERE key_part1=val1 AND key_part2=val2;
mysql> SELECT key_part2 FROM tbl_name GROUP BY key_part1;

The following queries use indexing to retrieve the rows in sorted order without a separate sorting pass:

mysql> SELECT ... FROM tbl_name ORDER BY key_part1,key_part2,...
mysql> SELECT ... FROM tbl_name ORDER BY key_part1 DESC,key_part2 DESC,...

10.5.4 How MySQL optimizes LEFT JOIN

A LEFT JOIN B is in MySQL implemented as follows

  • The table B is set to be dependent on table A.
  • The table A is set to be dependent on all tables (except B) that are used in the LEFT JOIN condition.
  • All LEFT JOIN conditions are moved to the WHERE clause.
  • All standard join optimizations are done, with the exception that a table is always read after all tables it is dependent on. If there is a circular dependence then MySQL will issue an error.
  • All standard WHERE optimzations are done.
  • If there is a row in A that matches the WHERE clause, but there wasn't any row in B that matched the LEFT JOIN condition, then an extra B row is generated with all columns set to NULL.
  • If you use LEFT JOIN to find rows that doesn't exist in some table and you have the following test: column_name IS NULL in the WHERE part, where column_name is a column that is declared as NOT NULL, then MySQL will stop searching after more rows (for a particular key combination) after it has found one row that matches the LEFT JOIN condition.

10.5.5 How MySQL optimizes LIMIT

In some cases MySQL will handle the query differently when you are using LIMIT # and not using HAVING:

  • If you are selecting only a few rows with LIMIT, MySQL will use indexes in some cases when it normally would prefer to do a full table scan.
  • If you use LIMIT # with ORDER BY, MySQL will end the sorting as soon as it has found the first # lines instead of sorting the whole table.
  • When combining LIMIT # with DISTINCT, MySQL will stop as soon as it finds # unique rows.
  • In some cases a GROUP BY can be resolved by reading the key in order (or do a sort on the key) and then calculate summaries until the key value changes. In this case LIMIT # will not calculate any unnecessary GROUP's.
  • As soon as MySQL has sent the first # rows to the client, it will abort the query.
  • LIMIT 0 will always quickly return an empty set. This is useful to check the query and to get the column types of the result columns.
  • The size of temporary tables uses the LIMIT # to calculate how much space is needed to resolve the query.

10.5.6 Speed of INSERT queries

The time to insert a record consists approximately of:

  • Connect: (3)
  • Sending query to server: (2)
  • Parsing query: (2)
  • Inserting record: (1 x size of record)
  • Inserting indexes: (1 x number of indexes)
  • Close: (1)

Where the numbers are somewhat proportional to the overall time. This does not take into consideration the initial overhead to open tables (which is done once for each concurrently-running query).

The size of the table slows down the insertion of indexes by N log N (B-trees).

Some ways to speed up inserts:

  • If you are inserting many rows from the same client at the same time use multiple value lists INSERT statements. This is much faster (many times in some cases) than using separate INSERT statements.
  • If you are inserting a lot of rows from different clients, you can get higher speed by using the INSERT DELAYED statement. See section 7.14 INSERT syntax.
  • Note that with MyISAM you can insert rows at the same time SELECTs are running if there are no deleted rows in the tables.
  • When loading a table from a text file, use LOAD DATA INFILE. This is usually 20 times faster than using a lot of INSERT statements. See section 7.16 LOAD DATA INFILE syntax.
  • It is possible with some extra work to make LOAD DATA INFILE run even faster when the table has many indexes. Use the following procedure:
    1. Optionally create the table with CREATE TABLE. For example using mysql or Perl-DBI.
    2. Execute a FLUSH TABLES statement or the shell command mysqladmin flush-tables.
    3. Use myisamchk --keys-used=0 -rq /path/to/db/tbl_name. This will remove all usage of all indexes from the table.
    4. Insert data into the table with LOAD DATA INFILE. This will not update any indexes and will therefore be very fast.
    5. If you have myisampack and want to compress the table, run myisampack on it. See section 10.6.3 Compressed table characteristics.
    6. Recreate the indexes with myisamchk -r -q /path/to/db/tbl_name. This will create the index tree in memory before writing it to disk, which is much faster since it avoid lots of disk seeks. The resulting index tree is also perfectly balanced.
    7. Execute a FLUSH TABLES statement or the shell command mysqladmin flush-tables.
    This procedure will be built into LOAD DATA INFILE in some future version of MySQL.
  • You can speed up insertions by locking your tables:
    mysql> LOCK TABLES a WRITE;
    mysql> INSERT INTO a VALUES (1,23),(2,34),(4,33);
    mysql> INSERT INTO a VALUES (8,26),(6,29);
    mysql> UNLOCK TABLES;
    
    The main speed difference is that the index buffer is flushed to disk only once, after all INSERT statements have completed. Normally there would be as many index buffer flushes as there are different INSERT statements. Locking is not needed if you can insert all rows with a single statement. Locking will also lower the total time of multi-connection tests, but the maximum wait time for some threads will go up (because they wait for locks). For example:
    thread 1 does 1000 inserts
    thread 2, 3, and 4 does 1 insert
    thread 5 does 1000 inserts
    
    If you don't use locking, 2, 3 and 4 will finish before 1 and 5. If you use locking, 2, 3 and 4 probably will not finish before 1 or 5, but the total time should be about 40% faster. As INSERT, UPDATE and DELETE operations are very fast in MySQL, you will obtain better overall performance by adding locks around everything that does more than about 5 inserts or updates in a row. If you do very many inserts in a row, you could do a LOCK TABLES followed by a UNLOCK TABLES once in a while (about each 1000 rows) to allow other threads access to the table. This would still result in a nice performance gain. Of course, LOAD DATA INFILE is much faster still for loading data.

To get some more speed for both LOAD DATA INFILE and INSERT, enlarge the key buffer. See section 10.2.3 Tuning server parameters.

10.5.7 Speed of UPDATE queries

Update queries are optimized as a SELECT query with the additional overhead of a write. The speed of the write is dependent on the size of the data that are being updated and the number of indexes that are updated. Indexes that are not changed will not be updated.

Also another way to get fast updates is to delay updates and then do many updates in a row later. Doing many updates in a row is much quicker than doing one at a time if you lock the table.

Not that with dynamic record format updating a record with to a longer total length may split the record. So if you do this often it is very important to OPTIMIZE TABLE sometimes. See section 7.9 OPTIMIZE TABLE syntax.

10.5.8 Speed of DELETE queries

The time to delete a record is exactly proportional to the number of indexes. To delete records more quickly, you can increase the size of the index cache. See section 10.2.3 Tuning server parameters.

Its also much faster to remove all rows than to remove a big part of the rows from a table.

10.6 Choosing a table type

With MySQL you can currently (version 3.23.5) choose between four usable table formats from a speed point of view.

MyISAM Static
This format is the simplest and most secure format. It is also the fastest of the on disk formats. The speed comes from the easy way data can be found on disk. When looking up something with a index and static format it very simple, just multiply the row number with the row length. Also when scanning a table it is very easy to read a constant number of records with each disk read. The security comes from if your computer crashes when writing to a static MyISAM file, myisamchk can easily figure out where each row starts and ends. So it can usually reclaim all records except the partially written one. Not that in MySQL all indexes can always be reconstructed.
MyISAM Dynamic
This format is a litte more complex since each row has to have a header that says how long it is. One record can also end up at more that one location when it is made longer at a update. You can use OPTIMIZE table or myisamchk to defragment a table. If you have static data that you acess/change a lot in the same table as some VARCHAR or BLOB columns, it might be a good idea to move the dynamic columns to other tables just to avoid fragmentation.
MyISAM compressed
This is a read only type that is generated with the optional myisampack tool.
In memory (HEAP)
This table format is extremely useful for small/medium sized lookup tables. It is possible to copy/create a frequently used lookup table (in joins) to a (maybe temporary) HEAP table to speed up many joins. Suppose we want to do the following join many times with the same data.
SELECT tab1.a, tab3.a FROM tab1, tab2, tab3
        WHERE tab1.a = tab2.a and tab2.a = tab3.a and tab2.c != 0;
To speed this up we could create a temporary table with the join of tab2 and tab3 since that are looked up using the same column (tab1.a). Here is the command to create that table and the resulting select.
CREATE TEMPORARY TABLE test TYPE=HEAP
        SELECT
                tab2.a as a2, tab3.a as a3
        FROM
                tab2, tab3
        WHERE
                tab2.a = tab3.a and c = 0;
SELECT tab1.a, test.a3 from tab1, test where tab1.a = test.a2;
SELECT tab1.b, test.a3 from tab1, test where tab1.a = test.a2 and something;

10.6.1 Static (Fixed-length) table characteristics

  • This is the default format. It's used when the table contains no VARCHAR, BLOB or TEXT columns.
  • All CHAR, NUMERIC and DECIMAL columns are space-padded to the column width.
  • Very quick.
  • Easy to cache.
  • Easy to reconstruct after a crash, because records are located in fixed positions.
  • Doesn't have to be reorganized (with myisamchk) unless a huge number of records are deleted and you want to return free disk space to the operating system.
  • Usually requires more disk space than dynamic tables.

10.6.2 Dynamic table characteristics

  • This format is used if the table contains any VARCHAR, BLOB or TEXT columns.
  • All string columns are dynamic (except those with a length less than 4).
  • Each record is preceded by a bitmap indicating which columns are empty ('') for string columns, or zero for numeric columns (this isn't the same as columns containing NULL values). If a string column has a length of zero after removal of trailing spaces, or a numeric column has a value of zero, it is marked in the bit map and not saved to disk. Non-empty strings are saved as a length byte plus the string contents.
  • Usually takes much less disk space than fixed-length tables.
  • Each record uses only as much space as is required. If a record becomes larger, it is split into as many pieces as required. This results in record fragmentation.
  • If you update a row with information that extends the row length, the row will be fragmented. In this case, you may have to run myisamchk -r from time to time to get better performance. Use myisamchk -ei tbl_name for some statistics.
  • Not as easy to reconstruct after a crash, because a record may be fragmented into many pieces and a link (fragment) may be missing.
  • The expected row length for dynamic sized records is:
    3
    + (number of columns + 7) / 8
    + (number of char columns)
    + packed size of numeric columns
    + length of strings
    + (number of NULL columns + 7) / 8
    
    There is a penalty of 6 bytes for each link. A dynamic record is linked whenever an update causes an enlargement of the record. Each new link will be at least 20 bytes, so the next enlargement will probably go in the same link. If not, there will be another link. You may check how many links there are with myisamchk -ed. All links may be removed with myisamchk -r.

10.6.3 Compressed table characteristics

  • A read-only table made with the myisampack utility. All customers with extended MySQL email support are entitled to a copy of myisampack for their internal usage.
  • The uncompress code exists in all MySQL distributions so that even customers who don't have myisampack can read tables that were compressed with myisampack
  • Takes very little disk space. Minimises disk usage.
  • Each record is compressed separately (very little access overhead). The header for a record is fixed (1-3 bytes) depending on the biggest record in the table. Each column is compressed differently. Some of the compression types are:
    • There is usually a different Huffman table for each column.
    • Suffix space compression.
    • Prefix space compression.
    • Numbers with value 0 are stored using 1 bit.
    • If values in an integer column have a small range, the column is stored using the smallest possible type. For example, a BIGINT column (8 bytes) may be stored as a TINYINT column (1 byte) if all values are in the range 0 to 255.
    • If a column has only a small set of possible values, the column type is converted to ENUM.
    • A column may use a combination of the above compressions.
  • Can handle fixed or dynamic length records, but not BLOB or TEXT columns.
  • Can be uncompressed with myisamchk.

MySQL can support different index types, but the normal type is ISAM. This is a B-tree index and you can roughly calculate the size for the index file as (key_length+4)*0.67, summed over all keys. (This is for the worst case when all keys are inserted in sorted order.)

String indexes are space compressed. If the first index part is a string, it will also be prefix compressed. Space compression makes the index file smaller if the string column has a lot of trailing space or is a VARCHAR column that is not always used to the full length. Prefix compression helps if there are many strings with an identical prefix.

10.6.4 In memory table characteristics

HEAP tables only exists in memory so they are lost if mysqld is taken down or crashes. But since they are very fast they are usefull as anyway.

The MySQL internal HEAP tables uses 100% dynamic hashing without overflow areas and don't have problems with delete.

You can only access things by equality using a index (usually by the = operator) whith a heap table.

The downside with HEAPS are:

  1. You need enough extra memory for all HEAP tables that you want to use at the same time.
  2. You can't search on a part of a index.
  3. You can't search for the next entry in order (that is to use the index to do a ORDER BY).
  4. MySQL also cannot find out how approximately many rows there are between two values. This is used by the optimizer to chose which index to use. But on the other hand no disk seeks are even needed.

10.7 Other optimization tips

Unsorted tips for faster systems:

  • Use persistent connections to the database to avoid the connection over head.
  • Always check that all your queries really uses the indexes you have created in the tables. In MySQL you can do this with the EXPLAIN command. See section 7.22 EXPLAIN syntax (Get information about a SELECT).
  • Try to avoid complex SELECT queries on tables that are updated a lot. This is to avoid problems with table locking.
  • The new MyISAM tables can insert rows in a table without deleted rows at the same time another table is reading from it. If this is important for you, you should consider methods where you don't have to delete rows or run OPTIMIZE TABLE after you have deleted a lot of rows.
  • In some cases it may make sense to introduce a column that is 'hashed' based on information from other columns. If this column is short and reasonable unique it may be much faster than a big index on many columns. In MySQL its very easy to use this extra column: SELECT * from table where hash='calculated hash on col1 and col2' and col_1='constant' and col_2='constant' and ..
  • For tables that changes a lot you should try to avoid all VARCHAR or BLOB columns. You will get dynamic row length as soon as you are using a single VARCHAR or BLOB columns. See section 9.4 MySQL table types.
  • It's not normally useful to split a table into different tables just because the rows gets 'big'. To access a row, the biggest performance hit is the disk seek to find the first byte of the row. After finding the data most new disks can read the whole row fast enough for most applications. The only cases it really matters to split up a table is if its a dynamic row size table (see above) that you can change to a fixed row size. Or if you very often need to scan the table and don't need most of the columns. See section 9.4 MySQL table types.
  • If you very often need to calculate things based on information from a lot of rows (like counts of things) it's probably much better to introduce a new table and update the counter in real time. An update of type UPDATE table set count=count+1 where index_column=constant is very fast! This is really important when you use databases like MySQL that only has table locking (multiple readers / single writers). This will also give better performance with most databases as the row locking manager in this case will have less to do.
  • If you need to collect statistics from big log tables use summary tables instead of scanning the whole table. Maintaing the summarys should be much faster than trying to do statistics 'live'. It's much faster to re-generate new summary tables from the logs when things changes (depending on business decisions) than to have to change the running application!
  • If possible one should classify reports as 'live' or 'statistical', where data needed for statistical reports are only generated based on summary tables that are generated from the actual data.
  • Take advantage of the fact that columns have default values. Insert values explicitly only when the value to be inserted differs from the default. This reduces the parsing that MySQL need to do and improves the insert speed.
  • In some cases its convenient to pack and store data into a blob In this case you have to add some extra code in your appliction to pack/unpack things in the blob but this may save a lot of accesses at some stage. This is practical when you have data that doesn't conform to a static table structure.
  • Normally you should try to keep all data non-redundant (what is called 3rd normal form in database theory), but you should not be afraid of duplicating things or creating summary tables if you need these to gain more speed.
  • Stored procedures or UDF (user defined functions) may be a good way to get more performance. In this case you should however always have a way to do this some other (slower) way if you use some database that doesn't support this.
  • You can always gain something by caching queries/answers in your application and try to do many inserts/updates at the same time. If your database supports lock tables (like MySQL and Oracle), this should help to ensure that the index cache is only flushed once after all updates.
  • Use INSERT /*! DELAYED */ when you do not need to now when your data is written. This speeds things up since many records can be written with a single disk write.
  • Use INSERT /*! LOW_PRIORITY */ when you want your selects are more important.
  • Use SELECT /*! HIGH_PRIORITY */ to get selects that jumps the queue. That is the select is done even if there is somebody waiting to do a write.
  • Use the multi-line INSERT statement to store many rows with one SQL command (many SQL servers supports this)
  • Use LOAD DATA INFILE to load bigger amounts of data. This if faster than normal inserts and will be even faster when myisamchk is integrated in mysqld.
  • Use AUTO_INCREMENT columns to make unique values.
  • Use OPTIMIZE TABLE once in a while to avoid fragmentation when using dynamic table format.See section 7.9 OPTIMIZE TABLE syntax.
  • Use HEAP tables to get more speed when possibe. See section 9.4 MySQL table types.
  • When using a normal Web server setup, images should be stored as files. That is store only a file reference in the database. The main reason for this is that a normal web server is much better at caching files than database contents. So it it's much easier to get a fast system if you are using files.
  • Use in memory tables for not critical data that are accessed often (like information about the last shown banner for users that doesn't have cookies)
  • Columns with identical information in different tables should be declared identical and have identical names. Before version 3.23 you got slow joins otherwise. Try to keep the names simple (use name instead of customer_name in the customer table). To make your names portable to other SQL servers you should keep them shorter than 18 characters.
  • If you need REALLY high speed you should take a look at the low level interfaces for data storage that the different SQL servers support! For example by accessing the MySQL MyISAM directly you could get a speed increase of 2-5 times compared to using the SQL interface. The be able to do this the data must however be on the same server as the application and usually it should only be accessed by on processes (because external file locking is real slow). One could eliminate the above problems by introducing low level MyISAM commands in the MySQL server (this could be one easy way to get more performance if needed). By carefully designing the database interface it should be quite easy to support this types of optimisations.
  • In many cases it's faster to access data from a database (using a live connection) than accessing a text file, just because the database is likely to be more compact than the text file (if you are using numerical data) and this will involve fewer disk accesses. You will also save code because you don't have to parse your text files to find line and column boundaries.
  • You can also use replication to speed things up. See section 19.1 Database replication.
  • Declaring a table with DELAY_KEY_WRITE=1 will make the updating of indexes faster as these are not logged to disk until the file is closed. The downside is that you should run myisamchk on these tables before you start mysqld to ensure that they are ok if something killed mysqld in the middle. As the key information can always be generated from the data you should not lose anything by using DELAY_KEY_WRITE.

10.8 Using your own benchmarks

You should definitely benchmark your application and database to find out where is the bottlenecks. By fixing it (or by replacing the bottleneck with a 'dummy module') you can then easily identify the next bottleneck (and so on). Even if the overall performance for your application is 'good enough' you should at least make a 'plan', for each bottleneck, how to solve it if you someday 'really need it fix it'.

For some example portable becnchmark programs look at the MySQL benchmark suite. See section 11 The MySQL benchmark suite. You can take any program this suite and modify it for your needs. By doing this, you can try different solutions to your problem and test which is really the fastest solution for you.

It is very common that some problems only occur then the system is very heavily loaded. And we have had many customer who contacts us then they have a (tested) system in production and have have got load problems. In every on these cases so far it has been problems with basic design (table scans are NOT good at high load) or OS/Library issues. Most of this would be a LOT easier to fix if the system where not already in production.

To avoid probles like this you should put some effort into benchmarking your whole appliction under the worst possible load!

10.9 Design choices

MySQL keeps row data and index data in separate files. Many (almost all) other databases mix row and index data in the same file. We belive that the MySQL choice is better for a very wide range of modern systems.

Another way to store the row data is to keep the information for each column in a separate area (examples are SDBM and Focus). This will get a performance hit for every query that access more than one column. Since this degenerates so quickly when more that when one columns are accessed we believe that this model is not good for general purpose databases.

The more common case is there the index and data are stored together (like in Oracle/Sybase at all). In this case you will find the row information at the leaf page of the index. The good thing with this layout is that it in many cases (depends on how well the index is cached) saves a disk read. The bad things with this layout is:

Table scanning is much slower since you have to read through the indexes to get at the data.
You loose a lot of space as you must duplicate indexes from the nodes (as you can't store the row in the nodes)
Deletes will degenerate the table over times (as indexes in nodes are usually not updated on delete).
You can't use only the index table to retrieve data for a query.
The index data is harder to cache.

10.10 MySQL design limitations/tradeoffs

Since MySQL uses extremely fast table locking (multiple readers / single writers) the biggest remaining problem is a mix of a steady stream of inserts and slow selects on the same table.

We belive that for a huge number of systems the extremely fast performance in other cases make this choice a win. This case is usually also possible to solve by having multiple copies of the table. But it takes more effort and hardware.

We are also working on some extension to solve this problem for some common application niches.

10.11 Portability

Since all SQL servers implement different parts of SQL it takes work to write portable SQL applications. For very simple selects/inserts it is very easy but the more you need the harder it gets. And if you want a application that is fast with many databases it becomes even harder!

To make a complex application portable you need to choose a number of SQL server that it should work with.

When you can use the MySQL crash-me program/web-page http://www.mysql.com/crash-me-choose.htmy to find functions, types and limits you can use with a selection of database servers. Crash-me now test a long way from everything possible but it still is vґcomprehensive with about 450 things tested.

For example, you shouldn't have longer column names than 18 characters if you want to be able to use Informix or DB2.

Both the MySQL benchmarks and Crash-me programs are very database independent. By taking a look of how we have handled this, you can get a feeling of what you have to do to write your application database independent. The benchmark themselves can be found in the `sql-bench' directory in the MySQL source distribution. They are written in Perl with DBI database interface (which solves the access part of the problem.

See http://www.mysql.com/benchmark.html the results from this benchmark.

As you can see in these results all databases has some weak points. That is they have different design compromises that lead to different behavior.

If you strive for database independence you need to get a good feeling of each SQL servers bottlenecks. MySQL is VERY fast in retrieving and updating things, but will have a problem in mixing slow readers/writers on the same table. Oracle on the other hand has a big problem when you try to access rows that you have recently updated (until they are flushed to disk). Transaction databases in general are not very good in generating summary tables from log tables as in this case row locking is almost useless.

To get your application 'really database independent' you need to define a easy extendable interface through which you manipulate your data. As C++ is available on most systems, it makes sense to use a C++ classes interface to the databases.

If you use some specific feature for some database (like the REPLACE command in MySQL), you should code a method for the other SQL servers to implement the same feature (but slower). With MySQL you can use the /*! */ syntax to add MySQL specific keywords to a query. The code inside /**/ will be treated as a comment (ignored) by most other SQL servers.

If REAL high performance is more important than exactness, like in some web applications. A possibility is to create a application layer that caches all results to give you even higher performance. By just letting old results 'expire' after a while you can keep the cache reasonable fresh. This is quite nice in case of extremely high load, in which case you can dynamicly increase the cache to be bigger and set the expire timeout higher until things gets back to normal.

In this case the table creating information should contain information of the initial size of the cache and how often the table should normally be refreshed.

10.12 What have we used MySQL for?

During MySQL initial development the features of MySQL where made to fit our largest customer. They handle data warehousing for a couple of the biggest retailers in Sweden.

We get from all stores weekly summaries of all bonus card transactions and we are expected to provide useful information for the store owners to help them find how their advertisements campaigns are affecting their customers.

The data is quite huge (about 7 million summary transactions per month) and we have data for 4-10 years that we need to present to the users. We got weekly requests from the customers that they want to get 'instant' access to new reports from this data.

We solved this by storing all information per month in compressed 'transaction' tables. We have a set of simple macros/script that generate summary tables grouped by different criterias (product group, customer id, store ...) from the transaction tables. The reports are web pages that are dynamicly generated by a small perl script that parses a web pages, executes the SQL statements in it and inserts the results. Now we would have used PHP or mod_perl instead but they where not available at that time.

For graphical data we wrote a simple tool in C that can produce gifs based on the result of a SQL query (with some processing of the result). This is also dynamicly executed from the perl script that parses the HTML files.

In most cases a new report can simple by done by copying a existing script and modifying the SQL query in it. In some cases we will need to add more fields to an existing summary table or generate a new one, but this is also quite simply as we keep all transactions tables on disk. (Currently we have at least 50G of transactions tables and 200G of other customer data).

We also let our customers access the summary tables directly with ODBC so that the advanced users can themselves experiment with the data.

We haven't had any problems handling this with quite modest Sun Ultra sparcstation (2x200 Mz). We recently upgrade one of our servers to a 2 CPU 400 Mz Ultra sparc and we are now planing to start handling transactions on the product level, which would mean a 10 fold increase of data. We think we can keep up with this by just adding more disk to our systems.

We are also experimenting with Intel-Linux to be able to get more cpu power cheaper. Now that we have the binary portable database format (new in 3.32) we will start to use this for some parts of the application.

Our initial feelings are that Linux will perform much better on low to medium load but Solaris will perform better when you start to get a a high load because of extrema disk IO, but we don't yet have anything conclusive about this. After some discussion with a Linux Kernel developer this might be a side effect of Linux giving so much resources to the batch job that the interactive performance gets very low. This make the machine feel very slow and unresponsive while big batches are going. Hopefully this will be better handled in future Linux Kernels.


Go to the first, previous, next, last section, table of contents.


  • Главная
  • Новости
  • Новинки
  • Скрипты
  • Форум
  • Ссылки
  • О сайте




  • Emanual.ru – это сайт, посвящённый всем значимым событиям в IT-индустрии: новейшие разработки, уникальные методы и горячие новости! Тонны информации, полезной как для обычных пользователей, так и для самых продвинутых программистов! Интересные обсуждения на актуальные темы и огромная аудитория, которая может быть интересна широкому кругу рекламодателей. У нас вы узнаете всё о компьютерах, базах данных, операционных системах, сетях, инфраструктурах, связях и программированию на популярных языках!
     Copyright © 2001-2020
    Реклама на сайте