14.2. The InnoDB Storage Engine

MySQL 5.0

14.2. The InnoDB Storage Engine

14.2.1. InnoDB Overview

provides MySQL with a transaction-safe ( compliant) storage engine that has commit, rollback, and crash recovery capabilities. does locking on the row level and also provides an Oracle-style consistent non-locking read in statements. These features increase multi-user concurrency and performance. There is no need for lock escalation in because row-level locks fit in very little space. also supports constraints. You can freely mix tables with tables from other MySQL storage engines, even within the same statement.

has been designed for maximum performance when processing large data volumes. Its CPU efficiency is probably not matched by any other disk-based relational database engine.

Fully integrated with MySQL Server, the storage engine maintains its own buffer pool for caching data and indexes in main memory. stores its tables and indexes in a tablespace, which may consist of several files (or raw disk partitions). This is different from, for example, tables where each table is stored using separate files. tables can be of any size even on operating systems where file size is limited to 2GB.

is included in binary distributions by default. The Windows Essentials installer makes the MySQL default storage engine on Windows.

is used in production at numerous large database sites requiring high performance. The famous Internet news site Slashdot.org runs on . Mytrix, Inc. stores over 1TB of data in , and another site handles an average load of 800 inserts/updates per second in .

is published under the same GNU GPL License Version 2 (of June 1991) as MySQL. For more information on MySQL licensing, see http://www.mysql.com/company/legal/licensing/.

Additional resources

14.2.2. InnoDB Contact Information

Contact information for Innobase Oy, producer of the engine:

Web site: http://www.innodb.com/
Email: 
Phone: +358-9-6969 3250 (office)
       +358-40-5617367 (mobile)

Innobase Oy Inc.
World Trade Center Helsinki
Aleksanterinkatu 17
P.O.Box 800
00101 Helsinki
Finland

14.2.3. InnoDB Configuration

The storage engine is enabled by default. If you don't want to use tables, you can add the option to your MySQL option file.

Note: provides MySQL with a transaction-safe ( compliant) storage engine that has commit, rollback, and crash recovery capabilities. However, it cannot do so if the underlying operating system or hardware does not work as advertised. Many operating systems or disk subsystems may delay or reorder write operations to improve performance. On some operating systems, the very system call that should wait until all unwritten data for a file has been flushed — — might actually return before the data has been flushed to stable storage. Because of this, an operating system crash or a power outage may destroy recently committed data, or in the worst case, even corrupt the database because of write operations having been reordered. If data integrity is important to you, you should perform some “pull-the-plug” tests before using anything in production. On Mac OS X 10.3 and up, uses a special file flush method. Under Linux, it is advisable to disable the write-back cache.

On ATAPI hard disks, a command such may work to disable the write-back cache. Beware that some drives or disk controllers may be unable to disable the write-back cache.

Two important disk-based resources managed by the storage engine are its tablespace data files and its log files.

Note: If you specify no configuration options, MySQL creates an auto-extending 10MB data file named and two 5MB log files named and in the MySQL data directory. To get good performance, you should explicitly provide parameters as discussed in the following examples. Naturally, you should edit the settings to suit your hardware and requirements.

The examples shown here are representative. See Section 14.2.4, “ Startup Options and System Variables” for additional information about -related configuration parameters.

To set up the tablespace files, use the option in the section of the option file. On Windows, you can use instead. The value of should be a list of one or more data file specifications. If you name more than one data file, separate them by semicolon (‘’) characters:

innodb_data_file_path=[;]...

For example, a setting that explicitly creates a tablespace having the same characteristics as the default is as follows:

[mysqld]
innodb_data_file_path=ibdata1:10M:autoextend

This setting configures a single 10MB data file named that is auto-extending. No location for the file is given, so by default, creates it in the MySQL data directory.

Sizes are specified using or suffix letters to indicate units of MB or GB.

A tablespace containing a fixed-size 50MB data file named and a 50MB auto-extending file named in the data directory can be configured like this:

[mysqld]
innodb_data_file_path=ibdata1:50M;ibdata2:50M:autoextend

The full syntax for a data file specification includes the filename, its size, and several optional attributes:

:[:autoextend[:max:]]

The attribute and those following can be used only for the last data file in the line.

If you specify the option for the last data file, extends the data file if it runs out of free space in the tablespace. The increment is 8MB at a time by default. It can be modified by changing the system variable.

If the disk becomes full, you might want to add another data file on another disk. Instructions for reconfiguring an existing tablespace are given in Section 14.2.7, “Adding and Removing Data and Log Files”.

is not aware of the filesystem maximum file size, so be cautious on filesystems where the maximum file size is a small value such as 2GB. To specify a maximum size for an auto-extending data file, use the attribute. The following configuration allows to grow up to a limit of 500MB:

[mysqld]
innodb_data_file_path=ibdata1:10M:autoextend:max:500M

creates tablespace files in the MySQL data directory by default. To specify a location explicitly, use the option. For example, to use two files named and but create them in the directory, configure like this:

[mysqld]
innodb_data_home_dir = /ibdata
innodb_data_file_path=ibdata1:50M;ibdata2:50M:autoextend

Note: does not create directories, so make sure that the directory exists before you start the server. This is also true of any log file directories that you configure. Use the Unix or DOS command to create any necessary directories.

forms the directory path for each data file by textually concatenating the value of to the data file name, adding a pathname separator (slash or backslash) between values if necessary. If the option is not mentioned in at all, the default value is the “dot” directory , which means the MySQL data directory. (The MySQL server changes its current working directory to its data directory when it begins executing.)

If you specify as an empty string, you can specify absolute paths for the data files listed in the value. The following example is equivalent to the preceding one:

[mysqld]
innodb_data_home_dir =
innodb_data_file_path=/ibdata/ibdata1:50M;/ibdata/ibdata2:50M:autoextend

A simple example. Suppose that you have a computer with 128MB RAM and one hard disk. The following example shows possible configuration parameters in or for , including the attribute. The example suits most users, both on Unix and Windows, who do not want to distribute data files and log files onto several disks. It creates an auto-extending data file and two log files and in the MySQL data directory. Also, the small archived log file that creates automatically ends up in the data directory.

[mysqld]
# You can write your other MySQL server options here
# ...
# Data files must be able to hold your data and indexes.
# Make sure that you have enough free disk space.
innodb_data_file_path = ibdata1:10M:autoextend
#
# Set buffer pool size to 50-80% of your computer's memory
innodb_buffer_pool_size=70M
innodb_additional_mem_pool_size=10M
#
# Set the log file size to about 25% of the buffer pool size
innodb_log_file_size=20M
innodb_log_buffer_size=8M
#
innodb_flush_log_at_trx_commit=1

Make sure that the MySQL server has the proper access rights to create files in the data directory. More generally, the server must have access rights in any directory where it needs to create data files or log files.

Note that data files must be less than 2GB in some filesystems. The combined size of the log files must be less than 4GB. The combined size of data files must be at least 10MB.

When you create an tablespace for the first time, it is best that you start the MySQL server from the command prompt. then prints the information about the database creation to the screen, so you can see what is happening. For example, on Windows, if mysqld is located in , you can start it like this:

C:\> 

If you do not send server output to the screen, check the server's error log to see what prints during the startup process.

See Section 14.2.5, “Creating the Tablespace”, for an example of what the information displayed by should look like.

You can place options in the group of any option file that your server reads when it starts. The locations for option files are described in Section 4.3.2, “Using Option Files”.

If you installed MySQL on Windows using the installation and configuration wizards, the option file will be the file located in your MySQL installation directory. See Section 2.3.4.14, “The Location of the my.ini File”.

If your PC uses a boot loader where the drive is not the boot drive, your only option is to use the file in your Windows directory (typically or ). You can use the command at the command prompt in a console window to print the value of :

C:\> 
windir=C:\WINDOWS

If you want to make sure that mysqld reads options only from a specific file, you can use the option as the first option on the command line when starting the server:

mysqld --defaults-file=

An advanced example. Suppose that you have a Linux computer with 2GB RAM and three 60GB hard disks at directory paths , and . The following example shows possible configuration parameters in for .

[mysqld]
# You can write your other MySQL server options here
# ...
innodb_data_home_dir =
#
# Data files must be able to hold your data and indexes
innodb_data_file_path = /ibdata/ibdata1:2000M;/dr2/ibdata/ibdata2:2000M:autoextend
#
# Set buffer pool size to 50-80% of your computer's memory,
# but make sure on Linux x86 total memory usage is < 2GB
innodb_buffer_pool_size=1G
innodb_additional_mem_pool_size=20M
innodb_log_group_home_dir = /dr3/iblogs
#
innodb_log_files_in_group = 2
#
# Set the log file size to about 25% of the buffer pool size
innodb_log_file_size=250M
innodb_log_buffer_size=8M
#
innodb_flush_log_at_trx_commit=1
innodb_lock_wait_timeout=50
#
# Uncomment the next lines if you want to use them
#innodb_thread_concurrency=5

In some cases, database performance improves the if all data is not placed on the same physical disk. Putting log files on a different disk from data is very often beneficial for performance. The example illustrates how to do this. It places the two data files on different disks and places the log files on the third disk. fills the tablespace beginning with the first data file. You can also use raw disk partitions (raw devices) as data files, which may speed up I/O. See Section 14.2.3.2, “Using Raw Devices for the Shared Tablespace”.

Warning: On 32-bit GNU/Linux x86, you must be careful not to set memory usage too high. may allow the process heap to grow over thread stacks, which crashes your server. It is a risk if the value of the following expression is close to or exceeds 2GB:

innodb_buffer_pool_size
+ key_buffer_size
+ max_connections*(sort_buffer_size+read_buffer_size+binlog_cache_size)
+ max_connections*2MB

Each thread uses a stack (often 2MB, but only 256KB in MySQL AB binaries) and in the worst case also uses additional memory.

By compiling MySQL yourself, you can use up to 64GB of physical memory in 32-bit Windows. See the description for in Section 14.2.4, “ Startup Options and System Variables”.

How to tune other mysqld server parameters? The following values are typical and suit most users:

[mysqld]
skip-external-locking
max_connections=200
read_buffer_size=1M
sort_buffer_size=1M
#
# Set key_buffer to 5 - 50% of your RAM depending on how much
# you use MyISAM tables, but keep key_buffer_size + InnoDB
# buffer pool size < 80% of your RAM
key_buffer_size=

14.2.3.1. Using Per-Table Tablespaces

You can store each table and its indexes in its own file. This feature is called “multiple tablespaces” because in effect each table has its own tablespace.

Using multiple tablespaces can be beneficial to users who want to move specific tables to separate physical disks or who wish to restore backups of single tables quickly without interrupting the use of the remaining tables.

You can enable multiple tablespaces by adding this line to the section of :

[mysqld]
innodb_file_per_table

After restarting the server, stores each newly created table into its own file .ibd in the database directory where the table belongs. This is similar to what the storage engine does, but divides the table into a data file .MYD and the index file .MYI. For , the data and the indexes are stored together in the file. The .frm file is still created as usual.

If you remove the line from and restart the server, creates tables inside the shared tablespace files again.

affects only table creation, not access to existing tables. If you start the server with this option, new tables are created using files, but you can still access tables that exist in the shared tablespace. If you remove the option and restart the server, new tables are created in the shared tablespace, but you can still access any tables that were created using multiple tablespaces.

Note: always needs the shared tablespace because it puts its internal data dictionary and undo logs there. The files are not sufficient for to operate.

Note: You cannot freely move files between database directories as you can with table files. This is because the table definition that is stored in the shared tablespace includes the database name, and because must preserve the consistency of transaction IDs and log sequence numbers.

To move an file and the associated table from one database to another, use a statement:

RENAME TABLE  TO ;

If you have a “clean” backup of an file, you can restore it to the MySQL installation from which it originated as follows:

  1. Issue this statement:

    ALTER TABLE  DISCARD TABLESPACE;
    

    Caution: This statement deletes the current file.

  2. Put the backup file back in the proper database directory.

  3. Issue this statement:

    ALTER TABLE  IMPORT TABLESPACE;
    

In this context, a “clean file backup means:

  • There are no uncommitted modifications by transactions in the file.

  • There are no unmerged insert buffer entries in the file.

  • Purge has removed all delete-marked index records from the file.

  • mysqld has flushed all modified pages of the file from the buffer pool to the file.

You can make a clean backup file using the following method:

  1. Stop all activity from the mysqld server and commit all transactions.

  2. Wait until shows that there are no active transactions in the database, and the main thread status of is . Then you can make a copy of the file.

Another method for making a clean copy of an file is to use the commercial InnoDB Hot Backup tool:

  1. Use InnoDB Hot Backup to back up the installation.

  2. Start a second mysqld server on the backup and let it clean up the files in the backup.

14.2.3.2. Using Raw Devices for the Shared Tablespace

You can use raw disk partitions as data files in the shared tablespace. By using a raw disk, you can perform non-buffered I/O on Windows and on some Unix systems without filesystem overhead, which may improve performance.

When you create a new data file, you must put the keyword immediately after the data file size in . The partition must be at least as large as the size that you specify. Note that 1MB in is 1024 × 1024 bytes, whereas 1MB in disk specifications usually means 1,000,000 bytes.

[mysqld]
innodb_data_home_dir=
innodb_data_file_path=/dev/hdd1:3Gnewraw;/dev/hdd2:2Gnewraw

The next time you start the server, notices the keyword and initializes the new partition. However, do not create or change any tables yet. Otherwise, when you next restart the server, reinitializes the partition and your changes are lost. (As a safety measure prevents users from modifying data when any partition with is specified.)

After has initialized the new partition, stop the server, change in the data file specification to :

[mysqld]
innodb_data_home_dir=
innodb_data_file_path=/dev/hdd1:5Graw;/dev/hdd2:2Graw

Then restart the server and allows changes to be made.

On Windows, you can allocate a disk partition as a data file like this:

[mysqld]
innodb_data_home_dir=
innodb_data_file_path=//./D::10Gnewraw

The corresponds to the Windows syntax of for accessing physical drives.

When you use raw disk partitions, be sure that they have permissions that allow read and write access by the account used for running the MySQL server.

14.2.4. InnoDB Startup Options and System Variables

This section describes the -related command options and system variables. System variables that are true or false can be enabled at server startup by naming them, or disabled by using a prefix. For example, to enable or disable checksums, you can use or on the command line, or or in an option file. System variables that take a numeric value can be specified as = on the command line or as = in option files. For more information on specifying options and system variables, see Section 4.3, “Specifying Program Options”. Many of the system variables can be changed at runtime (see Section 5.2.3.2, “Dynamic System Variables”).

command options:

  • Enables the storage engine, if the server was compiled with support. Use to disable .

  • Causes to create a file named /innodb_status. in the MySQL data directory. periodically writes the output of to this file.

system variables:

  • The size in bytes of a memory pool uses to store data dictionary information and other internal data structures. The more tables you have in your application, the more memory you need to allocate here. If runs out of memory in this pool, it starts to allocate memory from the operating system and writes warning messages to the MySQL error log. The default value is 1MB.

  • The increment size (in MB) for extending the size of an auto-extending tablespace when it becomes full. The default value is 8.

  • The size of the buffer pool (in MB), if it is placed in the AWE memory. This is relevant only in 32-bit Windows. If your 32-bit Windows operating system supports more than 4GB memory, using so-called “Address Windowing Extensions,” you can allocate the buffer pool into the AWE physical memory using this variable. The maximum possible value for this variable is 63000. If it is greater than 0, is the window in the 32-bit address space of mysqld where maps that AWE memory. A good value for is 500MB.

    To take advantage of AWE memory, you will need to recompile MySQL yourself. The current project settings needed for doing this can be found in the source file.

  • The size in bytes of the memory buffer uses to cache data and indexes of its tables. The larger you set this value, the less disk I/O is needed to access data in tables. On a dedicated database server, you may set this to up to 80% of the machine physical memory size. However, do not set it too large because competition for physical memory might cause paging in the operating system.

  • can use checksum validation on all pages read from the disk to ensure extra fault tolerance against broken hardware or data files. This validation is enabled by default. However, under some rare circumstances (such as when running benchmarks) this extra safety feature is unneeded and can be disabled with . This variable was added in MySQL 5.0.3.

  • The number of threads that can commit at the same time. A value of 0 disables concurrency control. This variable was added in MySQL 5.0.12.

  • The number of threads that can enter concurrently is determined by the variable. A thread is placed in a queue when it tries to enter if the number of threads has already reached the concurrency limit. When a thread is allowed to enter , it is given a number of “free tickets” equal to the value of , and the thread can enter and leave freely until it has used up its tickets. After that point, the thread again becomes subject to the concurrency check (and possible queuing) the next time it tries to enter . This variable was added in MySQL 5.0.3.

  • The paths to individual data files and their sizes. The full directory path to each data file is formed by concatenating to each path specified here. The file sizes are specified in MB or GB (1024MB) by appending or to the size value. The sum of the sizes of the files must be at least 10MB. If you do not specify , the default behavior is to create a single 10MB auto-extending data file named . The size limit of individual files is determined by your operating system. You can set the file size to more than 4GB on those operating systems that support big files. You can also use raw disk partitions as data files. See Section 14.2.3.2, “Using Raw Devices for the Shared Tablespace”.

  • The common part of the directory path for all data files. If you do not set this value, the default is the MySQL data directory. You can specify the value as an empty string, in which case you can use absolute file paths in .

  • By default, stores all data twice, first to the doublewrite buffer, and then to the actual data files. This variable is enabled by default. It can be turned off with for benchmarks or cases when top performance is needed rather than concern for data integrity or possible failures. This variable was added in MySQL 5.0.3.

  • If you set this variable to 0, does a full purge and an insert buffer merge before a shutdown. These operations can take minutes, or even hours in extreme cases. If you set this variable to 1, skips these operations at shutdown. The default value is 1. If you set it to 2, will just flush its logs and then shut down cold, as if MySQL had crashed; no committed transaction will be lost, but crash recovery will be done at the next startup. The value of 2 can be used as of MySQL 5.0.5, except that it cannot be used on NetWare.

  • The number of file I/O threads in . Normally, this should be left at the default value of 4, but disk I/O on Windows may benefit from a larger number. On Unix, increasing the number has no effect; always uses the default value.

  • If this variable is enabled, creates each new table using its own file for storing data and indexes, rather than in the shared tablespace. The default is to create tables in the shared tablespace. See Section 14.2.3.1, “Using Per-Table Tablespaces”.

  • When is set to 0, the log buffer is written out to the log file once per second and the flush to disk operation is performed on the log file, but nothing is done at a transaction commit. When this value is 1 (the default), the log buffer is written out to the log file at each transaction commit and the flush to disk operation is performed on the log file. When set to 2, the log buffer is written out to the file at each commit, but the flush to disk operation is not performed on it. However, the flushing on the log file takes place once per second also when the value is 2. Note that the once-per-second flushing is not 100% guaranteed to happen every second, due to process scheduling issues.

    The default value of this variable is 1, which is the value that is required for ACID compliance. You can achieve better performance by setting the value different from 1, but then you can lose at most one second worth of transactions in a crash. If you set the value to 0, then any mysqld process crash can erase the last second of transactions. If you set the value to 2, then only an operating system crash or a power outage can erase the last second of transactions. However, 's crash recovery is not affected and thus crash recovery does work regardless of the value. Note that many operating systems and some disk hardware fool the flush-to-disk operation. They may tell mysqld that the flush has taken place, even though it has not. Then the durability of transactions is not guaranteed even with the setting 1, and in the worst case a power outage can even corrupt the database. Using a battery-backed disk cache in the SCSI disk controller or in the disk itself speeds up file flushes, and makes the operation safer. You can also try using the Unix command hdparm to disable the caching of disk writes in hardware caches, or use some other command specific to the hardware vendor.

  • If set to (the default), uses to flush both the data and log files. If set to , uses to open and flush the log files, but uses to flush the data files. If is specified (available on some GNU/Linux versions), uses to open the data files, and uses to flush both the data and log files. Note that uses instead of , and it does not use by default because there have been problems with it on many varieties of Unix. This variable is relevant only for Unix. On Windows, the flush method is always and cannot be changed.

  • The crash recovery mode. Warning: This variable should be set greater than 0 only in an emergency situation when you want to dump your tables from a corrupt database! Possible values are from 1 to 6. The meanings of these values are described in Section 14.2.8.1, “Forcing Recovery”. As a safety measure, prevents any changes to its data when this variable is greater than 0.

  • The timeout in seconds an transaction may wait for a lock before being rolled back. automatically detects transaction deadlocks in its own lock table and rolls back the transaction. notices locks set using the statement. The default is 50 seconds.

    Note: For the greatest possible durability and consistency in a replication setup using with transactions, you should use , , and, before MySQL 5.0.3, in your master server file. ( is not needed from 5.0.3 on.)

  • This variable controls next-key locking in searches and index scans. By default, this variable is 0 (disabled), which means that next-key locking is enabled.

    Normally, uses an algorithm called next-key locking. performs row-level locking in such a way that when it searches or scans a table index, it sets shared or exclusive locks on any index records it encounters. Thus, the row-level locks are actually index record locks. The locks that sets on index records also affect the “gap” preceding that index record. If a user has a shared or exclusive lock on record R in an index, another user cannot insert a new index record immediately before R in the order of the index. Enabling this variable causes not to use next-key locking in searches or index scans. Next-key locking is still used to ensure foreign key constraints and duplicate key checking. Note that enabling this variable may cause phantom problems: Suppose that you want to read and lock all children from the table with an identifier value larger than 100, with the intention of updating some column in the selected rows later:

    SELECT * FROM child WHERE id > 100 FOR UPDATE;
    

    Suppose that there is an index on the column. The query scans that index starting from the first record where is greater than 100. If the locks set on the index records do not lock out inserts made in the gaps, another client can insert a new row into the table. If you execute the same within the same transaction, you see a new row in the result set returned by the query. This also means that if new items are added to the database, does not guarantee serializability. Therefore, if this variable is enabled guarantees at most isolation level . (Conflict serializability is still guaranteed.)

    Starting from MySQL 5.0.2, this option is even more unsafe. in an or a only locks rows that it updates or deletes. This greatly reduces the probability of deadlocks, but they can happen. Note that enabling this variable still does not allow operations such as to overtake other similar operations (such as another ) even in the case when they affect different rows. Consider the following example, beginning with this table:

    CREATE TABLE A(A INT NOT NULL, B INT) ENGINE = InnoDB;
    INSERT INTO A VALUES (1,2),(2,3),(3,2),(4,3),(5,2);
    COMMIT;
    

    Suppose that one client executes these statements:

    SET AUTOCOMMIT = 0;
    UPDATE A SET B = 5 WHERE B = 3;
    

    Then suppose that another client executes these statements following those of the first client:

    SET AUTOCOMMIT = 0;
    UPDATE A SET B = 4 WHERE B = 2;
    

    In this case, the second must wait for a commit or rollback of the first . The first has an exclusive lock on row (2,3), and the second while scanning rows also tries to acquire an exclusive lock for the same row, which it cannot have. This is because two first acquires an exclusive lock on a row and then determines whether the row belongs to the result set. If not, it releases the unnecessary lock, when the variable is enabled.

    Therefore, executes one as follows:

    x-lock(1,2)
    unlock(1,2)
    x-lock(2,3)
    update(2,3) to (2,5)
    x-lock(3,2)
    unlock(3,2)
    x-lock(4,3)
    update(4,3) to (4,5)
    x-lock(5,2)
    unlock(5,2)
    

    executes two as follows:

    x-lock(1,2)
    update(1,2) to (1,4)
    x-lock(2,3) - wait for query one to commit or rollback
    
  • The directory where fully written log files would be archived if we used log archiving. If used, the value of this variable should be set the same as . However, it is not required.

  • Whether to log archive files. This variable is present for historical reasons, but is unused. Recovery from a backup is done by MySQL using its own log files, so there is no need to archive log files. The default for this variable is 0.

  • The size in bytes of the buffer that uses to write to the log files on disk. Sensible values range from 1MB to 8MB. The default is 1MB. A large log buffer allows large transactions to run without a need to write the log to disk before the transactions commit. Thus, if you have big transactions, making the log buffer larger saves disk I/O.

  • The size in bytes of each log file in a log group. The combined size of log files must be less than 4GB on 32-bit computers. The default is 5MB. Sensible values range from 1MB to 1/-th of the size of the buffer pool, where is the number of log files in the group. The larger the value, the less checkpoint flush activity is needed in the buffer pool, saving disk I/O. But larger log files also mean that recovery is slower in case of a crash.

  • The number of log files in the log group. writes to the files in a circular fashion. The default (and recommended) is 2.

  • The directory path to the log files. It must have the same value as . If you do not specify any log variables, the default is to create two 5MB files names and in the MySQL data directory.

  • This is an integer in the range from 0 to 100. The default is 90. The main thread in tries to write pages from the buffer pool so that the percentage of dirty (not yet written) pages will not exceed this value.

  • This variable controls how to delay , and operations when the purge operations are lagging (see Section 14.2.12, “Implementation of Multi-Versioning”). The default value of this variable is 0, meaning that there are no delays.

    The transaction system maintains a list of transactions that have delete-marked index records by or operations. Let the length of this list be . When exceeds , each , and operation is delayed by ((/)×10)–5 milliseconds. The delay is computed in the beginning of a purge batch, every ten seconds. The operations are not delayed if purge cannot run because of an old consistent read view that could see the rows to be purged.

    A typical setting for a problematic workload might be 1 million, assuming that our transactions are small, only 100 bytes in size, and we can allow 100MB of unpurged rows in our tables.

  • The number of identical copies of log groups to keep for the database. Currently, this should be set to 1.

  • This variable is relevant only if you use multiple tablespaces in . It specifies the maximum number of files that can keep open at one time. The minimum value is 10. The default is 300.

    The file descriptors used for files are for only. They are independent of those specified by the server option, and do not affect the operation of the table cache.

  • Adds consistency guarantees between the content of tables and the binary log. See Section 5.12.3, “The Binary Log”. This variable was removed in MySQL 5.0.3, having been made obsolete by the introduction of XA transaction support.

  • When set to or 1 (the default), this variable enables support for two-phase commit in XA transactions. Enabling causes an extra disk flush for transaction preparation. If you don't care about using XA, you can disable this variable by setting it to or 0 to reduce the number of disk flushes and get better performance. This variable was added in MySQL 5.0.3.

  • The number of times a thread waits for an mutex to be freed before the thread is suspended. This variable was added in MySQL 5.0.3.

  • honors ; MySQL does not return from until all other threads have released all their locks to the table. The default value is 1, which means that causes to lock a table internally. In applications using , 's internal table locks can cause deadlocks. You can set in the server option file to remove that problem.

  • tries to keep the number of operating system threads concurrently inside less than or equal to the limit given by this variable. If you have performance issues, and reveals many threads waiting for semaphores, you may have thread “thrashing” and should try setting this variable lower or higher. If you have a computer with many processors and disks, you can try setting the value higher to make better use of your computer's resources. A recommended value is the sum of the number of processors and disks your system has. greater disables concurrency checking.

    The range of this variable is 0 to 1000. A value of 20 or higher is interpreted as infinite concurrency before MySQL 5.0.19. From 5.0.19 on, 0 is interpreted as infinite. Infinite means that concurrency checking is disabled and the possibly considerable overhead of acquiring and releasing a mutex is avoided.

    The default value has changed several times: 8 before MySQL 5.0.8, 20 (infinite) from 5.0.8 through 5.0.18, 0 (infinite) from 5.0.19 to 5.0.20, and 8 (finite) from 5.0.21 on.

  • How long threads sleep before joining the queue, in microseconds. The default value is 10,000. A value of 0 disables sleep. This variable was added in MySQL 5.0.3.

  • If the value of this variable is positive, the MySQL server synchronizes its binary log to disk () after every writes to this binary log. Note that there is one write to the binary log per statement if in autocommit mode, and otherwise one write per transaction. The default value is 0 which does no synchronizing to disk. A value of 1 is the safest choice, because in the event of a crash you lose at most one statement/transaction from the binary log; however, it is also the slowest choice (unless the disk has a battery-backed cache, which makes synchronization very fast).

14.2.5. Creating the InnoDB Tablespace

Suppose that you have installed MySQL and have edited your option file so that it contains the necessary configuration parameters. Before starting MySQL, you should verify that the directories you have specified for data files and log files exist and that the MySQL server has access rights to those directories. does not create directories, only files. Check also that you have enough disk space for the data and log files.

It is best to run the MySQL server mysqld from the command prompt when you first start the server with enabled, not from the mysqld_safe wrapper or as a Windows service. When you run from a command prompt you see what mysqld prints and what is happening. On Unix, just invoke mysqld. On Windows, use the option.

When you start the MySQL server after initially configuring in your option file, creates your data files and log files, and prints something like this:

InnoDB: The first specified datafile /home/heikki/data/ibdata1
did not exist:
InnoDB: a new database to be created!
InnoDB: Setting file /home/heikki/data/ibdata1 size to 134217728
InnoDB: Database physically writes the file full: wait...
InnoDB: datafile /home/heikki/data/ibdata2 did not exist:
new to be created
InnoDB: Setting file /home/heikki/data/ibdata2 size to 262144000
InnoDB: Database physically writes the file full: wait...
InnoDB: Log file /home/heikki/data/logs/ib_logfile0 did not exist:
new to be created
InnoDB: Setting log file /home/heikki/data/logs/ib_logfile0 size
to 5242880
InnoDB: Log file /home/heikki/data/logs/ib_logfile1 did not exist:
new to be created
InnoDB: Setting log file /home/heikki/data/logs/ib_logfile1 size
to 5242880
InnoDB: Doublewrite buffer not found: creating new
InnoDB: Doublewrite buffer created
InnoDB: Creating foreign key constraint system tables
InnoDB: Foreign key constraint system tables created
InnoDB: Started
mysqld: ready for connections

At this point has initialized its tablespace and log files. You can connect to the MySQL server with the usual MySQL client programs like mysql. When you shut down the MySQL server with mysqladmin shutdown, the output is like this:

010321 18:33:34  mysqld: Normal shutdown
010321 18:33:34  mysqld: Shutdown Complete
InnoDB: Starting shutdown...
InnoDB: Shutdown completed

You can look at the data file and log directories and you see the files created there. The log directory also contains a small file named . That file resulted from the database creation, after which switched off log archiving. When MySQL is started again, the data files and log files have been created already, so the output is much briefer:

InnoDB: Started
mysqld: ready for connections

If you add the option to , stores each table in its own file in the same MySQL database directory where the file is created. See Section 14.2.3.1, “Using Per-Table Tablespaces”.

14.2.5.1. Dealing with Initialization Problems

If prints an operating system error during a file operation, usually the problem has one of the following causes:

  • You did not create the data file directory or the log directory.

  • mysqld does not have access rights to create files in those directories.

  • mysqld cannot read the proper or option file, and consequently does not see the options that you specified.

  • The disk is full or a disk quota is exceeded.

  • You have created a subdirectory whose name is equal to a data file that you specified, so the name cannot be used as a filename.

  • There is a syntax error in the or value.

If something goes wrong when attempts to initialize its tablespace or its log files, you should delete all files created by . This means all files and all files. In case you have already created some tables, delete the corresponding files for these tables (and any files if you are using multiple tablespaces) from the MySQL database directories as well. Then you can try the database creation again. It is best to start the MySQL server from a command prompt so that you see what is happening.

14.2.6. Creating and Using InnoDB Tables

To create an table, specify an option in the statement:

CREATE TABLE customers (a INT, b CHAR (20), INDEX (a)) ENGINE=InnoDB;

The older term is supported as a synonym for for backward compatibility, but is the preferred term and is deprecated.

The statement creates a table and an index on column in the tablespace that consists of the data files that you specified in . In addition, MySQL creates a file in the directory under the MySQL database directory. Internally, adds an entry for the table to its own data dictionary. The entry includes the database name. For example, if is the database in which the table is created, the entry is for . This means you can create a table of the same name in some other database, and the table names do not collide inside .

You can query the amount of free space in the tablespace by issuing a statement for any table. The amount of free space in the tablespace appears in the section in the output of . For example:

SHOW TABLE STATUS FROM test LIKE 'customers'

Note that the statistics displays for tables are only approximate. They are used in SQL optimization. Table and index reserved sizes in bytes are accurate, though.

14.2.6.1. How to Use Transactions in with Different APIs

By default, each client that connects to the MySQL server begins with autocommit mode enabled, which automatically commits every SQL statement as you execute it. To use multiple-statement transactions, you can switch autocommit off with the SQL statement and use and to commit or roll back your transaction. If you want to leave autocommit on, you can enclose your transactions within and either or . The following example shows two transactions. The first is committed; the second is rolled back.

shell> 

mysql> 
    -> 
Query OK, 0 rows affected (0.00 sec)
mysql> 
Query OK, 0 rows affected (0.00 sec)
mysql> 
Query OK, 1 row affected (0.00 sec)
mysql> 
Query OK, 0 rows affected (0.00 sec)
mysql> 
Query OK, 0 rows affected (0.00 sec)
mysql> 
Query OK, 1 row affected (0.00 sec)
mysql> 
Query OK, 0 rows affected (0.00 sec)
mysql> 
+------+--------+
| A    | B      |
+------+--------+
|   10 | Heikki |
+------+--------+
1 row in set (0.00 sec)
mysql>

In APIs such as PHP, Perl DBI, JDBC, ODBC, or the standard C call interface of MySQL, you can send transaction control statements such as to the MySQL server as strings just like any other SQL statements such as or . Some APIs also offer separate special transaction commit and rollback functions or methods.

14.2.6.2. Converting Tables to

Important: Do not convert MySQL system tables in the database (such as or ) to the type. This is an unsupported operation. The system tables must always be of the type.

If you want all your (non-system) tables to be created as tables, you can simply add the line to the section of your server option file.

does not have a special optimization for separate index creation the way the storage engine does. Therefore, it does not pay to export and import the table and create indexes afterward. The fastest way to alter a table to is to do the inserts directly to an table. That is, use , or create an empty table with identical definitions and insert the rows with .

If you have constraints on secondary keys, you can speed up a table import by turning off the uniqueness checks temporarily during the import operation:

SET UNIQUE_CHECKS=0;

SET UNIQUE_CHECKS=1;

For big tables, this saves a lot of disk I/O because can then use its insert buffer to write secondary index records as a batch. Be certain that the data contains no duplicate keys. allows but does not require storage engines to ignore duplicate keys.

To get better control over the insertion process, it might be good to insert big tables in pieces:

INSERT INTO newtable SELECT * FROM oldtable
   WHERE yourkey > something AND yourkey <= somethingelse;

After all records have been inserted, you can rename the tables.

During the conversion of big tables, you should increase the size of the buffer pool to reduce disk I/O. Do not use more than 80% of the physical memory, though. You can also increase the sizes of the log files.

Make sure that you do not fill up the tablespace: tables require a lot more disk space than tables. If an operation runs out of space, it starts a rollback, and that can take hours if it is disk-bound. For inserts, uses the insert buffer to merge secondary index records to indexes in batches. That saves a lot of disk I/O. For rollback, no such mechanism is used, and the rollback can take 30 times longer than the insertion.

In the case of a runaway rollback, if you do not have valuable data in your database, it may be advisable to kill the database process rather than wait for millions of disk I/O operations to complete. For the complete procedure, see Section 14.2.8.1, “Forcing Recovery”.

14.2.6.3. How Columns Work in

If you specify an column for an table, the table handle in the data dictionary contains a special counter called the auto-increment counter that is used in assigning new values for the column. This counter is stored only in main memory, not on disk.

uses the following algorithm to initialize the auto-increment counter for a table that contains an column named : After a server startup, for the first insert into a table , executes the equivalent of this statement:

SELECT MAX(ai_col) FROM T FOR UPDATE;

increments by one the value retrieved by the statement and assigns it to the column and to the auto-increment counter for the table. If the table is empty, uses the value . If a user invokes a statement that displays output for the table and the auto-increment counter has not been initialized, initializes but does not increment the value and stores it for use by later inserts. Note that this initialization uses a normal exclusive-locking read on the table and the lock lasts to the end of the transaction.

follows the same procedure for initializing the auto-increment counter for a freshly created table.

After the auto-increment counter has been initialized, if a user does not explicitly specify a value for an column, increments the counter by one and assigns the new value to the column. If the user inserts a row that explicitly specifies the column value, and the value is bigger than the current counter value, the counter is set to the specified column value.

You may see gaps in the sequence of values assigned to the column if you roll back transactions that have generated numbers using the counter.

If a user specifies or for the column in an , treats the row as if the value had not been specified and generates a new value for it.

The behavior of the auto-increment mechanism is not defined if a user assigns a negative value to the column or if the value becomes bigger than the maximum integer that can be stored in the specified integer type.

When accessing the auto-increment counter, uses a special table-level lock that it keeps to the end of the current SQL statement, not to the end of the transaction. The special lock release strategy was introduced to improve concurrency for inserts into a table containing an column. Nevertheless, two transactions cannot have the lock on the same table simultaneously, which can have a performance impact if the lock is held for a long time. That might be the case for a statement such as that inserts all rows from one table into another.

uses the in-memory auto-increment counter as long as he server runs. When the server is stopped and restarted, reinitializes the counter for each table for the first to the table, as described earlier.

Beginning with MySQL 5.0.3, supports the table option in and statements, to set the initial counter value or alter the current counter value. The effect of this option is canceled by a server restart, for reasons discussed earlier in this section.

14.2.6.4.  Constraints

also supports foreign key constraints. The syntax for a foreign key constraint definition in looks like this:

[CONSTRAINT ] FOREIGN KEY [] (, ...)
    REFERENCES  (, ...)
    [ON DELETE {RESTRICT | CASCADE | SET NULL | NO ACTION}]
    [ON UPDATE {RESTRICT | CASCADE | SET NULL | NO ACTION}]

Foreign keys definitions are subject to the following conditions:

  • Both tables must be tables and they must not be tables.

  • In the referencing table, there must be an index where the foreign key columns are listed as the first columns in the same order. Such an index is created on the referencing table automatically if it does not exist.

  • In the referenced table, there must be an index where the referenced columns are listed as the first columns in the same order.

  • Index prefixes on foreign key columns are not supported. One consequence of this is that and columns cannot be included in a foreign key, because indexes on those columns must always include a prefix length.

  • If the clause is given, the value must be unique in the database. If the clause is not given, creates the name automatically.

rejects any or operation that attempts to create a foreign key value in a child table if there is no a matching candidate key value in the parent table. The action takes for any or operation that attempts to update or delete a candidate key value in the parent table that has some matching rows in the child table is dependent on the referential action specified using and subclauses of the clause. When the user attempts to delete or update a row from a parent table, and there are one or more matching rows in the child table, supports five options regarding the action to be taken:

  • : Delete or update the row from the parent table and automatically delete or update the matching rows in the child table. Both and are supported. Between two tables, you should not define several clauses that act on the same column in the parent table or in the child table.

  • : Delete or update the row from the parent table and set the foreign key column or columns in the child table to . This is valid only if the foreign key columns do not have the qualifier specified. Both and clauses are supported.

  • : In standard SQL, means no action in the sense that an attempt to delete or update a primary key value is not allowed to proceed if there is a related foreign key value in the referenced table. rejects the delete or update operation for the parent table.

  • : Rejects the delete or update operation for the parent table. and are the same as omitting the or clause. (Some database systems have deferred checks, and is a deferred check. In MySQL, foreign key constraints are checked immediately, so and are the same.)

  • : This action is recognized by the parser, but rejects table definitions containing or clauses.

Note that supports foreign key references within a table. In these cases, “child table records” really refers to dependent records within the same table.

requires indexes on foreign keys and referenced keys so that foreign key checks can be fast and not require a table scan. The index on the foreign key is created automatically. This is in contrast to some older versions, in which indexes had to be created explicitly or the creation of foreign key constraints would fail.

Corresponding columns in the foreign key and the referenced key must have similar internal data types inside so that they can be compared without a type conversion. The size and sign of integer types must be the same. The length of string types need not be the same. If you specify a action, make sure that you have not declared the columns in the child table as .

If MySQL reports an error number 1005 from a statement, and the error message refers to errno 150, table creation failed because a foreign key constraint was not correctly formed. Similarly, if an fails and it refers to errno 150, that means a foreign key definition would be incorrectly formed for the altered table. You can use to display a detailed explanation of the most recent foreign key error in the server.

Note: does not check foreign key constraints on those foreign key or referenced key values that contain a column.

Note: Currently, triggers are not activated by cascaded foreign key actions.

Deviation from SQL standards: If there are several rows in the parent table that have the same referenced key value, acts in foreign key checks as if the other parent rows with the same key value do not exist. For example, if you have defined a type constraint, and there is a child row with several parent rows, does not allow the deletion of any of those parent rows.

performs cascading operations through a depth-first algorithm, based on records in the indexes corresponding to the foreign key constraints.

Deviation from SQL standards: A constraint that references a non- key is not standard SQL. It is an extension to standard SQL.

Deviation from SQL standards: If or recurses to update the same table it has previously updated during the cascade, it acts like . This means that you cannot use self-referential or operations. This is to prevent infinite loops resulting from cascaded updates. A self-referential , on the other hand, is possible, as is a self-referential . Cascading operations may not be nested more than 15 levels deep.

Deviation from SQL standards: Like MySQL in general, in an SQL statement that inserts, deletes, or updates many rows, checks and constraints row-by-row. According to the SQL standard, the default behavior should be deferred checking. That is, constraints are only checked after the entire SQL statement has been processed. Until implements deferred constraint checking, some things will be impossible, such as deleting a record that refers to itself via a foreign key.

Here is a simple example that relates and tables through a single-column foreign key:

CREATE TABLE parent (id INT NOT NULL,
                     PRIMARY KEY (id)
) ENGINE=INNODB;
CREATE TABLE child (id INT, parent_id INT,
                    INDEX par_ind (parent_id),
                    FOREIGN KEY (parent_id) REFERENCES parent(id)
                      ON DELETE CASCADE
) ENGINE=INNODB;

A more complex example in which a table has foreign keys for two other tables. One foreign key references a two-column index in the table. The other references a single-column index in the table:

CREATE TABLE product (category INT NOT NULL, id INT NOT NULL,
                      price DECIMAL,
                      PRIMARY KEY(category, id)) ENGINE=INNODB;
CREATE TABLE customer (id INT NOT NULL,
                       PRIMARY KEY (id)) ENGINE=INNODB;
CREATE TABLE product_order (no INT NOT NULL AUTO_INCREMENT,
                            product_category INT NOT NULL,
                            product_id INT NOT NULL,
                            customer_id INT NOT NULL,
                            PRIMARY KEY(no),
                            INDEX (product_category, product_id),
                            FOREIGN KEY (product_category, product_id)
                              REFERENCES product(category, id)
                              ON UPDATE CASCADE ON DELETE RESTRICT,
                            INDEX (customer_id),
                            FOREIGN KEY (customer_id)
                              REFERENCES customer(id)) ENGINE=INNODB;

allows you to add a new foreign key constraint to a table by using :

ALTER TABLE 
    ADD [CONSTRAINT ] FOREIGN KEY [] (, ...)
    REFERENCES  (, ...)
    [ON DELETE {RESTRICT | CASCADE | SET NULL | NO ACTION}]
    [ON UPDATE {RESTRICT | CASCADE | SET NULL | NO ACTION}]

Remember to create the required indexes first. You can also add a self-referential foreign key constraint to a table using .

also supports the use of to drop foreign keys:

ALTER TABLE  DROP FOREIGN KEY ;

If the clause included a name when you created the foreign key, you can refer to that name to drop the foreign key. Otherwise, the value is internally generated by when the foreign key is created. To find out the symbol value when you want to drop a foreign key, use the statement. For example:

mysql> 
*************************** 1. row ***************************
       Table: ibtest11c
Create Table: CREATE TABLE `ibtest11c` (
  `A` int(11) NOT NULL auto_increment,
  `D` int(11) NOT NULL default '0',
  `B` varchar(200) NOT NULL default '',
  `C` varchar(175) default NULL,
  PRIMARY KEY  (`A`,`D`,`B`),
  KEY `B` (`B`,`C`),
  KEY `C` (`C`),
  CONSTRAINT `0_38775` FOREIGN KEY (`A`, `D`)
REFERENCES `ibtest11a` (`A`, `D`)
ON DELETE CASCADE ON UPDATE CASCADE,
  CONSTRAINT `0_38776` FOREIGN KEY (`B`, `C`)
REFERENCES `ibtest11a` (`B`, `C`)
ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=INNODB CHARSET=latin1
1 row in set (0.01 sec)

mysql> 

You cannot add a foreign key and drop a foreign key in separate clauses of a single statement. Separate statements are required.

The parser allows table and column identifiers in a clause to be quoted within backticks. (Alternatively, double quotes can be used if the SQL mode is enabled.) The parser also takes into account the setting of the system variable.

returns a table's foreign key definitions as part of the output of the statement:

SHOW CREATE TABLE ;

mysqldump also produces correct definitions of tables to the dump file, and does not forget about the foreign keys.

You can also display the foreign key constraints for a table like this:

SHOW TABLE STATUS FROM  LIKE '';

The foreign key constraints are listed in the column of the output.

When performing foreign key checks, sets shared row-level locks on child or parent records it has to look at. checks foreign key constraints immediately; the check is not deferred to transaction commit.

To make it easier to reload dump files for tables that have foreign key relationships, mysqldump automatically includes a statement in the dump output to set to 0. This avoids problems with tables having to be reloaded in a particular order when the dump is reloaded. It is also possible to set this variable manually:

mysql> 
mysql> ;
mysql> 

This allows you to import the tables in any order if the dump file contains tables that are not correctly ordered for foreign keys. It also speeds up the import operation. Setting to 0 can also be useful for ignoring foreign key constraints during and operations. However, even if , InnoDB does not allow the creation of a foreign key constraint where a column references a non-matching column type.

does not allow you to drop a table that is referenced by a constraint, unless you do . When you drop a table, the constraints that were defined in its create statement are also dropped.

If you re-create a table that was dropped, it must have a definition that conforms to the foreign key constraints referencing it. It must have the right column names and types, and it must have indexes on the referenced keys, as stated earlier. If these are not satisfied, MySQL returns error number 1005 and refers to errno 150 in the error message.

14.2.6.5.  and MySQL Replication

MySQL replication works for tables as it does for tables. It is also possible to use replication in a way where the storage engine on the slave is not the same as the original storage engine on the master. For example, you can replicate modifications to an table on the master to a table on the slave.

To set up a new slave for a master, you have to make a copy of the tablespace and the log files, as well as the files of the tables, and move the copies to the slave. If the variable is enabled, you must also copy the files as well. For the proper procedure to do this, see Section 14.2.8, “Backing Up and Recovering an Database”.

If you can shut down the master or an existing slave, you can take a cold backup of the tablespace and log files and use that to set up a slave. To make a new slave without taking down any server you can also use the non-free (commercial) tool.

You cannot set up replication for using the statement, which works only for tables. There are two possible workarounds:

  • Dump the table on the master and import the dump file into the slave.

  • Use ENGINE=MyISAM on the master before setting up replication with FROM MASTER, and then use to convert the master table back to afterward. However, this should not be done for tables that have foreign key definitions because the definitions will be lost.

Transactions that fail on the master do not affect replication at all. MySQL replication is based on the binary log where MySQL writes SQL statements that modify data. A transaction that fails (for example, because of a foreign key violation, or because it is is rolled back) is not written to the binary log, so it is not sent to slaves. See Section 13.4.1, “, , and Syntax”.

14.2.7. Adding and Removing InnoDB Data and Log Files

This section describes what you can do when your tablespace runs out of room or when you want to change the size of the log files.

The easiest way to increase the size of the tablespace is to configure it from the beginning to be auto-extending. Specify the attribute for the last data file in the tablespace definition. Then increases the size of that file automatically in 8MB increments when it runs out of space. The increment size can be changed by setting the value of the system variable, which is measured in MB.

Alternatively, you can increase the size of your tablespace by adding another data file. To do this, you have to shut down the MySQL server, change the tablespace configuration to add a new data file to the end of , and start the server again.

If your last data file was defined with the keyword , the procedure for reconfiguring the tablespace must take into account the size to which the last data file has grown. Obtain the size of the data file, round it down to the closest multiple of 1024 × 1024 bytes (= 1MB), and specify the rounded size explicitly in . Then you can add another data file. Remember that only the last data file in the can be specified as auto-extending.

As an example, assume that the tablespace has just one auto-extending data file :

innodb_data_home_dir =
innodb_data_file_path = /ibdata/ibdata1:10M:autoextend

Suppose that this data file, over time, has grown to 988MB. Here is the configuration line after modifying the original data file to not be auto-extending and adding another auto-extending data file:

innodb_data_home_dir =
innodb_data_file_path = /ibdata/ibdata1:988M;/disk2/ibdata2:50M:autoextend

When you add a new file to the tablespace configuration, make sure that it does not exist. will create and initialize the file when you restart the server.

Currently, you cannot remove a data file from the tablespace. To decrease the size of your tablespace, use this procedure:

  1. Use mysqldump to dump all your tables.

  2. Stop the server.

  3. Remove all the existing tablespace files.

  4. Configure a new tablespace.

  5. Restart the server.

  6. Import the dump files.

If you want to change the number or the size of your log files, use the following instructions. The procedure to use depends on the value of :

  • If is not set to 2: You must stop the MySQL server and make sure that it shuts down without errors (to ensure that there is no information for outstanding transactions in the logs). Then copy the old log files into a safe place just in case something went wrong in the shutdown and you need them to recover the tablespace. Delete the old log files from the log file directory, edit to change the log file configuration, and start the MySQL server again. mysqld sees that no log files exist at startup and tells you that it is creating new ones.

  • If is set to 2: You should shut down the server, set to 1, and restart the server. The server should be allowed to recover. Then you should shut down the server again and follow the procedure described in the preceding item to change log file size. Set back to 2 and restart the server.

14.2.8. Backing Up and Recovering an InnoDB Database

The key to safe database management is making regular backups.

InnoDB Hot Backup is an online backup tool you can use to backup your database while it is running. InnoDB Hot Backup does not require you to shut down your database and it does not set any locks or disturb your normal database processing. InnoDB Hot Backup is a non-free (commercial) add-on tool with an annual license fee of €390 per computer on which the MySQL server is run. See the InnoDB Hot Backup home page for detailed information and screenshots.

If you are able to shut down your MySQL server, you can make a binary backup that consists of all files used by to manage its tables. Use the following procedure:

  1. Shut down your MySQL server and make sure that it shuts down without errors.

  2. Copy all your data files ( files and files) into a safe place.

  3. Copy all your files to a safe place.

  4. Copy your configuration file or files to a safe place.

  5. Copy all the files for your tables to a safe place.

Replication works with tables, so you can use MySQL replication capabilities to keep a copy of your database at database sites requiring high availability.

In addition to making binary backups as just described, you should also regularly make dumps of your tables with mysqldump. The reason for this is that a binary file might be corrupted without you noticing it. Dumped tables are stored into text files that are human-readable, so spotting table corruption becomes easier. Also, because the format is simpler, the chance for serious data corruption is smaller. mysqldump also has a option that you can use to make a consistent snapshot without locking out other clients.

To be able to recover your database to the present from the binary backup just described, you have to run your MySQL server with binary logging turned on. Then you can apply the binary log to the backup database to achieve point-in-time recovery:

mysqlbinlog -bin.123 | mysql

To recover from a crash of your MySQL server, the only requirement is to restart it. automatically checks the logs and performs a roll-forward of the database to the present. automatically rolls back uncommitted transactions that were present at the time of the crash. During recovery, mysqld displays output something like this:

InnoDB: Database was not shut down normally.
InnoDB: Starting recovery from log files...
InnoDB: Starting log scan based on checkpoint at
InnoDB: log sequence number 0 13674004
InnoDB: Doing recovery: scanned up to log sequence number 0 13739520
InnoDB: Doing recovery: scanned up to log sequence number 0 13805056
InnoDB: Doing recovery: scanned up to log sequence number 0 13870592
InnoDB: Doing recovery: scanned up to log sequence number 0 13936128
...
InnoDB: Doing recovery: scanned up to log sequence number 0 20555264
InnoDB: Doing recovery: scanned up to log sequence number 0 20620800
InnoDB: Doing recovery: scanned up to log sequence number 0 20664692
InnoDB: 1 uncommitted transaction(s) which must be rolled back
InnoDB: Starting rollback of uncommitted transactions
InnoDB: Rolling back trx no 16745
InnoDB: Rolling back of trx no 16745 completed
InnoDB: Rollback of uncommitted transactions completed
InnoDB: Starting an apply batch of log records to the database...
InnoDB: Apply batch completed
InnoDB: Started
mysqld: ready for connections

If your database gets corrupted or your disk fails, you have to do the recovery from a backup. In the case of corruption, you should first find a backup that is not corrupted. After restoring the base backup, do the recovery from the binary log files using mysqlbinlog and mysql to restore the changes performed after the backup was made.

In some cases of database corruption it is enough just to dump, drop, and re-create one or a few corrupt tables. You can use the SQL statement to check whether a table is corrupt, although naturally cannot detect every possible kind of corruption. You can use to check the integrity of the file space management inside the tablespace files.

In some cases, apparent database page corruption is actually due to the operating system corrupting its own file cache, and the data on disk may be okay. It is best first to try restarting your computer. Doing so may eliminate errors that appeared to be database page corruption.

14.2.8.1. Forcing Recovery

If there is database page corruption, you may want to dump your tables from the database with . Usually, most of the data obtained in this way is intact. Even so, the corruption may cause statements or background operations to crash or assert, or even to cause roll-forward recovery to crash. However, you can force the storage engine to start up while preventing background operations from running, so that you are able to dump your tables. For example, you can add the following line to the section of your option file before restarting the server:

[mysqld]
innodb_force_recovery = 4

The allowable non-zero values for follow. A larger number includes all precautions of smaller numbers. If you are able to dump your tables with an option value of at most 4, then you are relatively safe that only some data on corrupt individual pages is lost. A value of 6 is more drastic because database pages are left in an obsolete state, which in turn may introduce more corruption into B-trees and other database structures.

  • ()

    Let the server run even if it detects a corrupt page. Try to make jump over corrupt index records and pages, which helps in dumping tables.

  • ()

    Prevent the main thread from running. If a crash would occur during the purge operation, this recovery value prevents it.

  • ()

    Do not run transaction rollbacks after recovery.

  • ()

    Prevent also insert buffer merge operations. If they would cause a crash, do not do them. Do not calculate table statistics.

  • ()

    Do not look at undo logs when starting the database: treats even incomplete transactions as committed.

  • ()

    Do not do the log roll-forward in connection with recovery.

You can from tables to dump them, or or tables even if forced recovery is used. If you know that a given table is causing a crash on rollback, you can drop it. You can also use this to stop a runaway rollback caused by a failing mass import or . You can kill the mysqld process and set to to bring the database up without the rollback, then the table that is causing the runaway rollback.

The database must not otherwise be used with any non-zero value of . As a safety measure, prevents users from performing , , or operations when is greater than 0.

14.2.8.2. Checkpoints

implements a checkpoint mechanism known as “fuzzy” checkpointing. flushes modified database pages from the buffer pool in small batches. There is no need to flush the buffer pool in one single batch, which would in practice stop processing of user SQL statements during the checkpointing process.

During crash recovery, looks for a checkpoint label written to the log files. It knows that all modifications to the database before the label are present in the disk image of the database. Then scans the log files forward from the checkpoint, applying the logged modifications to the database.

writes to its log files on a rotating basis. All committed modifications that make the database pages in the buffer pool different from the images on disk must be available in the log files in case has to do a recovery. This means that when starts to reuse a log file, it has to make sure that the database page images on disk contain the modifications logged in the log file that is going to reuse. In other words, must create a checkpoint and this often involves flushing of modified database pages to disk.

The preceding description explains why making your log files very large may save disk I/O in checkpointing. It often makes sense to set the total size of the log files as big as the buffer pool or even bigger. The drawback of using large log files is that crash recovery can take longer because there is more logged information to apply to the database.

14.2.9. Moving an InnoDB Database to Another Machine

On Windows, always stores database and table names internally in lowercase. To move databases in a binary format from Unix to Windows or from Windows to Unix, you should have all table and database names in lowercase. A convenient way to accomplish this is to add the following line to the section of your or file before creating any databases or tables:

[mysqld]
lower_case_table_names=1

Like data files, data and log files are binary-compatible on all platforms having the same floating-point number format. You can move an database simply by copying all the relevant files listed in Section 14.2.8, “Backing Up and Recovering an Database”. If the floating-point formats differ but you have not used or data types in your tables, then the procedure is the same: simply copy the relevant files. If the formats differ and your tables contain floating-point data, you must use mysqldump to dump your tables on one machine and then import the dump files on the other machine.

One way to increase performance is to switch off autocommit mode when importing data, assuming that the tablespace has enough space for the big rollback segment that the import transactions generate. Do the commit only after importing a whole table or a segment of a table.

14.2.10. InnoDB Transaction Model and Locking

In the transaction model, the goal is to combine the best properties of a multi-versioning database with traditional two-phase locking. does locking on the row level and runs queries as non-locking consistent reads by default, in the style of Oracle. The lock table in is stored so space-efficiently that lock escalation is not needed: Typically several users are allowed to lock every row in the database, or any random subset of the rows, without running out of memory.

14.2.10.1.  Lock Modes

implements standard row-level locking where there are two types of locks:

  • A shared () lock allows a transaction to read a row (tuple).

  • An exclusive () lock allows a transaction to update or delete a row.

If transaction holds a shared () lock on tuple , then

  • A request from some distinct transaction for an lock on can be granted immediately. As a result, both and hold an lock on .

  • A request from some distinct transaction for an lock on cannot be granted immediately.

If a transaction holds an exclusive () lock on tuple , then a request from some distinct transaction for a lock of either type on cannot be granted immediately. Instead, transaction has to wait for transaction to release its lock on tuple .

Additionally, supports multiple granularity locking which allows coexistence of record locks and locks on entire tables. To make locking at multiple granularity levels practical, additional types of locks called intention locks are used. Intention locks are table locks in . The idea behind intention locks is for a transaction to indicate which type of lock (shared or exclusive) it will require later for a row in that table. There are two types of intention locks used in (assume that transaction has requested a lock of the indicated type on table ):

  • Intention shared (): Transaction intends to set locks on individual rows in table .

  • Intention exclusive (): Transaction intends to set locks on those rows.

The intention locking protocol is as follows:

  • Before a given transaction can acquire an lock on a given row, it must first acquire an or stronger lock on the table containing that row.

  • Before a given transaction can acquire an lock on a given row, it must first acquire an lock on the table containing that row.

These rules can be conveniently summarized by means of a lock type compatibility matrix:

 
Conflict Conflict Conflict Conflict
Conflict Compatible Conflict Compatible
Conflict Conflict Compatible Compatible
Conflict Compatible Compatible Compatible

A lock is granted to a requesting transaction if it is compatible with existing locks. A lock is not granted to a requesting transaction if it conflicts with existing locks. A transaction waits until the conflicting existing lock is released. If a lock request conflicts with an existing lock and cannot be granted because it would cause deadlock, an error occurs.

Thus, intention locks do not block anything except full table requests (for example, ). The main purpose of and locks is to show that someone is locking a row, or going to lock a row in the table.

The following example illustrates how an error can occur when a lock request would cause a deadlock. The example involves two clients, A and B.

First, client A creates a table containing one row, and then begins a transaction. Within the transaction, A obtains an lock on the row by selecting it in share mode:

mysql> 
Query OK, 0 rows affected (1.07 sec)

mysql> 
Query OK, 1 row affected (0.09 sec)

mysql> 
Query OK, 0 rows affected (0.00 sec)

mysql> 
+------+
| i    |
+------+
|    1 |
+------+
1 row in set (0.10 sec)

Next, client B begins a transaction and attempts to delete the row from the table:

mysql> 
Query OK, 0 rows affected (0.00 sec)

mysql> 

The delete operation requires an lock. The lock cannot be granted because it is incompatible with the lock that client A holds, so the request goes on the queue of lock requests for the row and client B blocks.

Finally, client A also attempts to delete the row from the table:

mysql> 
ERROR 1213 (40001): Deadlock found when trying to get lock;
try restarting transaction

Deadlock occurs here because client A needs an lock to delete the row. However, that lock request cannot be granted because client B is already has a request for an lock and is waiting for client A to release its lock. Nor can the lock held by A be upgraded to an lock because of the prior request by B for an lock. As a result, generates an error for client A and releases its locks. At that point, the lock request for client B can be granted and B deletes the row from the table.

14.2.10.2.  and

In , all user activity occurs inside a transaction. If the autocommit mode is enabled, each SQL statement forms a single transaction on its own. By default, MySQL starts new connections with autocommit enabled.

If the autocommit mode is switched off with , then we can consider that a user always has a transaction open. An SQL or statement ends the current transaction and a new one starts. A means that the changes made in the current transaction are made permanent and become visible to other users. A statement, on the other hand, cancels all modifications made by the current transaction. Both statements release all locks that were set during the current transaction.

If the connection has autocommit enabled, the user can still perform a multiple-statement transaction by starting it with an explicit or statement and ending it with or .

14.2.10.3.  and

In terms of the SQL:1992 transaction isolation levels, the default is . offers all four transaction isolation levels described by the SQL standard. You can set the default isolation level for all connections by using the option on the command line or in an option file. For example, you can set the option in the section of an option file like this:

[mysqld]
transaction-isolation = {READ-UNCOMMITTED | READ-COMMITTED
                         | REPEATABLE-READ | SERIALIZABLE}

A user can change the isolation level for a single session or for all new incoming connections with the statement. Its syntax is as follows:

SET [SESSION | GLOBAL] TRANSACTION ISOLATION LEVEL
                       {READ UNCOMMITTED | READ COMMITTED
                        | REPEATABLE READ | SERIALIZABLE}

Note that there are hyphens in the level names for the option, but not for the statement.

The default behavior is to set the isolation level for the next (not started) transaction. If you use the keyword, the statement sets the default transaction level globally for all new connections created from that point on (but not for existing connections). You need the privilege to do this. Using the keyword sets the default transaction level for all future transactions performed on the current connection.

Any client is free to change the session isolation level (even in the middle of a transaction), or the isolation level for the next transaction.

You can determine the global and session transaction isolation levels by checking the value of the system variable with these statements:

SELECT @@global.tx_isolation;
SELECT @@tx_isolation;

In row-level locking, uses next-key locking. That means that besides index records, can also lock the “gap” preceding an index record to block insertions by other users immediately before the index record. A next-key lock refers to a lock that locks an index record and the gap before it. A gap lock refers to a lock that only locks a gap before some index record.

A detailed description of each isolation level in follows:

  • statements are performed in a non-locking fashion, but a possible earlier version of a record might be used. Thus, using this isolation level, such reads are not consistent. This is also called a “dirty read.” Otherwise, this isolation level works like .

  • A somewhat Oracle-like isolation level. All and statements lock only the index records, not the gaps before them, and thus allow the free insertion of new records next to locked records. and statements using a unique index with a unique search condition lock only the index record found, not the gap before it. In range-type and statements, must set next-key or gap locks and block insertions by other users to the gaps covered by the range. This is necessary because “phantom rows” must be blocked for MySQL replication and recovery to work.

    Consistent reads behave as in Oracle: Each consistent read, even within the same transaction, sets and reads its own fresh snapshot. See Section 14.2.10.4, “Consistent Non-Locking Read”.

  • This is the default isolation level of . , , , and statements that use a unique index with a unique search condition lock only the index record found, not the gap before it. With other search conditions, these operations employ next-key locking, locking the index range scanned with next-key or gap locks, and block new insertions by other users.

    In consistent reads, there is an important difference from the isolation level: All consistent reads within the same transaction read the same snapshot established by the first read. This convention means that if you issue several plain statements within the same transaction, these statements are consistent also with respect to each other. See Section 14.2.10.4, “Consistent Non-Locking Read”.

  • This level is like , but implicitly commits all plain statements to .

14.2.10.4. Consistent Non-Locking Read

A consistent read means that uses multi-versioning to present to a query a snapshot of the database at a point in time. The query see the changes made by those transactions that committed before that point of time, and no changes made by later or uncommitted transactions. The exception to this rule is that the query sees the changes made by earlier statements within the same transaction. Note that the exception to the rule causes the following anomaly: if you update some rows in a table, a will see the latest version of the updated rows, while it sees the old version of other rows. If other users simultaneously update the same table, the anomaly means that you may see the table in a state that never existed in the database.

If you are running with the default isolation level, all consistent reads within the same transaction read the snapshot established by the first such read in that transaction. You can get a fresher snapshot for your queries by committing the current transaction and after that issuing new queries.

Consistent read is the default mode in which processes statements in and isolation levels. A consistent read does not set any locks on the tables it accesses, and therefore other users are free to modify those tables at the same time a consistent read is being performed on the table.

Note that consistent read does not work over and over . Consistent read does not work over because MySQL can't use a table that has been dropped and destroys the table. Consistent read does not work over because works by making a temporary copy of the original table and deleting the original table when the temporary copy is built. When you reissue a consistent read within a transaction, rows in the new table are not visible because those rows did not exist when the transaction's snapshot was taken.

14.2.10.5.  and Locking Reads

In some circumstances, a consistent read is not convenient. For example, you might want to add a new row into your table , and make sure that the child has a parent in table . The following example shows how to implement referential integrity in your application code.

Suppose that you use a consistent read to read the table and indeed see the parent of the child in the table. Can you safely add the child row to table ? No, because it may happen that meanwhile some other user deletes the parent row from the table without you being aware of it.

The solution is to perform the in a locking mode using :

SELECT * FROM parent WHERE NAME = 'Jones' LOCK IN SHARE MODE;

Performing a read in share mode means that we read the latest available data, and set a shared mode lock on the rows we read. A shared mode lock prevents others from updating or deleting the row we have read. Also, if the latest data belongs to a yet uncommitted transaction of another client connection, we wait until that transaction commits. After we see that the preceding query returns the parent , we can safely add the child record to the table and commit our transaction.

Let us look at another example: We have an integer counter field in a table that we use to assign a unique identifier to each child added to table . Obviously, using a consistent read or a shared mode read to read the present value of the counter is not a good idea because two users of the database may then see the same value for the counter, and a duplicate-key error occurs if two users attempt to add children with the same identifier to the table.

Here, is not a good solution because if two users read the counter at the same time, at least one of them ends up in deadlock when attempting to update the counter.

In this case, there are two good ways to implement the reading and incrementing of the counter: (1) update the counter first by incrementing it by 1 and only after that read it, or (2) read the counter first with a lock mode , and increment after that. The latter approach can be implemented as follows:

SELECT counter_field FROM child_codes FOR UPDATE;
UPDATE child_codes SET counter_field = counter_field + 1;

A reads the latest available data, setting exclusive locks on each row it reads. Thus, it sets the same locks a searched SQL would set on the rows.

The preceding description is merely an example of how works. In MySQL, the specific task of generating a unique identifier actually can be accomplished using only a single access to the table:

UPDATE child_codes SET counter_field = LAST_INSERT_ID(counter_field + 1);
SELECT LAST_INSERT_ID();

The statement merely retrieves the identifier information (specific to the current connection). It does not access any table.

Locks set by and reads are released when the transaction is committed or rolled back.

14.2.10.6. Next-Key Locking: Avoiding the Phantom Problem

In row-level locking, uses an algorithm called next-key locking. performs the row-level locking in such a way that when it searches or scans an index of a table, it sets shared or exclusive locks on the index records it encounters. Thus, the row-level locks are actually index record locks.

The locks sets on index records also affect the “gap” before that index record. If a user has a shared or exclusive lock on record in an index, another user cannot insert a new index record immediately before in the index order. This locking of gaps is done to prevent the so-called “phantom problem.” Suppose that you want to read and lock all children from the table having an identifier value greater than 100, with the intention of updating some column in the selected rows later:

SELECT * FROM child WHERE id > 100 FOR UPDATE;

Suppose that there is an index on the column. The query scans that index starting from the first record where is bigger than 100. If the locks set on the index records would not lock out inserts made in the gaps, a new row might meanwhile be inserted to the table. If you execute the same within the same transaction, you would see a new row in the result set returned by the query. This is contrary to the isolation principle of transactions: A transaction should be able to run so that the data it has read does not change during the transaction. If we regard a set of rows as a data item, the new “phantom” child would violate this isolation principle.

When scans an index, it can also lock the gap after the last record in the index. Just that happens in the previous example: The locks set by prevent any insert to the table where would be bigger than 100.

You can use next-key locking to implement a uniqueness check in your application: If you read your data in share mode and do not see a duplicate for a row you are going to insert, then you can safely insert your row and know that the next-key lock set on the successor of your row during the read prevents anyone meanwhile inserting a duplicate for your row. Thus, the next-key locking allows you to “lock” the non-existence of something in your table.

14.2.10.7. An Example of Consistent Read in

Suppose that you are running in the default isolation level. When you issue a consistent read (that is, an ordinary statement), gives your transaction a timepoint according to which your query sees the database. If another transaction deletes a row and commits after your timepoint was assigned, you do not see the row as having been deleted. Inserts and updates are treated similarly.

You can advance your timepoint by committing your transaction and then doing another .

This is called multi-versioned concurrency control.

               User A                 User B

           SET AUTOCOMMIT=0;      SET AUTOCOMMIT=0;
time
|          SELECT * FROM t;
|          empty set
|                                 INSERT INTO t VALUES (1, 2);
|
v          SELECT * FROM t;
           empty set
                                  COMMIT;

           SELECT * FROM t;
           empty set

           COMMIT;

           SELECT * FROM t;
           ---------------------
           |    1    |    2    |
           ---------------------
           1 row in set

In this example, user A sees the row inserted by B only when B has committed the insert and A has committed as well, so that the timepoint is advanced past the commit of B.

If you want to see the “freshest” state of the database, you should use either the isolation level or a locking read:

SELECT * FROM t LOCK IN SHARE MODE;

14.2.10.8. Locks Set by Different SQL Statements in

A locking read, an , or a generally set record locks on every index record that is scanned in the processing of the SQL statement. It does not matter if there are conditions in the statement that would exclude the row. does not remember the exact condition, but only knows which index ranges were scanned. The record locks are normally next-key locks that also block inserts to the “gap” immediately before the record.

If the locks to be set are exclusive, always retrieves also the clustered index record and sets a lock on it.

If you do not have indexes suitable for your statement and MySQL has to scan the whole table to process the statement, every row of the table becomes locked, which in turn blocks all inserts by other users to the table. It is important to create good indexes so that your queries do not unnecessarily need to scan many rows.

sets specific types of locks as follows:

  • is a consistent read, reading a snapshot of the database and setting no locks unless the transaction isolation level is set to . For level, this sets shared next-key locks on the index records it encounters.

  • sets shared next-key locks on all index records the read encounters.

  • sets exclusive next-key locks on all index records the read encounters.

  • sets an exclusive lock on the inserted row. Note that this lock is not a next-key lock and does not prevent other users from inserting to the gap before the inserted row. If a duplicate-key error occurs, a shared lock on the duplicate index record is set.

  • While initializing a previously specified column on a table, sets an exclusive lock on the end of the index associated with the column. In accessing the auto-increment counter, uses a specific table lock mode where the lock lasts only to the end of the current SQL statement, not to the end of the entire transaction. Note that other clients cannot insert into the table while the table lock is held; see Section 14.2.10.2, “ and .

    fetches the value of a previously initialized column without setting any locks.

  • sets an exclusive (non-next-key) lock on each row inserted into . sets shared next-key locks locks on , unless is enabled, in which case it does the search on as a consistent read. has to set locks in the latter case: In roll-forward recovery from a backup, every SQL statement has to be executed in exactly the same way it was done originally.

  • performs the as a consistent read or with shared locks, as in the previous item.

  • is done like an insert if there is no collision on a unique key. Otherwise, an exclusive next-key lock is placed on the row that has to be updated.

  • sets an exclusive next-key lock on every record the search encounters.

  • sets an exclusive next-key lock on every record the search encounters.

  • If a constraint is defined on a table, any insert, update, or delete that requires the constraint condition to be checked sets shared record-level locks on the records that it looks at to check the constraint. also sets these locks in the case where the constraint fails.

  • sets table locks, but it is the higher MySQL layer above the layer that sets these locks. is aware of table locks if (the default) and , and the MySQL layer above knows about row-level locks. Otherwise, 's automatic deadlock detection cannot detect deadlocks where such table locks are involved. Also, because the higher MySQL layer does not know about row-level locks, it is possible to get a table lock on a table where another user currently has row-level locks. However, this does not endanger transaction integrity, as discussed in Section 14.2.10.10, “Deadlock Detection and Rollback”. See also Section 14.2.16, “Restrictions on Tables”.

14.2.10.9. Implicit Transaction Commit and Rollback

By default, MySQL begins each client connection with autocommit mode enabled. When autocommit is enabled, MySQL does a commit after each SQL statement if that statement did not return an error. If an SQL statement returns an error, the commit or rollback behavior depends on the error. See Section 14.2.15, “ Error Handling”.

If you have the autocommit mode off and close a connection without explicitly committing the final transaction, MySQL rolls back that transaction.

Each of the following statements (and any synonyms for them) implicitly end a transaction, as if you had done a before executing the statement:

  • , , , , , , , , , , , , , , , , , , , , .

  • commits a transaction only if any tables are currently locked.

  • The , , and statements cause an implicit commit beginning with MySQL 5.0.8. The , , , , , and statements cause an implicit commit beginning with MySQL MySQL 5.0.13.

  • The statement in is processed as a single transaction. This means that a from the user does not undo statements the user made during that transaction.

Transactions cannot be nested. This is a consequence of the implicit performed for any current transaction when you issue a statement or one of its synonyms.

Statements that cause implicit cannot be used in an XA transaction while the transaction is in an state.

14.2.10.10. Deadlock Detection and Rollback

automatically detects a deadlock of transactions and rolls back a transaction or transactions to break the deadlock. tries to pick small transactions to roll back, where the size of a transaction is determined by the number of rows inserted, updated, or deleted.

is aware of table locks if (the default) and , and the MySQL layer above it knows about row-level locks. Otherwise, cannot detect deadlocks where a table lock set by a MySQL statement or a lock set by a storage engine other than is involved. You must resolve these situations by setting the value of the system variable.

When performs a complete rollback of a transaction, all locks set by the transaction are released. However, if just a single SQL statement is rolled back as a result of an error, some of the locks set by the statement may be preserved. This happens because stores row locks in a format such that it cannot know afterward which lock was set by which statement.

14.2.10.11. How to Cope with Deadlocks

Deadlocks are a classic problem in transactional databases, but they are not dangerous unless they are so frequent that you cannot run certain transactions at all. Normally, you must write your applications so that they are always prepared to re-issue a transaction if it gets rolled back because of a deadlock.

uses automatic row-level locking. You can get deadlocks even in the case of transactions that just insert or delete a single row. That is because these operations are not really “atomic”; they automatically set locks on the (possibly several) index records of the row inserted or deleted.

You can cope with deadlocks and reduce the likelihood of their occurrence with the following techniques:

  • Use to determine the cause of the latest deadlock. That can help you to tune your application to avoid deadlocks.

  • Always be prepared to re-issue a transaction if it fails due to deadlock. Deadlocks are not dangerous. Just try again.

  • Commit your transactions often. Small transactions are less prone to collision.

  • If you are using locking reads ( or ), try using a lower isolation level such as .

  • Access your tables and rows in a fixed order. Then transactions form well-defined queues and do not deadlock.

  • Add well-chosen indexes to your tables. Then your queries need to scan fewer index records and consequently set fewer locks. Use to determine which indexes the MySQL server regards as the most appropriate for your queries.

  • Use less locking. If you can afford to allow a to return data from an old snapshot, do not add the clause or to it. Using the isolation level is good here, because each consistent read within the same transaction reads from its own fresh snapshot.

  • If nothing else helps, serialize your transactions with table-level locks. The correct way to use with transactional tables, such as tables, is to set and not to call until after you commit the transaction explicitly. For example, if you need to write to table and read from table , you can do this:

    SET AUTOCOMMIT=0;
    LOCK TABLES t1 WRITE, t2 READ, ...;
    
    COMMIT;
    UNLOCK TABLES;
    

    Table-level locks make your transactions queue nicely, and deadlocks are avoided.

  • Another way to serialize transactions is to create an auxiliary “semaphore” table that contains just a single row. Have each transaction update that row before accessing other tables. In that way, all transactions happen in a serial fashion. Note that the instant deadlock detection algorithm also works in this case, because the serializing lock is a row-level lock. With MySQL table-level locks, the timeout method must be used to resolve deadlocks.

  • In applications that use the command, MySQL does not set table locks if .

14.2.11. InnoDB Performance Tuning Tips

  • In , having a long wastes a lot of disk space because its value must be stored with every secondary index record. (See Section 14.2.13, “ Table and Index Structures”.) Create an column as the primary key if your primary key is long.

  • If the Unix tool or the Windows Task Manager shows that the CPU usage percentage with your workload is less than 70%, your workload is probably disk-bound. Maybe you are making too many transaction commits, or the buffer pool is too small. Making the buffer pool bigger can help, but do not set it equal to more than 80% of physical memory.

  • Wrap several modifications into one transaction. must flush the log to disk at each transaction commit if that transaction made modifications to the database. The rotation speed of a disk is typically at most 167 revolutions/second, which constrains the number of commits to the same 167th of a second if the disk does not “fool” the operating system.

  • If you can afford the loss of some of the latest committed transactions if a crash occurs, you can set the parameter to 0. tries to flush the log once per second anyway, although the flush is not guaranteed.

  • Make your log files big, even as big as the buffer pool. When has written the log files full, it has to write the modified contents of the buffer pool to disk in a checkpoint. Small log files cause many unnecessary disk writes. The drawback of big log files is that the recovery time is longer.

  • Make the log buffer quite large as well (on the order of 8MB).

  • Use the data type instead of if you are storing variable-length strings or if the column may contain many values. A ) column always takes characters to store data, even if the string is shorter or its value is . Smaller tables fit better in the buffer pool and reduce disk I/O.

    When using (the default record format in MySQL 5.0) and variable-length character sets, such as or , ) will occupy a variable amount of space, at least bytes.

  • In some versions of GNU/Linux and Unix, flushing files to disk with the Unix call (which uses by default) and other similar methods is surprisingly slow. If you are dissatisfied with database write performance, you might try setting the parameter to . Although seems to be slower on most systems, yours might not be one of them.

  • When using the storage engine on Solaris 10 for x86_64 architecture (AMD Opteron), it is important to mount any filesystems used for storing -related files using the option. (The default on Solaris 10/x86_64 is not to use this option.) Failure to use causes a serious degradation of 's speed and performance on this platform.

    When using the storage engine with a large value on any release of Solaris 2.6 and up and any platform (sparc/x86/x64/amd64), a significant performance gain can be achieved by placing data files and log files on raw devices or on a separate direct I/O UFS filesystem (using mount option ; see ). Users of the Veritas filesystem VxFS should use the mount option .

    Other MySQL data files, such as those for tables, should not be placed on a direct I/O filesystem. Executables or libraries must not be placed on a direct I/O filesystem.

  • When importing data into , make sure that MySQL does not have autocommit mode enabled because that requires a log flush to disk for every insert. To disable autocommit during your import operation, surround it with and statements:

    SET AUTOCOMMIT=0;
    
    COMMIT;
    

    If you use the mysqldump option , you get dump files that are fast to import into an table, even without wrapping them with the and statements.

  • Beware of big rollbacks of mass inserts: uses the insert buffer to save disk I/O in inserts, but no such mechanism is used in a corresponding rollback. A disk-bound rollback can take 30 times as long to perform as the corresponding insert. Killing the database process does not help because the rollback starts again on server startup. The only way to get rid of a runaway rollback is to increase the buffer pool so that the rollback becomes CPU-bound and runs fast, or to use a special procedure. See Section 14.2.8.1, “Forcing Recovery”.

  • Beware also of other big disk-bound operations. Use and to empty a table, not .

  • Use the multiple-row syntax to reduce communication overhead between the client and the server if you need to insert many rows:

    INSERT INTO yourtable VALUES (1,2), (5,5), ...;
    

    This tip is valid for inserts into any table, not just tables.

  • If you have constraints on secondary keys, you can speed up table imports by temporarily turning off the uniqueness checks during the import session:

    SET UNIQUE_CHECKS=0;
    
    SET UNIQUE_CHECKS=1;
    

    For big tables, this saves a lot of disk I/O because can use its insert buffer to write secondary index records in a batch. Be certain that the data contains no duplicate keys. allows but does not require storage engines to ignore duplicate keys.

  • If you have constraints in your tables, you can speed up table imports by turning the foreign key checks off for the duration of the import session:

    SET FOREIGN_KEY_CHECKS=0;
    
    SET FOREIGN_KEY_CHECKS=1;
    

    For big tables, this can save a lot of disk I/O.

  • If you often have recurring queries for tables that are not updated frequently, use the query cache:

    [mysqld]
    query_cache_type = ON
    query_cache_size = 10M
    

14.2.11.1.  and the Monitors

includes Monitors that print information about the internal state. You can use the SQL statement at any time to fetch the output of the standard Monitor to your SQL client. This information is useful in performance tuning. (If you are using the mysql interactive SQL client, the output is more readable if you replace the usual semicolon statement terminator with .) For a discussion of lock modes, see Section 14.2.10.1, “ Lock Modes”.

mysql> 

Another way to use Monitors is to let them periodically write data to the standard output of the mysqld server. In this case, no output is sent to clients. When switched on, Monitors print data about every 15 seconds. Server output usually is directed to the log in the MySQL data directory. This data is useful in performance tuning. On Windows, you must start the server from a command prompt in a console window with the option if you want to direct the output to the window rather than to the error log.

Monitor output includes the following types of information:

  • Table and record locks held by each active transaction

  • Lock waits of a transactions

  • Semaphore waits of threads

  • Pending file I/O requests

  • Buffer pool statistics

  • Purge and insert buffer merge activity of the main thread

To cause the standard Monitor to write to the standard output of mysqld, use the following SQL statement:

CREATE TABLE innodb_monitor (a INT) ENGINE=INNODB;

The monitor can be stopped by issuing the following statement:

DROP TABLE innodb_monitor;

The syntax is just a way to pass a command to the engine through MySQL's SQL parser: The only things that matter are the table name and that it be an table. The structure of the table is not relevant at all for the Monitor. If you shut down the server, the monitor does not restart automatically when you restart the server. You must drop the monitor table and issue a new statement to start the monitor. (This syntax may change in a future release.)

You can use in a similar fashion. This is the same as , except that it also provides a great deal of lock information. A separate prints a list of created file segments existing in the tablespace and validates the tablespace allocation data structures. In addition, there is with which you can print the contents of the internal data dictionary.

A sample of Monitor output:

mysql> 
*************************** 1. row ***************************
Status:
=====================================
030709 13:00:59 INNODB MONITOR OUTPUT
=====================================
Per second averages calculated from the last 18 seconds
----------
SEMAPHORES
----------
OS WAIT ARRAY INFO: reservation count 413452, signal count 378357
--Thread 32782 has waited at btr0sea.c line 1477 for 0.00 seconds the
semaphore: X-lock on RW-latch at 41a28668 created in file btr0sea.c line 135
a writer (thread id 32782) has reserved it in mode wait exclusive
number of readers 1, waiters flag 1
Last time read locked in file btr0sea.c line 731
Last time write locked in file btr0sea.c line 1347
Mutex spin waits 0, rounds 0, OS waits 0
RW-shared spins 108462, OS waits 37964; RW-excl spins 681824, OS waits
375485
------------------------
LATEST FOREIGN KEY ERROR
------------------------
030709 13:00:59 Transaction:
TRANSACTION 0 290328284, ACTIVE 0 sec, process no 3195, OS thread id 34831
inserting
15 lock struct(s), heap size 2496, undo log entries 9
MySQL thread id 25, query id 4668733 localhost heikki update
insert into ibtest11a (D, B, C) values (5, 'khDk' ,'khDk')
Foreign key constraint fails for table test/ibtest11a:
,
  CONSTRAINT `0_219242` FOREIGN KEY (`A`, `D`) REFERENCES `ibtest11b` (`A`,
  `D`) ON DELETE CASCADE ON UPDATE CASCADE
Trying to add in child table, in index PRIMARY tuple:
 0: len 4; hex 80000101; asc ....;; 1: len 4; hex 80000005; asc ....;; 2:
 len 4; hex 6b68446b; asc khDk;; 3: len 6; hex 0000114e0edc; asc ...N..;; 4:
 len 7; hex 00000000c3e0a7; asc .......;; 5: len 4; hex 6b68446b; asc khDk;;
But in parent table test/ibtest11b, in index PRIMARY,
the closest match we can find is record:
RECORD: info bits 0 0: len 4; hex 8000015b; asc ...[;; 1: len 4; hex
80000005; asc ....;; 2: len 3; hex 6b6864; asc khd;; 3: len 6; hex
0000111ef3eb; asc ......;; 4: len 7; hex 800001001e0084; asc .......;; 5:
len 3; hex 6b6864; asc khd;;
------------------------
LATEST DETECTED DEADLOCK
------------------------
030709 12:59:58
*** (1) TRANSACTION:
TRANSACTION 0 290252780, ACTIVE 1 sec, process no 3185, OS thread id 30733
inserting
LOCK WAIT 3 lock struct(s), heap size 320, undo log entries 146
MySQL thread id 21, query id 4553379 localhost heikki update
INSERT INTO alex1 VALUES(86, 86, 794,'aA35818','bb','c79166','d4766t',
'e187358f','g84586','h794',date_format('2001-04-03 12:54:22','%Y-%m-%d
%H:%i'),7
*** (1) WAITING FOR THIS LOCK TO BE GRANTED:
RECORD LOCKS space id 0 page no 48310 n bits 568 table test/alex1 index
symbole trx id 0 290252780 lock mode S waiting
Record lock, heap no 324 RECORD: info bits 0 0: len 7; hex 61613335383138;
asc aa35818;; 1:
*** (2) TRANSACTION:
TRANSACTION 0 290251546, ACTIVE 2 sec, process no 3190, OS thread id 32782
inserting
130 lock struct(s), heap size 11584, undo log entries 437
MySQL thread id 23, query id 4554396 localhost heikki update
REPLACE INTO alex1 VALUES(NULL, 32, NULL,'aa3572','','c3572','d6012t','',
NULL,'h396', NULL, NULL, 7.31,7.31,7.31,200)
*** (2) HOLDS THE LOCK(S):
RECORD LOCKS space id 0 page no 48310 n bits 568 table test/alex1 index
symbole trx id 0 290251546 lock_mode X locks rec but not gap
Record lock, heap no 324 RECORD: info bits 0 0: len 7; hex 61613335383138;
asc aa35818;; 1:
*** (2) WAITING FOR THIS LOCK TO BE GRANTED:
RECORD LOCKS space id 0 page no 48310 n bits 568 table test/alex1 index
symbole trx id 0 290251546 lock_mode X locks gap before rec insert intention
waiting
Record lock, heap no 82 RECORD: info bits 0 0: len 7; hex 61613335373230;
asc aa35720;; 1:
*** WE ROLL BACK TRANSACTION (1)
------------
TRANSACTIONS
------------
Trx id counter 0 290328385
Purge done for trx's n:o < 0 290315608 undo n:o < 0 17
Total number of lock structs in row lock hash table 70
LIST OF TRANSACTIONS FOR EACH SESSION:
---TRANSACTION 0 0, not started, process no 3491, OS thread id 42002
MySQL thread id 32, query id 4668737 localhost heikki
show innodb status
---TRANSACTION 0 290328384, ACTIVE 0 sec, process no 3205, OS thread id
38929 inserting
1 lock struct(s), heap size 320
MySQL thread id 29, query id 4668736 localhost heikki update
insert into speedc values (1519229,1, 'hgjhjgghggjgjgjgjgjggjgjgjgjgjgggjgjg
jlhhgghggggghhjhghgggggghjhghghghghghhhhghghghjhhjghjghjkghjghjghjghjfhjfh
---TRANSACTION 0 290328383, ACTIVE 0 sec, process no 3180, OS thread id
28684 committing
1 lock struct(s), heap size 320, undo log entries 1
MySQL thread id 19, query id 4668734 localhost heikki update
insert into speedcm values (1603393,1, 'hgjhjgghggjgjgjgjgjggjgjgjgjgjgggjgj
gjlhhgghggggghhjhghgggggghjhghghghghghhhhghghghjhhjghjghjkghjghjghjghjfhjf
---TRANSACTION 0 290328327, ACTIVE 0 sec, process no 3200, OS thread id
36880 starting index read
LOCK WAIT 2 lock struct(s), heap size 320
MySQL thread id 27, query id 4668644 localhost heikki Searching rows for
update
update ibtest11a set B = 'kHdkkkk' where A = 89572
------- TRX HAS BEEN WAITING 0 SEC FOR THIS LOCK TO BE GRANTED:
RECORD LOCKS space id 0 page no 65556 n bits 232 table test/ibtest11a index
PRIMARY trx id 0 290328327 lock_mode X waiting
Record lock, heap no 1 RECORD: info bits 0 0: len 9; hex 73757072656d756d00;
asc supremum.;;
------------------
---TRANSACTION 0 290328284, ACTIVE 0 sec, process no 3195, OS thread id
34831 rollback of SQL statement
ROLLING BACK 14 lock struct(s), heap size 2496, undo log entries 9
MySQL thread id 25, query id 4668733 localhost heikki update
insert into ibtest11a (D, B, C) values (5, 'khDk' ,'khDk')
---TRANSACTION 0 290327208, ACTIVE 1 sec, process no 3190, OS thread id
32782
58 lock struct(s), heap size 5504, undo log entries 159
MySQL thread id 23, query id 4668732 localhost heikki update
REPLACE INTO alex1 VALUES(86, 46, 538,'aa95666','bb','c95666','d9486t',
'e200498f','g86814','h538',date_format('2001-04-03 12:54:22','%Y-%m-%d
%H:%i'),
---TRANSACTION 0 290323325, ACTIVE 3 sec, process no 3185, OS thread id
30733 inserting
4 lock struct(s), heap size 1024, undo log entries 165
MySQL thread id 21, query id 4668735 localhost heikki update
INSERT INTO alex1 VALUES(NULL, 49, NULL,'aa42837','','c56319','d1719t','',
NULL,'h321', NULL, NULL, 7.31,7.31,7.31,200)
--------
FILE I/O
--------
I/O thread 0 state: waiting for i/o request (insert buffer thread)
I/O thread 1 state: waiting for i/o request (log thread)
I/O thread 2 state: waiting for i/o request (read thread)
I/O thread 3 state: waiting for i/o request (write thread)
Pending normal aio reads: 0, aio writes: 0,
 ibuf aio reads: 0, log i/o's: 0, sync i/o's: 0
Pending flushes (fsync) log: 0; buffer pool: 0
151671 OS file reads, 94747 OS file writes, 8750 OS fsyncs
25.44 reads/s, 18494 avg bytes/read, 17.55 writes/s, 2.33 fsyncs/s
-------------------------------------
INSERT BUFFER AND ADAPTIVE HASH INDEX
-------------------------------------
Ibuf for space 0: size 1, free list len 19, seg size 21,
85004 inserts, 85004 merged recs, 26669 merges
Hash table size 207619, used cells 14461, node heap has 16 buffer(s)
1877.67 hash searches/s, 5121.10 non-hash searches/s
---
LOG
---
Log sequence number 18 1212842764
Log flushed up to   18 1212665295
Last checkpoint at  18 1135877290
0 pending log writes, 0 pending chkp writes
4341 log i/o's done, 1.22 log i/o's/second
----------------------
BUFFER POOL AND MEMORY
----------------------
Total memory allocated 84966343; in additional pool allocated 1402624
Buffer pool size   3200
Free buffers       110
Database pages     3074
Modified db pages  2674
Pending reads 0
Pending writes: LRU 0, flush list 0, single page 0
Pages read 171380, created 51968, written 194688
28.72 reads/s, 20.72 creates/s, 47.55 writes/s
Buffer pool hit rate 999 / 1000
--------------
ROW OPERATIONS
--------------
0 queries inside InnoDB, 0 queries in queue
Main thread process no. 3004, id 7176, state: purging
Number of rows inserted 3738558, updated 127415, deleted 33707, read 755779
1586.13 inserts/s, 50.89 updates/s, 28.44 deletes/s, 107.88 reads/s
----------------------------
END OF INNODB MONITOR OUTPUT
============================

Some notes on the output:

  • If the section reports lock waits, your applications may have lock contention. The output can also help to trace the reasons for transaction deadlocks.

  • The section reports threads waiting for a semaphore and statistics on how many times threads have needed a spin or a wait on a mutex or a rw-lock semaphore. A large number of threads waiting for semaphores may be a result of disk I/O, or contention problems inside . Contention can be due to heavy parallelism of queries or problems in operating system thread scheduling. Setting smaller than the default value can help in such situations.

  • The section gives you statistics on pages read and written. You can calculate from these numbers how many data file I/O operations your queries currently are doing.

  • The section shows what the main thread is doing.

sends diagnostic output to or to files rather than to or fixed-size memory buffers, to avoid potential buffer overflows. As a side effect, the output of is written to a status file in the MySQL data directory every fifteen seconds. The name of the file is , where is the server process ID. removes the file for a normal shutdown. If abnormal shutdowns have occurred, instances of these status files may be present and must be removed manually. Before removing them, you might want to examine them to see whether they contain useful information about the cause of abnormal shutdowns. The file is created only if the configuration option is set.

14.2.12. Implementation of Multi-Versioning

Because is a multi-versioned storage engine, it must keep information about old versions of rows in the tablespace. This information is stored in a data structure called a rollback segment (after an analogous data structure in Oracle).

Internally, adds two fields to each row stored in the database. A 6-byte field indicates the transaction identifier for the last transaction that inserted or updated the row. Also, a deletion is treated internally as an update where a special bit in the row is set to mark it as deleted. Each row also contains a 7-byte field called the roll pointer. The roll pointer points to an undo log record written to the rollback segment. If the row was updated, the undo log record contains the information necessary to rebuild the content of the row before it was updated.

uses the information in the rollback segment to perform the undo operations needed in a transaction rollback. It also uses the information to build earlier versions of a row for a consistent read.

Undo logs in the rollback segment are divided into insert and update undo logs. Insert undo logs are needed only in transaction rollback and can be discarded as soon as the transaction commits. Update undo logs are used also in consistent reads, but they can be discarded only after there is no transaction present for which has assigned a snapshot that in a consistent read could need the information in the update undo log to build an earlier version of a database row.

You must remember to commit your transactions regularly, including those transactions that issue only consistent reads. Otherwise, cannot discard data from the update undo logs, and the rollback segment may grow too big, filling up your tablespace.

The physical size of an undo log record in the rollback segment is typically smaller than the corresponding inserted or updated row. You can use this information to calculate the space need for your rollback segment.

In the multi-versioning scheme, a row is not physically removed from the database immediately when you delete it with an SQL statement. Only when can discard the update undo log record written for the deletion can it also physically remove the corresponding row and its index records from the database. This removal operation is called a purge, and it is quite fast, usually taking the same order of time as the SQL statement that did the deletion.

In a scenario where the user inserts and deletes rows in smallish batches at about the same rate in the table, it is possible that the purge thread starts to lag behind, and the table grows bigger and bigger, making everything disk-bound and very slow. Even if the table carries just 10MB of useful data, it may grow to occupy 10GB with all the “dead” rows. In such a case, it would be good to throttle new row operations, and allocate more resources to the purge thread. The system variable exists for exactly this purpose. See Section 14.2.4, “ Startup Options and System Variables”, for more information.

14.2.13. InnoDB Table and Index Structures

MySQL stores its data dictionary information for tables in files in database directories. This is true for all MySQL storage engines. But every table also has its own entry in the internal data dictionary inside the tablespace. When MySQL drops a table or a database, it has to delete both an file or files, and the corresponding entries inside the data dictionary. This is the reason why you cannot move tables between databases simply by moving the files.

Every table has a special index called the clustered index where the data for the rows is stored. If you define a on your table, the index of the primary key is the clustered index.

If you do not define a for your table, MySQL picks the first index that has only columns as the primary key and uses it as the clustered index. If there is no such index in the table, internally generates a clustered index where the rows are ordered by the row ID that assigns to the rows in such a table. The row ID is a 6-byte field that increases monotonically as new rows are inserted. Thus, the rows ordered by the row ID are physically in insertion order.

Accessing a row through the clustered index is fast because the row data is on the same page where the index search leads. If a table is large, the clustered index architecture often saves a disk I/O when compared to the traditional solution. (In many database systems, data storage uses a different page from the index record.)

In , the records in non-clustered indexes (also called secondary indexes) contain the primary key value for the row. uses this primary key value to search for the row from the clustered index. Note that if the primary key is long, the secondary indexes use more space.

compares and strings of different lengths such that the remaining length in the shorter string is treated as if padded with spaces.

14.2.13.1. Physical Structure of an Index

All indexes are B-trees where the index records are stored in the leaf pages of the tree. The default size of an index page is 16KB. When new records are inserted, tries to leave 1/16 of the page free for future insertions and updates of the index records.

If index records are inserted in a sequential order (ascending or descending), the resulting index pages are about 15/16 full. If records are inserted in a random order, the pages are from 1/2 to 15/16 full. If the fill factor of an index page drops below 1/2, tries to contract the index tree to free the page.

14.2.13.2. Insert Buffering

It is a common situation in database applications that the primary key is a unique identifier and new rows are inserted in the ascending order of the primary key. Thus, the insertions to the clustered index do not require random reads from a disk.

On the other hand, secondary indexes are usually non-unique, and insertions into secondary indexes happen in a relatively random order. This would cause a lot of random disk I/O operations without a special mechanism used in .

If an index record should be inserted to a non-unique secondary index, checks whether the secondary index page is in the buffer pool. If that is the case, does the insertion directly to the index page. If the index page is not found in the buffer pool, inserts the record to a special insert buffer structure. The insert buffer is kept so small that it fits entirely in the buffer pool, and insertions can be done very fast.

Periodically, the insert buffer is merged into the secondary index trees in the database. Often it is possible to merge several insertions to the same page of the index tree, saving disk I/O operations. It has been measured that the insert buffer can speed up insertions into a table up to 15 times.

The insert buffer merging may continue to happen after the inserting transaction has been committed. In fact, it may continue to happen after a server shutdown and restart (see Section 14.2.8.1, “Forcing Recovery”).

The insert buffer merging may take many hours, when many secondary indexes must be updated, and many rows have been inserted. During this time, disk I/O will be increased, which can cause significant slowdown on disk-bound queries. Another significant background I/O operation is the purge thread (see Section 14.2.12, “Implementation of Multi-Versioning”).

14.2.13.3. Adaptive Hash Indexes

If a table fits almost entirely in main memory, the fastest way to perform queries on it is to use hash indexes. has a mechanism that monitors index searches made to the indexes defined for a table. If notices that queries could benefit from building a hash index, it does so automatically.

Note that the hash index is always built based on an existing B-tree index on the table. can build a hash index on a prefix of any length of the key defined for the B-tree, depending on the pattern of searches that observes for the B-tree index. A hash index can be partial: It is not required that the whole B-tree index is cached in the buffer pool. builds hash indexes on demand for those pages of the index that are often accessed.

In a sense, tailors itself through the adaptive hash index mechanism to ample main memory, coming closer to the architecture of main-memory databases.

14.2.13.4. Physical Row Structure

The physical record structure for InnoDB tables is dependent on the MySQL version and the optional option used when the table was created. For InnoDB tables in MySQL earlier than 5.0.3, only the row format was available. For MySQL 5.0.3 and later, the default is to use the row format, but you can use the format to retain compatibility with older versions of InnoDB tables.

Records in InnoDB tables have the following characteristics:

  • Each index record contains a six-byte header. The header is used to link together consecutive records, and also in row-level locking.

  • Records in the clustered index contain fields for all user-defined columns. In addition, there is a six-byte field for the transaction ID and a seven-byte field for the roll pointer.

  • If no primary key was defined for a table, each clustered index record also contains a six-byte row ID field.

  • Each secondary index record contains also all the fields defined for the clustered index key.

  • A record contains also a pointer to each field of the record. If the total length of the fields in a record is less than 128 bytes, the pointer is one byte; otherwise, two bytes. The array of these pointers is called the record directory. The area where these pointers point is called the data part of the record.

  • Internally, InnoDB stores fixed-length character columns such as in a fixed-length format. InnoDB truncates trailing spaces from columns.

  • An SQL value reserves 1 or 2 bytes in the record directory. Besides that, an SQL value reserves zero bytes in the data part of the record if stored in a variable length column. In a fixed-length column, it reserves the fixed length of the column in the data part of the record. The motivation behind reserving the fixed space for values is that it enables an update of the column from to a non- value to be done in place without causing fragmentation of the index page.

Records in InnoDB tables have the following characteristics:

  • Each index record contains a five-byte header that may be preceded by a variable-length header. The header is used to link together consecutive records, and also in row-level locking.

  • The record header contains a bit vector for indicating columns. The bit vector occupies (+7)/8 bytes. Columns that are will not occupy other space than the bit in this vector.

  • For each non- variable-length field, the record header contains the length of the column in one or two bytes. Two bytes will only be needed if part of the column is stored externally or the maximum length exceeds 255 bytes and the actual length exceeds 127 bytes.

  • The record header is followed by the data contents of the columns. Columns that are are omitted.

  • Records in the clustered index contain fields for all user-defined columns. In addition, there is a six-byte field for the transaction ID and a seven-byte field for the roll pointer.

  • If no primary key was defined for a table, each clustered index record also contains a six-byte row ID field.

  • Each secondary index record contains also all the fields defined for the clustered index key.

  • Internally, InnoDB stores fixed-length, fixed-width character columns such as in a fixed-length format. InnoDB truncates trailing spaces from columns.

  • Internally, InnoDB attempts to store UTF-8 ) columns in bytes by trimming trailing spaces. In , such columns occupy 3* bytes. The motivation behind reserving the minimum space is that it in many cases enables an update of the column to be done in place without causing fragmentation of the index page.

14.2.14. InnoDB File Space Management and Disk I/O

14.2.14.1.  Disk I/O

uses simulated asynchronous disk I/O: creates a number of threads to take care of I/O operations, such as read-ahead.

There are two read-ahead heuristics in :

  • In sequential read-ahead, if notices that the access pattern to a segment in the tablespace is sequential, it posts in advance a batch of reads of database pages to the I/O system.

  • In random read-ahead, if notices that some area in a tablespace seems to be in the process of being fully read into the buffer pool, it posts the remaining reads to the I/O system.

uses a novel file flush technique called doublewrite. It adds safety to recovery following an operating system crash or a power outage, and improves performance on most varieties of Unix by reducing the need for operations.

Doublewrite means that before writing pages to a data file, first writes them to a contiguous tablespace area called the doublewrite buffer. Only after the write and the flush to the doublewrite buffer has completed does write the pages to their proper positions in the data file. If the operating system crashes in the middle of a page write, can later find a good copy of the page from the doublewrite buffer during recovery.

14.2.14.2. File Space Management

The data files that you define in the configuration file form the tablespace of . The files are simply concatenated to form the tablespace. There is no striping in use. Currently, you cannot define where within the tablespace your tables are allocated. However, in a newly created tablespace, allocates space starting from the first data file.

The tablespace consists of database pages with a default size of 16KB. The pages are grouped into extents of 64 consecutive pages. The “files” inside a tablespace are called segments in . The term “rollback segment” is somewhat confusing because it actually contains many tablespace segments.

Two segments are allocated for each index in . One is for non-leaf nodes of the B-tree, the other is for the leaf nodes. The idea here is to achieve better sequentiality for the leaf nodes, which contain the data.

When a segment grows inside the tablespace, allocates the first 32 pages to it individually. After that starts to allocate whole extents to the segment. can add to a large segment up to 4 extents at a time to ensure good sequentiality of data.

Some pages in the tablespace contain bitmaps of other pages, and therefore a few extents in an tablespace cannot be allocated to segments as a whole, but only as individual pages.

When you ask for available free space in the tablespace by issuing a statement, reports the extents that are definitely free in the tablespace. always reserves some extents for cleanup and other internal purposes; these reserved extents are not included in the free space.

When you delete data from a table, contracts the corresponding B-tree indexes. Whether the freed space becomes available for other users depends on whether the pattern of deletes frees individual pages or extents to the tablespace. Dropping a table or deleting all rows from it is guaranteed to release the space to other users, but remember that deleted rows are physically removed only in an (automatic) purge operation after they are no longer needed for transaction rollbacks or consistent reads. (See Section 14.2.12, “Implementation of Multi-Versioning”.)

14.2.14.3. Defragmenting a Table

If there are random insertions into or deletions from the indexes of a table, the indexes may become fragmented. Fragmentation means that the physical ordering of the index pages on the disk is not close to the index ordering of the records on the pages, or that there are many unused pages in the 64-page blocks that were allocated to the index.

A symptom of fragmentation is that a table takes more space than it “should” take. How much that is exactly, is difficult to determine. All data and indexes are stored in B-trees, and their fill factor may vary from 50% to 100%. Another symptom of fragmentation is that a table scan such as this takes more time than it “should” take:

SELECT COUNT(*) FROM t WHERE a_non_indexed_column <> 12345;

(In the preceding query, we are “fooling” the SQL optimizer into scanning the clustered index, rather than a secondary index.) Most disks can read 10 to 50MB/s, which can be used to estimate how fast a table scan should run.

It can speed up index scans if you periodically perform a “null operation:

ALTER TABLE  ENGINE=INNODB

That causes MySQL to rebuild the table. Another way to perform a defragmentation operation is to use mysqldump to dump the table to a text file, drop the table, and reload it from the dump file.

If the insertions to an index are always ascending and records are deleted only from the end, the filespace management algorithm guarantees that fragmentation in the index does not occur.

14.2.15. InnoDB Error Handling

Error handling in is not always the same as specified in the SQL standard. According to the standard, any error during an SQL statement should cause the rollback of that statement. sometimes rolls back only part of the statement, or the whole transaction. The following items describe how performs error handling:

  • If you run out of file space in the tablespace, a MySQL error occurs and rolls back the SQL statement.

  • A transaction deadlock causes to roll back the entire transaction. In the case of a lock wait timeout, also rolls back the entire transaction before MySQL 5.0.13; as of 5.0.13, rolls back only the most recent SQL statement.

    When a transaction rollback occurs due to a deadlock or lock wait timeout, it cancels the effect of the statements within the transaction. But if the start-transaction statement was or statement, rollback does not cancel that statement. Further SQL statements become part of the transaction until the occurrence of , , or some SQL statement that causes an implicit commit.

  • A duplicate-key error rolls back the SQL statement, if you have not specified the option in your statement.

  • A rolls back the SQL statement.

  • Other errors are mostly detected by the MySQL layer of code (above the storage engine level), and they roll back the corresponding SQL statement. Locks are not released in a rollback of a single SQL statement.

During implicit rollbacks, as well as during the execution of an explicit SQL command, displays in the column for the relevant connection.

14.2.15.1.  Error Codes

The following is a non-exhaustive list of common -specific errors that you may encounter, with information about why each occurs and how to resolve the problem.

  • Cannot create table. If the error message refers to 150, table creation failed because a foreign key constraint was not correctly formed. If the error message refers to -1, table creation probably failed because the table included a column name that matched the name of an internal InnoDB table.

  • Cannot find the table from the data files, although the file for the table exists. See Section 14.2.17.1, “Troubleshooting Data Dictionary Operations”.

  • has run out of free space in the tablespace. You should reconfigure the tablespace to add a new data file.

  • Lock wait timeout expired. Transaction was rolled back.

  • Transaction deadlock. You should rerun the transaction.

  • You are trying to add a row but there is no parent row, and a foreign key constraint fails. You should add the parent row first.

  • You are trying to delete a parent row that has children, and a foreign key constraint fails. You should delete the children first.

14.2.15.2. Operating System Error Codes

To print the meaning of an operating system error number, use the perror program that comes with the MySQL distribution.

The following table provides a list of some common Linux system error codes. For a more complete list, see Linux source code.

  • Operation not permitted

  • No such file or directory

  • No such process

  • Interrupted system call

  • I/O error

  • No such device or address

  • Arg list too long

  • Exec format error

  • Bad file number

  • No child processes

  • Try again

  • Out of memory

  • Permission denied

  • Bad address

  • Block device required

  • Device or resource busy

  • File exists

  • Cross-device link

  • No such device

  • Not a directory

  • Is a directory

  • Invalid argument

  • File table overflow

  • Too many open files

  • Inappropriate ioctl for device

  • Text file busy

  • File too large

  • No space left on device

  • Illegal seek

  • Read-only file system

  • Too many links

The following table provides a list of some common Windows system error codes. For a complete list see the Microsoft Web site.

  • Incorrect function.

  • The system cannot find the file specified.

  • The system cannot find the path specified.

  • The system cannot open the file.

  • Access is denied.

  • The handle is invalid.

  • The storage control blocks were destroyed.

  • Not enough storage is available to process this command.

  • The storage control block address is invalid.

  • The environment is incorrect.

  • An attempt was made to load a program with an incorrect format.

  • The access code is invalid.

  • The data is invalid.

  • Not enough storage is available to complete this operation.

  • The system cannot find the drive specified.

  • The directory cannot be removed.

  • The system cannot move the file to a different disk drive.

  • There are no more files.

  • The media is write protected.

  • The system cannot find the device specified.

  • The device is not ready.

  • The device does not recognize the command.

  • Data error (cyclic redundancy check).

  • The program issued a command but the command length is incorrect.

  • The drive cannot locate a specific area or track on the disk.

  • The specified disk or diskette cannot be accessed.

  • The drive cannot find the sector requested.

  • The printer is out of paper.

  • The system cannot write to the specified device.

  • The system cannot read from the specified device.

  • A device attached to the system is not functioning.

  • The process cannot access the file because it is being used by another process.

  • The process cannot access the file because another process has locked a portion of the file.

  • The wrong diskette is in the drive. Insert %2 (Volume Serial Number: %3) into drive %1.

  • Too many files opened for sharing.

  • Reached the end of the file.

  • The disk is full.

  • The parameter is incorrect. (If this error occurs on Windows and you have enabled in a server option file, add the line to the file as well.)

  • The disk is full.

  • The filename, directory name, or volume label syntax is incorrect.

  • Insufficient system resources exist to complete the requested service.

14.2.16. Restrictions on InnoDB Tables

  • Warning: Do not convert MySQL system tables in the database from to tables! This is an unsupported operation. If you do this, MySQL does not restart until you restore the old system tables from a backup or re-generate them with the mysql_install_db script.

  • A table cannot contain more than 1000 columns.

  • The internal maximum key length is 3500 bytes, but MySQL itself restricts this to 1024 bytes.

  • The maximum row length, except for , and columns, is slightly less than half of a database page. That is, the maximum row length is about 8000 bytes. and columns must be less than 4GB, and the total row length, including also and columns, must be less than 4GB. stores the first 768 bytes of a , , or column in the row, and the rest into separate pages.

  • Although supports row sizes larger than 65535 internally, you cannot define a row containing columns with a combined size larger than 65535:

    mysql> 
        -> 
        -> 
    ERROR 1118 (42000): Row size too large. The maximum row size for the
    used table type, not counting BLOBs, is 65535. You have to change some
    columns to TEXT or BLOBs
    
  • On some older operating systems, files must be less than 2GB. This is not a limitation of itself, but if you require a large tablespace, you will need to configure it using several smaller data files rather than one or a file large data files.

  • The combined size of the log files must be less than 4GB.

  • The minimum tablespace size is 10MB. The maximum tablespace size is four billion database pages (64TB). This is also the maximum size for a table.

  • tables do not support indexes.

  • tables do not support spatial data types before MySQL 5.0.16.

  • determines index cardinality (as displayed in the column of output) by doing ten random dives to each of the index trees and updating index cardinality estimates accordingly. Note that because these are only estimates, repeated runs of may produce different numbers. This makes fast on tables but not 100% accurate as it doesn't take all rows into account.

    MySQL uses index cardinality estimates only in join optimization. If some join is not optimized in the right way, you can try using . In the few cases that doesn't produce values good enough for your particular tables, you can use with your queries to force the use of a particular index, or set the system variable to ensure that MySQL prefers index lookups over table scans. See Section 5.2.2, “Server System Variables”, and Section A.6, “Optimizer-Related Issues”.

  • does not give accurate statistics on tables, except for the physical size reserved by the table. The row count is only a rough estimate used in SQL optimization.

  • does not keep an internal count of rows in a table. (In practice, this would be somewhat complicated due to multi-versioning.) To process a statement, must scan an index of the table, which takes some time if the index is not entirely in the buffer pool. To get a fast count, you have to use a counter table you create yourself and let your application update it according to the inserts and deletes it does. If your table does not change often, using the MySQL query cache is a good solution. also can be used if an approximate row count is sufficient. See Section 14.2.11, “ Performance Tuning Tips”.

  • On Windows, always stores database and table names internally in lowercase. To move databases in binary format from Unix to Windows or from Windows to Unix, you should always use explicitly lowercase names when creating databases and tables.

  • For an column, you must always define an index for the table, and that index must contain just the column. In tables, the column may be part of a multi-column index.

  • In MySQL 5.0 before MySQL 5.0.3, does not support the table option for setting the initial sequence value in a or statement. To set the value with , insert a dummy row with a value one less and delete that dummy row, or insert the first row with an explicit value specified.

  • While initializing a previously specified column on a table, sets an exclusive lock on the end of the index associated with the column. In accessing the auto-increment counter, uses a specific table lock mode where the lock lasts only to the end of the current SQL statement, not to the end of the entire transaction. Note that other clients cannot insert into the table while the table lock is held; see Section 14.2.10.2, “ and .

  • When you restart the MySQL server, may reuse an old value that was generated for an column but never stored (that is, a value that was generated during an old transaction that was rolled back).

  • When an column runs out of values, wraps a to and to . However, values have 64 bits, so do note that if you were to insert one million rows per second, it would still take nearly three hundred thousand years before reached its upper bound. With all other integer type columns, a duplicate-key error results. This is similar to how works, because it is mostly general MySQL behavior and not about any storage engine in particular.

  • does not regenerate the table but instead deletes all rows, one by one.

  • Under some conditions, for an table is mapped to and doesn't reset the counter. See Section 13.2.9, “ Syntax”.

  • In MySQL 5.0, the MySQL operation acquires two locks on each table if (the default). In addition to a table lock on the MySQL layer, it also acquires an table lock. Older versions of MySQL did not acquire table locks; the old behavior can be selected by setting . If no table lock is acquired, completes even if some records of the tables are being locked by other transactions.

  • All locks held by a transaction are released when the transaction is committed or aborted. Thus, it does not make much sense to invoke on tables in mode, because the acquired table locks would be released immediately.

  • Sometimes it would be useful to lock further tables in the course of a transaction. Unfortunately, in MySQL performs an implicit and . An variant of has been planned that can be executed in the middle of a transaction.

  • The statement for setting up replication slave servers does not work for tables. A workaround is to alter the table to on the master, do then the load, and after that alter the master table back to . Do not do this if the tables use -specific features such as foreign keys.

  • The default database page size in is 16KB. By recompiling the code, you can set it to values ranging from 8KB to 64KB. You must update the values of and in the source file.

  • Currently, triggers are not activated by cascaded foreign key actions.

  • You cannot create a table with a column name that matches the name of an internal InnoDB column (including , , and ). In versions of MySQL before 5.0.21 this would cause a crash, since 5.0.21 the server will report error 1005 and refers to -1 in the error message.

  • As of MySQL 5.0.19, does not ignore trailing spaces when comparing or column values. See Section 11.4.2, “The and Types” and Section D.1.8, “Changes in release 5.0.19 (04 March 2006)”.

14.2.17. InnoDB Troubleshooting

The following general guidelines apply to troubleshooting problems:

  • When an operation fails or you suspect a bug, you should look at the MySQL server error log, which is the file in the data directory that has a suffix of .

  • When troubleshooting, it is usually best to run the MySQL server from the command prompt, rather than through the mysqld_safe wrapper or as a Windows service. You can then see what mysqld prints to the console, and so have a better grasp of what is going on. On Windows, you must start the server with the option to direct the output to the console window.

  • Use the Monitors to obtain information about a problem (see Section 14.2.11.1, “ and the Monitors”). If the problem is performance-related, or your server appears to be hung, you should use to print information about the internal state of . If the problem is with locks, use . If the problem is in creation of tables or other data dictionary operations, use to print the contents of the internal data dictionary.

  • If you suspect that a table is corrupt, run on that table.

14.2.17.1. Troubleshooting Data Dictionary Operations

A specific issue with tables is that the MySQL server keeps data dictionary information in files it stores in the database directories, whereas also stores the information into its own data dictionary inside the tablespace files. If you move files around, or if the server crashes in the middle of a data dictionary operation, the locations of the files may end up out of synchrony with the locations recorded in the internal data dictionary.

A symptom of an out-of-sync data dictionary is that a statement fails. If this occurs, you should look in the server's error log. If the log says that the table already exists inside the internal data dictionary, you have an orphaned table inside the tablespace files that has no corresponding file. The error message looks like this:

InnoDB: Error: table test/parent already exists in InnoDB internal
InnoDB: data dictionary. Have you deleted the .frm file
InnoDB: and not used DROP TABLE? Have you used DROP DATABASE
InnoDB: for InnoDB tables in MySQL version <= 3.23.43?
InnoDB: See the Restrictions section of the InnoDB manual.
InnoDB: You can drop the orphaned table inside InnoDB by
InnoDB: creating an InnoDB table with the same name in another
InnoDB: database and moving the .frm file to the current database.
InnoDB: Then MySQL thinks the table exists, and DROP TABLE will
InnoDB: succeed.

You can drop the orphaned table by following the instructions given in the error message. If you are still unable to use successfully, the problem may be due to name completion in the mysql client. To work around this problem, start the mysql client with the option and try again. (With name completion on, mysql tries to construct a list of table names, which fails when a problem such as just described exists.)

Another symptom of an out-of-sync data dictionary is that MySQL prints an error that it cannot open a file:

ERROR 1016: Can't open file: 'child2.InnoDB'. (errno: 1)

In the error log you can find a message like this:

InnoDB: Cannot find table test/child2 from the internal data dictionary
InnoDB: of InnoDB though the .frm file for the table exists. Maybe you
InnoDB: have deleted and recreated InnoDB data files but have forgotten
InnoDB: to delete the corresponding .frm files of InnoDB tables?

This means that there is an orphaned file without a corresponding table inside . You can drop the orphaned file by deleting it manually.

If MySQL crashes in the middle of an operation, you may end up with an orphaned temporary table inside the tablespace. Using you can see listed a table whose name is . You can perform SQL statements on tables whose name contains the character ‘’ if you enclose the name within backticks. Thus, you can drop such an orphaned table like any other orphaned table using the method described earlier. Note that to copy or rename a file in the Unix shell, you need to put the file name in double quotes if the file name contains ‘’.