InnoDB provides MySQL with a transaction-safe
(ACID compliant) storage engine that has
commit, rollback, and crash recovery capabilities.
InnoDB does locking on the row level and also
provides an Oracle-style consistent non-locking read in
SELECT statements. These features increase
multi-user concurrency and performance. There is no need for lock
escalation in InnoDB because row-level locks
fit in very little space. InnoDB also supports
FOREIGN KEY constraints. You can freely mix
InnoDB tables with tables from other MySQL
storage engines, even within the same statement.
InnoDB 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 InnoDB
storage engine maintains its own buffer pool for caching data and
indexes in main memory. InnoDB stores its
tables and indexes in a tablespace, which may consist of several
files (or raw disk partitions). This is different from, for
example, MyISAM tables where each table is
stored using separate files. InnoDB tables can
be of any size even on operating systems where file size is
limited to 2GB.
InnoDB is included in binary distributions by
default. The Windows Essentials installer makes
InnoDB the MySQL default storage engine on
Windows.
InnoDB is used in production at numerous large
database sites requiring high performance. The famous Internet
news site Slashdot.org runs on InnoDB. Mytrix,
Inc. stores over 1TB of data in InnoDB, and
another site handles an average load of 800 inserts/updates per
second in InnoDB.
InnoDB 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
A forum dedicated to the InnoDB storage
engine is available at
http://forums.mysql.com/list.php?22.
Contact information for Innobase Oy, producer of the
InnoDB engine:
Web site: http://www.innodb.com/
Email: <sales@innodb.com>
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
The InnoDB storage engine is enabled by
default. If you don't want to use InnoDB
tables, you can add the skip-innodb option to
your MySQL option file.
Note: InnoDB
provides MySQL with a transaction-safe (ACID
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 —
fsync() — 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, InnoDB
uses a special fcntl() file flush method. Under
Linux, it is advisable to disable the
write-back cache.
On ATAPI hard disks, a command such hdparm -W0
/dev/hda 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
InnoDB storage engine are its tablespace data
files and its log files.
Note: If you specify no
InnoDB configuration options, MySQL creates an
auto-extending 10MB data file named ibdata1
and two 5MB log files named ib_logfile0 and
ib_logfile1 in the MySQL data directory. To
get good performance, you should explicitly provide
InnoDB 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, “InnoDB Startup Options and System Variables” for additional information
about InnoDB-related configuration parameters.
To set up the InnoDB tablespace files, use the
innodb_data_file_path option in the
[mysqld] section of the
my.cnf option file. On Windows, you can use
my.ini instead. The value of
innodb_data_file_path 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=datafile_spec1[;datafile_spec2]...
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
ibdata1 that is auto-extending. No location
for the file is given, so by default, InnoDB
creates it in the MySQL data directory.
Sizes are specified using M or
G suffix letters to indicate units of MB or GB.
A tablespace containing a fixed-size 50MB data file named
ibdata1 and a 50MB auto-extending file named
ibdata2 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:
file_name:file_size[:autoextend[:max:max_file_size]]
The autoextend attribute and those following
can be used only for the last data file in the
innodb_data_file_path line.
If you specify the autoextend option for the
last data file, InnoDB 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
innodb_autoextend_increment 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 InnoDB Data and Log Files”.
InnoDB 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 max
attribute. The following configuration allows
ibdata1 to grow up to a limit of 500MB:
[mysqld] innodb_data_file_path=ibdata1:10M:autoextend:max:500M
InnoDB creates tablespace files in the MySQL
data directory by default. To specify a location explicitly, use
the innodb_data_home_dir option. For example,
to use two files named ibdata1 and
ibdata2 but create them in the
/ibdata directory, configure
InnoDB like this:
[mysqld] innodb_data_home_dir = /ibdata innodb_data_file_path=ibdata1:50M;ibdata2:50M:autoextend
Note: InnoDB
does not create directories, so make sure that the
/ibdata directory exists before you start the
server. This is also true of any log file directories that you
configure. Use the Unix or DOS mkdir command to
create any necessary directories.
InnoDB forms the directory path for each data
file by textually concatenating the value of
innodb_data_home_dir to the data file name,
adding a pathname separator (slash or backslash) between values if
necessary. If the innodb_data_home_dir option
is not mentioned in my.cnf 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 innodb_data_home_dir as an empty
string, you can specify absolute paths for the data files listed
in the innodb_data_file_path 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 my.cnf
example. Suppose that you have a computer with 128MB
RAM and one hard disk. The following example shows possible
configuration parameters in my.cnf or
my.ini for InnoDB,
including the autoextend attribute. The example
suits most users, both on Unix and Windows, who do not want to
distribute InnoDB data files and log files onto
several disks. It creates an auto-extending data file
ibdata1 and two InnoDB log
files ib_logfile0 and
ib_logfile1 in the MySQL data directory.
Also, the small archived InnoDB log file
ib_arch_log_0000000000 that
InnoDB 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 InnoDB tablespace for the
first time, it is best that you start the MySQL server from the
command prompt. InnoDB 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 C:\Program
Files\MySQL\MySQL Server 5.0\bin, you can
start it like this:
C:\> "C:\Program Files\MySQL\MySQL Server 5.0\bin\mysqld" --console
If you do not send server output to the screen, check the server's
error log to see what InnoDB prints during the
startup process.
See Section 14.2.5, “Creating the InnoDB Tablespace”, for an example of what the
information displayed by InnoDB should look
like.
You can place InnoDB options in the
[mysqld] 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
my.ini 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 C:
drive is not the boot drive, your only option is to use the
my.ini file in your Windows directory
(typically C:\WINDOWS or
C:\WINNT). You can use the
SET command at the command prompt in a console
window to print the value of WINDIR:
C:\> SET WINDIR
windir=C:\WINDOWS
If you want to make sure that mysqld reads
options only from a specific file, you can use the
--defaults-file option as the first option on the
command line when starting the server:
mysqld --defaults-file=your_path_to_my_cnf
An advanced my.cnf
example. Suppose that you have a Linux computer with
2GB RAM and three 60GB hard disks at directory paths
/, /dr2 and
/dr3. The following example shows possible
configuration parameters in my.cnf for
InnoDB.
[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. InnoDB fills the tablespace beginning
with the first data file. You can also use raw disk partitions
(raw devices) as InnoDB 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.
glibc 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
sort_buffer_size + read_buffer_size additional
memory.
By compiling MySQL yourself, you can use up to 64GB of physical
memory in 32-bit Windows. See the description for
innodb_buffer_pool_awe_mem_mb in
Section 14.2.4, “InnoDB 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=value
You can store each InnoDB 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 InnoDB tables.
You can enable multiple tablespaces by adding this line to the
[mysqld] section of
my.cnf:
[mysqld] innodb_file_per_table
After restarting the server, InnoDB stores
each newly created table into its own file
in
the database directory where the table belongs. This is similar
to what the tbl_name.ibdMyISAM storage engine does, but
MyISAM divides the table into a data file
and
the index file
tbl_name.MYD.
For tbl_name.MYIInnoDB, the data and the indexes are
stored together in the .ibd file. The
file is still created as usual.
tbl_name.frm
If you remove the innodb_file_per_table line
from my.cnf and restart the server,
InnoDB creates tables inside the shared
tablespace files again.
innodb_file_per_table affects only table
creation, not access to existing tables. If you start the server
with this option, new tables are created using
.ibd 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: InnoDB
always needs the shared tablespace because it puts its internal
data dictionary and undo logs there. The
.ibd files are not sufficient for
InnoDB to operate.
Note: You cannot freely move
.ibd files between database directories as
you can with MyISAM table files. This is
because the table definition that is stored in the
InnoDB shared tablespace includes the
database name, and because InnoDB must
preserve the consistency of transaction IDs and log sequence
numbers.
To move an .ibd file and the associated
table from one database to another, use a RENAME
TABLE statement:
RENAME TABLEdb1.tbl_nameTOdb2.tbl_name;
If you have a “clean” backup of an
.ibd file, you can restore it to the MySQL
installation from which it originated as follows:
Issue this ALTER TABLE statement:
ALTER TABLE tbl_name DISCARD TABLESPACE;
Caution: This statement
deletes the current .ibd file.
Put the backup .ibd file back in the
proper database directory.
Issue this ALTER TABLE statement:
ALTER TABLE tbl_name IMPORT TABLESPACE;
In this context, a “clean”
.ibd file backup means:
There are no uncommitted modifications by transactions in
the .ibd file.
There are no unmerged insert buffer entries in the
.ibd file.
Purge has removed all delete-marked index records from the
.ibd file.
mysqld has flushed all modified pages of
the .ibd file from the buffer pool to
the file.
You can make a clean backup .ibd file using
the following method:
Stop all activity from the mysqld server and commit all transactions.
Wait until SHOW ENGINE INNODB STATUS
shows that there are no active transactions in the database,
and the main thread status of InnoDB is
Waiting for server activity. Then you can
make a copy of the .ibd file.
Another method for making a clean copy of an
.ibd file is to use the commercial
InnoDB Hot Backup tool:
Use InnoDB Hot Backup to back up the
InnoDB installation.
Start a second mysqld server on the
backup and let it clean up the .ibd
files in the backup.
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
newraw immediately after the data file size
in innodb_data_file_path. The partition must
be at least as large as the size that you specify. Note that 1MB
in InnoDB 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, InnoDB
notices the newraw keyword and initializes
the new partition. However, do not create or change any
InnoDB tables yet. Otherwise, when you next
restart the server, InnoDB reinitializes the
partition and your changes are lost. (As a safety measure
InnoDB prevents users from modifying data
when any partition with newraw is specified.)
After InnoDB has initialized the new
partition, stop the server, change newraw in
the data file specification to raw:
[mysqld] innodb_data_home_dir= innodb_data_file_path=/dev/hdd1:5Graw;/dev/hdd2:2Graw
Then restart the server and InnoDB 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.
This section describes the InnoDB-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 skip- prefix. For example,
to enable or disable InnoDB checksums, you can
use --innodb_checksums or
--skip-innodb_checksums on the command line, or
innodb_checksums or
skip-innodb_checksums in an option file. System
variables that take a numeric value can be specified as
--
on the command line or as
var_name=value
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”).
var_name=value
InnoDB command options:
Enables the InnoDB storage engine, if the
server was compiled with InnoDB support.
Use --skip-innodb to disable
InnoDB.
Causes InnoDB to create a file named
in the MySQL data directory. <datadir>/innodb_status.<pid>InnoDB
periodically writes the output of SHOW ENGINE INNODB
STATUS to this file.
InnoDB system variables:
innodb_additional_mem_pool_size
The size in bytes of a memory pool InnoDB
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
InnoDB 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.
innodb_autoextend_increment
The increment size (in MB) for extending the size of an auto-extending tablespace when it becomes full. The default value is 8.
innodb_buffer_pool_awe_mem_mb
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 InnoDB 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, innodb_buffer_pool_size is the
window in the 32-bit address space of
mysqld where InnoDB maps
that AWE memory. A good value for
innodb_buffer_pool_size 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
innobase/os/os0proj.c source file.
innodb_buffer_pool_size
The size in bytes of the memory buffer
InnoDB 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.
innodb_checksums
InnoDB 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
--skip-innodb_checksums. This variable was
added in MySQL 5.0.3.
innodb_commit_concurrency
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.
innodb_concurrency_tickets
The number of threads that can enter InnoDB
concurrently is determined by the
innodb_thread_concurrency variable. A
thread is placed in a queue when it tries to enter
InnoDB if the number of threads has already
reached the concurrency limit. When a thread is allowed to
enter InnoDB, it is given a number of
“free tickets” equal to the value of
innodb_concurrency_tickets, and the thread
can enter and leave InnoDB 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
InnoDB. This variable was added in MySQL
5.0.3.
innodb_data_file_path
The paths to individual data files and their sizes. The full
directory path to each data file is formed by concatenating
innodb_data_home_dir to each path specified
here. The file sizes are specified in MB or GB (1024MB) by
appending M or G to the
size value. The sum of the sizes of the files must be at least
10MB. If you do not specify
innodb_data_file_path, the default behavior
is to create a single 10MB auto-extending data file named
ibdata1. 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”.
innodb_data_home_dir
The common part of the directory path for all
InnoDB 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
innodb_data_file_path.
innodb_doublewrite
By default, InnoDB 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 --skip-innodb_doublewrite 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.
innodb_fast_shutdown
If you set this variable to 0, InnoDB 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,
InnoDB skips these operations at shutdown.
The default value is 1. If you set it to 2,
InnoDB 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.
innodb_file_io_threads
The number of file I/O threads in InnoDB.
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; InnoDB
always uses the default value.
innodb_file_per_table
If this variable is enabled, InnoDB creates
each new table using its own .ibd 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”.
innodb_flush_log_at_trx_commit
When innodb_flush_log_at_trx_commit 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, InnoDB'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
InnoDB 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.
innodb_flush_method
If set to fdatasync (the default),
InnoDB uses fsync() to
flush both the data and log files. If set to
O_DSYNC, InnoDB uses
O_SYNC to open and flush the log files, but
uses fsync() to flush the data files. If
O_DIRECT is specified (available on some
GNU/Linux versions), InnoDB uses
O_DIRECT to open the data files, and uses
fsync() to flush both the data and log
files. Note that InnoDB uses
fsync() instead of
fdatasync(), and it does not use
O_DSYNC 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
async_unbuffered and cannot be changed.
innodb_force_recovery
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 InnoDB Recovery”. As a safety measure,
InnoDB prevents any changes to its data
when this variable is greater than 0.
innodb_lock_wait_timeout
The timeout in seconds an InnoDB
transaction may wait for a lock before being rolled back.
InnoDB automatically detects transaction
deadlocks in its own lock table and rolls back the
transaction. InnoDB notices locks set using
the LOCK TABLES statement. The default is
50 seconds.
Note: For the greatest possible durability and consistency in
a replication setup using InnoDB with
transactions, you should use
innodb_flush_log_at_trx_commit=1,
sync_binlog=1, and, before MySQL 5.0.3,
innodb_safe_binlog in your master server
my.cnf file.
(innodb_safe_binlog is not needed from
5.0.3 on.)
innodb_locks_unsafe_for_binlog
This variable controls next-key locking in
InnoDB searches and index scans. By
default, this variable is 0 (disabled), which means that
next-key locking is enabled.
Normally, InnoDB uses an algorithm called
next-key locking.
InnoDB 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 InnoDB 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
InnoDB 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
child 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 id
column. The query scans that index starting from the first
record where id 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 SELECT 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, InnoDB does not guarantee
serializability. Therefore, if this variable is enabled
InnoDB guarantees at most isolation level
READ COMMITTED. (Conflict serializability
is still guaranteed.)
Starting from MySQL 5.0.2, this option is even more unsafe.
InnoDB in an UPDATE or a
DELETE 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 UPDATE to
overtake other similar operations (such as another
UPDATE) 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 UPDATE must wait
for a commit or rollback of the first
UPDATE. The first UPDATE
has an exclusive lock on row (2,3), and the second
UPDATE while scanning rows also tries to
acquire an exclusive lock for the same row, which it cannot
have. This is because UPDATE 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
innodb_locks_unsafe_for_binlog variable is
enabled.
Therefore, InnoDB executes
UPDATE 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)
InnoDB executes UPDATE
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
innodb_log_arch_dir
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
innodb_log_group_home_dir. However, it is
not required.
innodb_log_archive
Whether to log InnoDB 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
InnoDB log files. The default for this
variable is 0.
innodb_log_buffer_size
The size in bytes of the buffer that InnoDB
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.
innodb_log_file_size
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/N-th of the size of the buffer
pool, where N 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.
innodb_log_files_in_group
The number of log files in the log group.
InnoDB writes to the files in a circular
fashion. The default (and recommended) is 2.
innodb_log_group_home_dir
The directory path to the InnoDB log files.
It must have the same value as
innodb_log_arch_dir. If you do not specify
any InnoDB log variables, the default is to
create two 5MB files names ib_logfile0
and ib_logfile1 in the MySQL data
directory.
innodb_max_dirty_pages_pct
This is an integer in the range from 0 to 100. The default is
90. The main thread in InnoDB tries to
write pages from the buffer pool so that the percentage of
dirty (not yet written) pages will not exceed this value.
innodb_max_purge_lag
This variable controls how to delay INSERT,
UPDATE and DELETE
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 InnoDB transaction system maintains a
list of transactions that have delete-marked index records by
UPDATE or DELETE
operations. Let the length of this list be
purge_lag. When
purge_lag exceeds
innodb_max_purge_lag, each
INSERT, UPDATE and
DELETE operation is delayed by
((purge_lag/innodb_max_purge_lag)×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.
innodb_mirrored_log_groups
The number of identical copies of log groups to keep for the database. Currently, this should be set to 1.
innodb_open_files
This variable is relevant only if you use multiple tablespaces
in InnoDB. It specifies the maximum number
of .ibd files that
InnoDB can keep open at one time. The
minimum value is 10. The default is 300.
The file descriptors used for .ibd files
are for InnoDB only. They are independent
of those specified by the --open-files-limit
server option, and do not affect the operation of the table
cache.
innodb_safe_binlog
Adds consistency guarantees between the content of
InnoDB 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.
innodb_support_xa
When set to ON or 1 (the default), this
variable enables InnoDB support for
two-phase commit in XA transactions. Enabling
innodb_support_xa 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
OFF or 0 to reduce the number of disk
flushes and get better InnoDB performance.
This variable was added in MySQL 5.0.3.
innodb_sync_spin_loops
The number of times a thread waits for an
InnoDB mutex to be freed before the thread
is suspended. This variable was added in MySQL 5.0.3.
innodb_table_locks
InnoDB honors LOCK
TABLES; MySQL does not return from LOCK
TABLE .. WRITE until all other threads have released
all their locks to the table. The default value is 1, which
means that LOCK TABLES causes
InnoDB to lock a table internally. In
applications using AUTOCOMMIT=1,
InnoDB's internal table locks can cause
deadlocks. You can set innodb_table_locks=0
in the server option file to remove that problem.
innodb_thread_concurrency
InnoDB tries to keep the number of
operating system threads concurrently inside
InnoDB less than or equal to the limit
given by this variable. If you have performance issues, and
SHOW ENGINE INNODB STATUS 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.
innodb_thread_sleep_delay
How long InnoDB threads sleep before
joining the InnoDB queue, in microseconds.
The default value is 10,000. A value of 0 disables sleep. This
variable was added in MySQL 5.0.3.
sync_binlog
If the value of this variable is positive, the MySQL server
synchronizes its binary log to disk
(fdatasync()) after every
sync_binlog 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).
Suppose that you have installed MySQL and have edited your option
file so that it contains the necessary InnoDB
configuration parameters. Before starting MySQL, you should verify
that the directories you have specified for
InnoDB data files and log files exist and that
the MySQL server has access rights to those directories.
InnoDB 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
InnoDB 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
--console option.
When you start the MySQL server after initially configuring
InnoDB in your option file,
InnoDB 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 InnoDB 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 ib_arch_log_0000000000. That file
resulted from the database creation, after which
InnoDB 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 innodb_file_per_table option to
my.cnf, InnoDB stores each
table in its own .ibd file in the same MySQL
database directory where the .frm file is
created. See Section 14.2.3.1, “Using Per-Table Tablespaces”.
If InnoDB prints an operating system error
during a file operation, usually the problem has one of the
following causes:
You did not create the InnoDB data file
directory or the InnoDB log directory.
mysqld does not have access rights to create files in those directories.
mysqld cannot read the proper
my.cnf or my.ini
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
innodb_data_home_dir or
innodb_data_file_path value.
If something goes wrong when InnoDB attempts
to initialize its tablespace or its log files, you should delete
all files created by InnoDB. This means all
ibdata files and all
ib_logfile files. In case you have already
created some InnoDB tables, delete the
corresponding .frm files for these tables
(and any .ibd files if you are using
multiple tablespaces) from the MySQL database directories as
well. Then you can try the InnoDB database
creation again. It is best to start the MySQL server from a
command prompt so that you see what is happening.
To create an InnoDB table, specify an
ENGINE = InnoDB option in the CREATE
TABLE statement:
CREATE TABLE customers (a INT, b CHAR (20), INDEX (a)) ENGINE=InnoDB;
The older term TYPE is supported as a synonym
for ENGINE for backward compatibility, but
ENGINE is the preferred term and
TYPE is deprecated.
The statement creates a table and an index on column
a in the InnoDB tablespace
that consists of the data files that you specified in
my.cnf. In addition, MySQL creates a file
customers.frm in the
test directory under the MySQL database
directory. Internally, InnoDB adds an entry for
the table to its own data dictionary. The entry includes the
database name. For example, if test is the
database in which the customers table is
created, the entry is for 'test/customers'.
This means you can create a table of the same name
customers in some other database, and the table
names do not collide inside InnoDB.
You can query the amount of free space in the
InnoDB tablespace by issuing a SHOW
TABLE STATUS statement for any InnoDB
table. The amount of free space in the tablespace appears in the
Comment section in the output of SHOW
TABLE STATUS. For example:
SHOW TABLE STATUS FROM test LIKE 'customers'
Note that the statistics SHOW displays for
InnoDB tables are only approximate. They are
used in SQL optimization. Table and index reserved sizes in bytes
are accurate, though.
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 SET AUTOCOMMIT = 0 and use
COMMIT and ROLLBACK to
commit or roll back your transaction. If you want to leave
autocommit on, you can enclose your transactions within
START TRANSACTION and either
COMMIT or ROLLBACK. The
following example shows two transactions. The first is
committed; the second is rolled back.
shell>mysql testmysql>CREATE TABLE CUSTOMER (A INT, B CHAR (20), INDEX (A))->ENGINE=InnoDB;Query OK, 0 rows affected (0.00 sec) mysql>START TRANSACTION;Query OK, 0 rows affected (0.00 sec) mysql>INSERT INTO CUSTOMER VALUES (10, 'Heikki');Query OK, 1 row affected (0.00 sec) mysql>COMMIT;Query OK, 0 rows affected (0.00 sec) mysql>SET AUTOCOMMIT=0;Query OK, 0 rows affected (0.00 sec) mysql>INSERT INTO CUSTOMER VALUES (15, 'John');Query OK, 1 row affected (0.00 sec) mysql>ROLLBACK;Query OK, 0 rows affected (0.00 sec) mysql>SELECT * FROM CUSTOMER;+------+--------+ | 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 COMMIT to the MySQL server
as strings just like any other SQL statements such as
SELECT or INSERT. Some
APIs also offer separate special transaction commit and rollback
functions or methods.
Important: Do not convert MySQL system tables in the
mysql database (such as
user or host) to the
InnoDB type. This is an unsupported
operation. The system tables must always be of the
MyISAM type.
If you want all your (non-system) tables to be created as
InnoDB tables, you can simply add the line
default-storage-engine=innodb to the
[mysqld] section of your server option file.
InnoDB does not have a special optimization
for separate index creation the way the
MyISAM 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
InnoDB is to do the inserts directly to an
InnoDB table. That is, use ALTER
TABLE ... ENGINE=INNODB, or create an empty
InnoDB table with identical definitions and
insert the rows with INSERT INTO ... SELECT * FROM
....
If you have UNIQUE 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;
... import operation ...
SET UNIQUE_CHECKS=1;
For big tables, this saves a lot of disk I/O because
InnoDB can then use its insert buffer to
write secondary index records as a batch. Be certain that the
data contains no duplicate keys.
UNIQUE_CHECKS 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 InnoDB 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 InnoDB
log files.
Make sure that you do not fill up the tablespace:
InnoDB tables require a lot more disk space
than MyISAM tables. If an ALTER
TABLE operation runs out of space, it starts a
rollback, and that can take hours if it is disk-bound. For
inserts, InnoDB 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 InnoDB Recovery”.
If you specify an AUTO_INCREMENT column for
an InnoDB table, the table handle in the
InnoDB 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.
InnoDB uses the following algorithm to
initialize the auto-increment counter for a table
T that contains an
AUTO_INCREMENT column named
ai_col: After a server startup, for the first
insert into a table T,
InnoDB executes the equivalent of this
statement:
SELECT MAX(ai_col) FROM T FOR UPDATE;
InnoDB 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,
InnoDB uses the value 1.
If a user invokes a SHOW TABLE STATUS
statement that displays output for the table
T and the auto-increment counter has not been
initialized, InnoDB 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.
InnoDB 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
AUTO_INCREMENT column,
InnoDB 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
AUTO_INCREMENT column if you roll back
transactions that have generated numbers using the counter.
If a user specifies NULL or
0 for the AUTO_INCREMENT
column in an INSERT,
InnoDB 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,
InnoDB uses a special table-level
AUTO-INC 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
AUTO_INCREMENT column. Nevertheless, two
transactions cannot have the AUTO-INC lock on
the same table simultaneously, which can have a performance
impact if the AUTO-INC lock is held for a
long time. That might be the case for a statement such as
INSERT INTO t1 ... SELECT ... FROM t2 that
inserts all rows from one table into another.
InnoDB uses the in-memory auto-increment
counter as long as he server runs. When the server is stopped
and restarted, InnoDB reinitializes the
counter for each table for the first INSERT
to the table, as described earlier.
Beginning with MySQL 5.0.3, InnoDB supports
the AUTO_INCREMENT =
table option in
NCREATE TABLE and ALTER
TABLE 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.
InnoDB also supports foreign key constraints.
The syntax for a foreign key constraint definition in
InnoDB looks like this:
[CONSTRAINTsymbol] FOREIGN KEY [id] (index_col_name, ...) REFERENCEStbl_name(index_col_name, ...) [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 InnoDB tables and
they must not be TEMPORARY 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 BLOB and
TEXT columns cannot be included in a
foreign key, because indexes on those columns must always
include a prefix length.
If the CONSTRAINT
clause is given,
the symbolsymbol value must be unique
in the database. If the clause is not given,
InnoDB creates the name automatically.
InnoDB rejects any INSERT
or UPDATE 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
InnoDB takes for any
UPDATE or DELETE 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 ON UPDATE and ON
DELETE subclauses of the FOREIGN
KEY 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, InnoDB supports five
options regarding the action to be taken:
CASCADE: Delete or update the row from
the parent table and automatically delete or update the
matching rows in the child table. Both ON DELETE
CASCADE and ON UPDATE CASCADE
are supported. Between two tables, you should not define
several ON UPDATE CASCADE clauses that
act on the same column in the parent table or in the child
table.
SET NULL: Delete or update the row from
the parent table and set the foreign key column or columns
in the child table to NULL. This is valid
only if the foreign key columns do not have the NOT
NULL qualifier specified. Both ON DELETE
SET NULL and ON UPDATE SET NULL
clauses are supported.
NO ACTION: In standard SQL, NO
ACTION 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.
InnoDB rejects the delete or update
operation for the parent table.
RESTRICT: Rejects the delete or update
operation for the parent table. NO ACTION
and RESTRICT are the same as omitting the
ON DELETE or ON UPDATE
clause. (Some database systems have deferred checks, and
NO ACTION is a deferred check. In MySQL,
foreign key constraints are checked immediately, so
NO ACTION and RESTRICT
are the same.)
SET DEFAULT: This action is recognized by
the parser, but InnoDB rejects table
definitions containing ON DELETE SET
DEFAULT or ON UPDATE SET
DEFAULT clauses.
Note that InnoDB supports foreign key
references within a table. In these cases, “child table
records” really refers to dependent records within the
same table.
InnoDB 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
InnoDB 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 SET NULL
action, make sure that you have not declared the
columns in the child table as NOT
NULL.
If MySQL reports an error number 1005 from a CREATE
TABLE statement, and the error message refers to errno
150, table creation failed because a foreign key constraint was
not correctly formed. Similarly, if an ALTER
TABLE fails and it refers to errno 150, that means a
foreign key definition would be incorrectly formed for the
altered table. You can use SHOW ENGINE INNODB
STATUS to display a detailed explanation of the most
recent InnoDB foreign key error in the
server.
Note: InnoDB
does not check foreign key constraints on those foreign key or
referenced key values that contain a NULL
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, InnoDB 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
RESTRICT type constraint, and there is a
child row with several parent rows, InnoDB
does not allow the deletion of any of those parent rows.
InnoDB 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
FOREIGN KEY constraint that references a
non-UNIQUE key is not standard SQL. It is an
InnoDB extension to standard SQL.
Deviation from SQL standards:
If ON UPDATE CASCADE or ON UPDATE
SET NULL recurses to update the same
table it has previously updated during the cascade,
it acts like RESTRICT. This means that you
cannot use self-referential ON UPDATE CASCADE
or ON UPDATE SET NULL operations. This is to
prevent infinite loops resulting from cascaded updates. A
self-referential ON DELETE SET NULL, on the
other hand, is possible, as is a self-referential ON
DELETE CASCADE. 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, InnoDB checks
UNIQUE and FOREIGN KEY
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
InnoDB 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 parent
and child 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
product_order table has foreign keys for two
other tables. One foreign key references a two-column index in
the product table. The other references a
single-column index in the customer 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;
InnoDB allows you to add a new foreign key
constraint to a table by using ALTER TABLE:
ALTER TABLEtbl_nameADD [CONSTRAINTsymbol] FOREIGN KEY [id] (index_col_name, ...) REFERENCEStbl_name(index_col_name, ...) [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 ALTER TABLE.
InnoDB also supports the use of
ALTER TABLE to drop foreign keys:
ALTER TABLEtbl_nameDROP FOREIGN KEYfk_symbol;
If the FOREIGN KEY clause included a
CONSTRAINT name when you created the foreign
key, you can refer to that name to drop the foreign key.
Otherwise, the fk_symbol value is
internally generated by InnoDB when the
foreign key is created. To find out the symbol value when you
want to drop a foreign key, use the SHOW CREATE
TABLE statement. For example:
mysql>SHOW CREATE TABLE ibtest11c\G*************************** 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>ALTER TABLE ibtest11c DROP FOREIGN KEY `0_38775`;
You cannot add a foreign key and drop a foreign key in separate
clauses of a single ALTER TABLE statement.
Separate statements are required.
The InnoDB parser allows table and column
identifiers in a FOREIGN KEY ... REFERENCES
... clause to be quoted within backticks.
(Alternatively, double quotes can be used if the
ANSI_QUOTES SQL mode is enabled.) The
InnoDB parser also takes into account the
setting of the lower_case_table_names system
variable.
InnoDB returns a table's foreign key
definitions as part of the output of the SHOW CREATE
TABLE statement:
SHOW CREATE TABLE tbl_name;
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 FROMdb_nameLIKE 'tbl_name';
The foreign key constraints are listed in the
Comment column of the output.
When performing foreign key checks, InnoDB
sets shared row-level locks on child or parent records it has to
look at. InnoDB 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
FOREIGN_KEY_CHECKS 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>SET FOREIGN_KEY_CHECKS = 0;mysql>SOURCEmysql>dump_file_name;SET FOREIGN_KEY_CHECKS = 1;
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
FOREIGN_KEY_CHECKS to 0 can also be useful
for ignoring foreign key constraints during LOAD
DATA and ALTER TABLE operations.
However, even if FOREIGN_KEY_CHECKS=0, InnoDB
does not allow the creation of a foreign key constraint where a
column references a non-matching column type.
InnoDB does not allow you to drop a table
that is referenced by a FOREIGN KEY
constraint, unless you do SET
FOREIGN_KEY_CHECKS=0. 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.
MySQL replication works for InnoDB tables as
it does for MyISAM 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
InnoDB table on the master to a
MyISAM table on the slave.
To set up a new slave for a master, you have to make a copy of
the InnoDB tablespace and the log files, as
well as the .frm files of the
InnoDB tables, and move the copies to the
slave. If the innodb_file_per_table variable
is enabled, you must also copy the .ibd
files as well. For the proper procedure to do this, see
Section 14.2.8, “Backing Up and Recovering an InnoDB Database”.
If you can shut down the master or an existing slave, you can
take a cold backup of the InnoDB 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)
InnoDB
Hot Backup tool.
You cannot set up replication for InnoDB
using the LOAD TABLE FROM MASTER statement,
which works only for MyISAM tables. There are
two possible workarounds:
Dump the table on the master and import the dump file into the slave.
Use ALTER TABLE on the master before setting up
replication with tbl_name
ENGINE=MyISAMLOAD TABLE
,
and then use tbl_name FROM MASTERALTER TABLE to convert the
master table back to InnoDB 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, “START TRANSACTION, COMMIT, and ROLLBACK Syntax”.
This section describes what you can do when your
InnoDB 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
InnoDB tablespace is to configure it from the
beginning to be auto-extending. Specify the
autoextend attribute for the last data file in
the tablespace definition. Then InnoDB
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
innodb_autoextend_increment 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 innodb_data_file_path,
and start the server again.
If your last data file was defined with the keyword
autoextend, 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
innodb_data_file_path. Then you can add another
data file. Remember that only the last data file in the
innodb_data_file_path can be specified as
auto-extending.
As an example, assume that the tablespace has just one
auto-extending data file ibdata1:
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. InnoDB 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:
Use mysqldump to dump all your
InnoDB tables.
Stop the server.
Remove all the existing tablespace files.
Configure a new tablespace.
Restart the server.
Import the dump files.
If you want to change the number or the size of your
InnoDB log files, use the following
instructions. The procedure to use depends on the value of
innodb_fast_shutdown:
If innodb_fast_shutdown 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
my.cnf 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 innodb_fast_shutdown is set to 2: You
should shut down the server, set
innodb_fast_shutdown 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
InnoDB log file size. Set
innodb_fast_shutdown back to 2 and restart
the server.
The key to safe database management is making regular backups.
InnoDB Hot Backup is an online backup tool you
can use to backup your InnoDB 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
InnoDB to manage its tables. Use the following
procedure:
Shut down your MySQL server and make sure that it shuts down without errors.
Copy all your data files (ibdata files
and .ibd files) into a safe place.
Copy all your ib_logfile files to a safe
place.
Copy your my.cnf configuration file or
files to a safe place.
Copy all the .frm files for your
InnoDB tables to a safe place.
Replication works with InnoDB 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
--single-transaction option that you can use to
make a consistent snapshot without locking out other clients.
To be able to recover your InnoDB 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 yourhostname-bin.123 | mysql
To recover from a crash of your MySQL server, the only requirement
is to restart it. InnoDB automatically checks
the logs and performs a roll-forward of the database to the
present. InnoDB 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
CHECK TABLE SQL statement to check whether a
table is corrupt, although CHECK TABLE
naturally cannot detect every possible kind of corruption. You can
use innodb_tablespace_monitor 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.
If there is database page corruption, you may want to dump your
tables from the database with SELECT INTO
OUTFILE. Usually, most of the data obtained in this
way is intact. Even so, the corruption may cause SELECT
* FROM statements
or tbl_nameInnoDB background operations to crash or
assert, or even to cause InnoDB roll-forward
recovery to crash. However, you can force the
InnoDB 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 [mysqld] section of your option
file before restarting the server:
[mysqld] innodb_force_recovery = 4
The allowable non-zero values for
innodb_force_recovery 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.
1
(SRV_FORCE_IGNORE_CORRUPT)
Let the server run even if it detects a corrupt page. Try to
make SELECT * FROM
jump over
corrupt index records and pages, which helps in dumping
tables.
tbl_name
2
(SRV_FORCE_NO_BACKGROUND)
Prevent the main thread from running. If a crash would occur during the purge operation, this recovery value prevents it.
3
(SRV_FORCE_NO_TRX_UNDO)
Do not run transaction rollbacks after recovery.
4
(SRV_FORCE_NO_IBUF_MERGE)
Prevent also insert buffer merge operations. If they would cause a crash, do not do them. Do not calculate table statistics.
5
(SRV_FORCE_NO_UNDO_LOG_SCAN)
Do not look at undo logs when starting the database:
InnoDB treats even incomplete
transactions as committed.
6
(SRV_FORCE_NO_LOG_REDO)
Do not do the log roll-forward in connection with recovery.
You can SELECT from tables to dump them, or
DROP or CREATE 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 ALTER TABLE. You can kill the
mysqld process and set
innodb_force_recovery to 3
to bring the database up without the rollback, then
DROP the table that is causing the runaway
rollback.