Optimisation is a complicated task because it ultimately requires understanding of the whole system. While it may be possible to do some local optimisations with small knowledge of your system or application, the more optimal you want your system to become the more you will have to know about it.
This chapter will try to explain and give some examples of different ways to optimise MySQL. Remember, however, that there are always some (increasingly harder) additional ways to make the system even faster.
The most important part for getting a system fast is of course the basic design. You also need to know what kinds of things your system will be doing, and what your bottlenecks are.
The most common bottlenecks are:
When using the MyISAM storage engine, MySQL uses extremely fast table locking (multiple readers / single writers). The biggest problem with this table type is a if you have a mix of a steady stream of updates and slow selects on the same table. If this is a problem with some tables, you can use another table type for these. See section 7 MySQL Table Types.
MySQL can work with both transactional and non-transactional tables. To be able to work smoothly with non-transactional tables (which can't rollback if something goes wrong), MySQL has the following rules:
NOT NULLcolumn or a too big numerical value in a numerical column, MySQL will instead of giving an error instead set the column to the 'best possible value'. For numerical values this is 0, the smallest possible values or the largest possible value. For strings this is either the empty string or the longest possible string that can be in the column.
For more information about this, see See section 1.7.5 How MySQL deals with constraints.
The above means that one should not use MySQL to check fields content, but one should do this in the application.
Because all SQL servers implement different parts of SQL, it takes work to write portable SQL applications. For very simple selects/inserts it is very easy, but the more you need the harder it gets. If you want an application that is fast with many databases it becomes even harder!
To make a complex application portable you need to choose a number of SQL servers that it should work with.
You can use the MySQL
http://www.mysql.com/information/crash-me.php to find functions,
types, and limits you can use with a selection of database
servers. Crash-me now tests far from everything possible, but it
is still comprehensive with about 450 things tested.
For example, you shouldn't have column names longer than 18 characters if you want to be able to use Informix or DB2.
Both the MySQL benchmarks and
crash-me programs are very
database-independent. By taking a look at how we have handled this, you
can get a feeling for what you have to do to write your application
database-independent. The benchmarks themselves can be found in the
`sql-bench' directory in the MySQL source
distribution. They are written in Perl with DBI database interface
(which solves the access part of the problem).
See http://www.mysql.com/information/benchmarks.html for the results from this benchmark.
As you can see in these results, all databases have some weak points. That is, they have different design compromises that lead to different behaviour.
If you strive for database independence, you need to get a good feeling for each SQL server's bottlenecks. MySQL is very fast in retrieving and updating things, but will have a problem in mixing slow readers/writers on the same table. Oracle, on the other hand, has a big problem when you try to access rows that you have recently updated (until they are flushed to disk). Transaction databases in general are not very good at generating summary tables from log tables, as in this case row locking is almost useless.
To get your application really database-independent, you need to define an easy extendable interface through which you manipulate your data. As C++ is available on most systems, it makes sense to use a C++ classes interface to the databases.
If you use some specific feature for some database (like the
REPLACE command in MySQL), you should code a method for
the other SQL servers to implement the same feature (but slower). With
MySQL you can use the
/*! */ syntax to add
MySQL-specific keywords to a query. The code inside
/**/ will be treated as a comment (ignored) by most other SQL
If high performance is more important than exactness, as in some web applications, it is possibile to create an application layer that caches all results to give you even higher performance. By letting old results 'expire' after a while, you can keep the cache reasonably fresh. This provides a method to handle high load spikes, in which case you can dynamically increase the cache and set the expire timeout higher until things get back to normal.
In this case the table creation information should contain information of the initial size of the cache and how often the table should normally be refreshed.
During MySQL initial development, the features of MySQL were made to fit our largest customer. They handle data warehousing for a couple of the biggest retailers in Sweden.
From all stores, we get weekly summaries of all bonus card transactions, and we are expected to provide useful information for the store owners to help them find how their advertisement campaigns are affecting their customers.
The data is quite huge (about 7 million summary transactions per month), and we have data for 4-10 years that we need to present to the users. We got weekly requests from the customers that they want to get 'instant' access to new reports from this data.
We solved this by storing all information per month in compressed 'transaction' tables. We have a set of simple macros (script) that generates summary tables grouped by different criteria (product group, customer id, store ...) from the transactional tables. The reports are web pages that are dynamically generated by a small Perl script that parses a web page, executes the SQL statements in it, and inserts the results. We would have used PHP or mod_perl instead but they were not available at that time.
For graphical data we wrote a simple tool in
C that can produce
GIFs based on the result of an SQL query (with some processing of the
result). This is also dynamically executed from the Perl script that
In most cases a new report can simply be done by copying an existing script and modifying the SQL query in it. In some cases, we will need to add more fields to an existing summary table or generate a new one, but this is also quite simple, as we keep all transactions tables on disk. (Currently we have at least 50G of transactions tables and 200G of other customer data.)
We also let our customers access the summary tables directly with ODBC so that the advanced users can themselves experiment with the data.
We haven't had any problems handling this with quite modest Sun Ultra SPARCstation (2x200 Mhz). We recently upgraded one of our servers to a 2 CPU 400 Mhz UltraSPARC, and we are now planning to start handling transactions on the product level, which would mean a ten-fold increase of data. We think we can keep up with this by just adding more disk to our systems.
We are also experimenting with Intel-Linux to be able to get more CPU power cheaper. Now that we have the binary portable database format (new in Version 3.23), we will start to use this for some parts of the application.
Our initial feelings are that Linux will perform much better on low-to-medium load and Solaris will perform better when you start to get a high load because of extreme disk IO, but we don't yet have anything conclusive about this. After some discussion with a Linux Kernel developer, this might be a side effect of Linux giving so much resources to the batch job that the interactive performance gets very low. This makes the machine feel very slow and unresponsive while big batches are going. Hopefully this will be better handled in future Linux Kernels.
This should contain a technical description of the MySQL
benchmark suite (and
crash-me), but that description is not
written yet. Currently, you can get a good idea of the benchmark by
looking at the code and results in the `sql-bench' directory in any
MySQL source distributions.
This benchmark suite is meant to be a benchmark that will tell any user what things a given SQL implementation performs well or poorly at.
Note that this benchmark is single threaded, so it measures the minimum time for the operations. We plan to in the future add a lot of multi-threaded tests to the benchmark suite.
For example, (run on the same NT 4.0 machine):
|Reading 2000000 rows by index||Seconds||Seconds|
|Inserting (350768) rows||Seconds||Seconds|
In the above test MySQL was run with a 8M index cache.
We have gathered some more benchmark results at http://www.mysql.com/information/benchmarks.html.
Note that Oracle is not included because they asked to be removed. All Oracle benchmarks have to be passed by Oracle! We believe that makes Oracle benchmarks very biased because the above benchmarks are supposed to show what a standard installation can do for a single client.
To run the benchmark suite, you have to download a MySQL source distribution, install the Perl DBI driver, the Perl DBD driver for the database you want to test and then do:
cd sql-bench perl run-all-tests --server=#
where # is one of supported servers. You can get a list of all options
and supported servers by doing
crash-me tries to determine what features a database supports and
what its capabilities and limitations are by actually running
queries. For example, it determines:
VARCHARcolumn can be
We can find the result from
crash-me on a lot of different databases at
You should definitely benchmark your application and database to find out where the bottlenecks are. By fixing it (or by replacing the bottleneck with a 'dummy module') you can then easily identify the next bottleneck (and so on). Even if the overall performance for your application is sufficient, you should at least make a plan for each bottleneck, and decide how to solve it if someday you really need the extra performance.
For an example of portable benchmark programs, look at the MySQL benchmark suite. See section 5.1.4 The MySQL Benchmark Suite. You can take any program from this suite and modify it for your needs. By doing this, you can try different solutions to your problem and test which is really the fastest solution for you.
It is very common that some problems only occur when the system is very heavily loaded. We have had many customers who contact us when they have a (tested) system in production and have encountered load problems. In every one of these cases so far, it has been problems with basic design (table scans are not good at high load) or OS/Library issues. Most of this would be a lot easier to fix if the systems were not already in production.
To avoid problems like this, you should put some effort into benchmarking your whole application under the worst possible load! You can use Super Smack for this, and it is available at: http://www.mysql.com/Downloads/super-smack/super-smack-1.0.tar.gz. As the name suggests, it can bring your system down to its knees if you ask it, so make sure to use it only on your development systems.
SELECTs and Other Queries
First, one thing that affects all queries: The more complex permission system setup you have, the more overhead you get.
If you do not have any
GRANT statements done, MySQL will
optimise the permission checking somewhat. So if you have a very high
volume it may be worth the time to avoid grants. Otherwise, more
permission check results in a larger overhead.
If your problem is with some explicit MySQL function, you can always time this in the MySQL client:
mysql> SELECT BENCHMARK(1000000,1+1); +------------------------+ | BENCHMARK(1000000,1+1) | +------------------------+ | 0 | +------------------------+ 1 row in set (0.32 sec)
The above shows that MySQL can execute 1,000,000
expressions in 0.32 seconds on a
All MySQL functions should be very optimised, but there may be
some exceptions, and the
BENCHMARK(loop_count,expression) is a
great tool to find out if this is a problem with your query.
EXPLAINSyntax (Get Information About a
EXPLAIN tbl_name or EXPLAIN SELECT select_options
EXPLAIN tbl_name is a synonym for
DESCRIBE tbl_name or
SHOW COLUMNS FROM tbl_name.
When you precede a
SELECT statement with the keyword
MySQL explains how it would process the
information about how tables are joined and in which order.
With the help of
EXPLAIN, you can see when you must add indexes
to tables to get a faster
SELECT that uses indexes to find the
You should frequently run
ANALYZE TABLE to update table statistics
such as cardinality of keys which can affect the choices the optimiser
makes. See section 4.5.2
ANALYZE TABLE Syntax.
You can also see if the optimiser joins the tables in an optimal
order. To force the optimiser to use a specific join order for a
SELECT statement, add a
For non-simple joins,
EXPLAIN returns a row of information for each
table used in the
SELECT statement. The tables are listed in the order
they would be read. MySQL resolves all joins using a single-sweep
multi-join method. This means that MySQL reads a row from the first
table, then finds a matching row in the second table, then in the third table
and so on. When all tables are processed, it outputs the selected columns and
backtracks through the table list until a table is found for which there are
more matching rows. The next row is read from this table and the process
continues with the next table.
In MySQL version 4.1 the
EXPLAIN output was changed to work better
with constructs like
UNIONs, subqueries and derived tables. Most
notable is the addition of two new columns:
EXPLAIN consists of the following columns:
SELECTidentifier, the sequential number of this
SELECTwithin the query.
SELECTclause, which can be any of the following:
UNIONs or subqueries).
SELECTSs, dependent on outer subquery.
SELECT, dependent on outer subquery.
consttables are very fast as they are read only once!
constis used when you compare all parts of a
UNIQUEkey with constants:
SELECT * FROM const_table WHERE primary_key=1; SELECT * FROM const_table WHERE primary_key_part1=1 and primary_key_part2=2;
consttypes. It is used when all parts of an index are used by the join and the index is
eq_refcan be used for indexed columns that is compared with
=. The compared item may be a constant or an expression that uses columns from tables that are read before this table. In the following examples,
ref_tablewill be able to use
SELECT * FROM ref_table,other_table WHERE ref_table.key_column=other_table.column; SELECT * FROM ref_table,other_table WHERE ref_table.key_column_part1=other_table.column AND ref_table.key_column_part2=1;
refis used if the join uses only a leftmost prefix of the key, or if the key is not
PRIMARY KEY(in other words, if the join cannot select a single row based on the key value). If the key that is used matches only a few rows, this join type is good.
refcan be used for indexed columns that is compared with
=. In the following examples,
ref_tablewill be able to use
SELECT * FROM ref_table WHERE key_column=expr; SELECT * FROM ref_table,other_table WHERE ref_table.key_column=other_table.column; SELECT * FROM ref_table,other_table WHERE ref_table.key_column_part1=other_table.column AND ref_table.key_column_part2=1;
ref, but with the addition that we will do an extra search for rows with
NULL. See section 5.2.5 How MySQL Optimises
SELECT * FROM ref_table WHERE key_column=expr OR key_column IS NULL;This optimisation is new for MySQL 4.1.1 and is mostly used when resolving sub queries.
keycolumn indicates which index is used. The
key_lencontains the longest key part that was used. The
refcolumn will be
NULLfor this type.
rangecan be used for when an key column is compared to a constant with
SELECT * FROM range_table WHERE key_column = 10; SELECT * FROM range_table WHERE key_column BETWEEN 10 and 20; SELECT * FROM range_table WHERE key_column IN (10,20,30); SELECT * FROM range_table WHERE key_part1= 10 and key_part2 IN (10,20,30);
ALL, except that only the index tree is scanned. This is usually faster than
ALL, as the index file is usually smaller than the datafile. This can be used when the query only uses columns that are part of one index.
const, and usually very bad in all other cases. You normally can avoid
ALLby adding more indexes, so that the row can be retrieved based on constant values or column values from earlier tables.
possible_keyscolumn indicates which indexes MySQL could use to find the rows in this table. Note that this column is totally independent of the order of the tables. That means that some of the keys in
possible_keysmay not be usable in practice with the generated table order. If this column is empty, there are no relevant indexes. In this case, you may be able to improve the performance of your query by examining the
WHEREclause to see if it refers to some column or columns that would be suitable for indexing. If so, create an appropriate index and check the query with
EXPLAINagain. See section 6.5.4
ALTER TABLESyntax. To see what indexes a table has, use
SHOW INDEX FROM tbl_name.
keycolumn indicates the key (index) that MySQL actually decided to use. The key is
NULLif no index was chosen. To force MySQL to use an key listed in the
USE KEY/IGNORE KEYin your query. See section 6.4.1
SELECTSyntax. Also, running
myisamchk --analyze(see section 126.96.36.199
myisamchkInvocation Syntax) or
ANALYZE TABLE(see section 4.5.2
ANALYZE TABLESyntax) on the table will help the optimiser choose better indexes.
key_lencolumn indicates the length of the key that MySQL decided to use. The length is
NULL. Note that this tells us how many parts of a multi-part key MySQL will actually use.
refcolumn shows which columns or constants are used with the
keyto select rows from the table.
rowscolumn indicates the number of rows MySQL believes it must examine to execute the query.
LEFT JOINoptimisation on the query and will not examine more rows in this table for the previous row combination after it finds one row that matches the
LEFT JOINcriteria. Here is an example for this:
SELECT * FROM t1 LEFT JOIN t2 ON t1.id=t2.id WHERE t2.id IS NULL;Assume that
t2.idis defined with
NOT NULL. In this case MySQL will scan
t1and look up the rows in
t1.id. If MySQL finds a matching row in
t2, it knows that
t2.idcan never be
NULL, and will not scan through the rest of the rows in
t2that has the same
id. In other words, for each row in
t1, MySQL only needs to do a single lookup in
t2, independent of how many matching rows there are in
range checked for each record (index map: #)
join typeand storing the sort key + pointer to the row for all rows that match the
WHERE. Then the keys are sorted. Finally the rows are retrieved in sorted order.
ORDER BYon a different column set than you did a
WHEREclause will be used to restrict which rows will be matched against the next table or sent to the client. If you don't have this information and the table is of type
index, you may have something wrong in your query (if you don't intend to fetch/examine all rows from the table).
You can get a good indication of how good a join is by multiplying all values
rows column of the
EXPLAIN output. This should tell you
roughly how many rows MySQL must examine to execute the query. This
number is also used when you restrict queries with the
See section 5.5.2 Tuning Server Parameters.
The following example shows how a
JOIN can be optimised progressively
using the information provided by
Suppose you have the
SELECT statement shown here, that you examine
EXPLAIN SELECT tt.TicketNumber, tt.TimeIn, tt.ProjectReference, tt.EstimatedShipDate, tt.ActualShipDate, tt.ClientID, tt.ServiceCodes, tt.RepetitiveID, tt.CurrentProcess, tt.CurrentDPPerson, tt.RecordVolume, tt.DPPrinted, et.COUNTRY, et_1.COUNTRY, do.CUSTNAME FROM tt, et, et AS et_1, do WHERE tt.SubmitTime IS NULL AND tt.ActualPC = et.EMPLOYID AND tt.AssignedPC = et_1.EMPLOYID AND tt.ClientID = do.CUSTNMBR;
For this example, assume that:
| || |
| || |
| || |
| || |
| || |
tt.ActualPCvalues aren't evenly distributed.
Initially, before any optimisations have been performed, the
statement produces the following information:
table type possible_keys key key_len ref rows Extra et ALL PRIMARY NULL NULL NULL 74 do ALL PRIMARY NULL NULL NULL 2135 et_1 ALL PRIMARY NULL NULL NULL 74 tt ALL AssignedPC,ClientID,ActualPC NULL NULL NULL 3872 range checked for each record (key map: 35)
ALL for each table, this output indicates that
MySQL is generating a Cartesian product of all the tables! This will take
quite a long time, as the product of the number of rows in each table must be
examined! For the case at hand, this is
74 * 2135 * 74 * 3872 =
45,268,558,720 rows. If the tables were bigger, you can only imagine how
long it would take.
One problem here is that MySQL can't (yet) use indexes on columns
efficiently if they are declared differently. In this context,
CHAR are the same unless they are declared as
different lengths. Because
tt.ActualPC is declared as
et.EMPLOYID is declared as
CHAR(15), there is a length
To fix this disparity between column lengths, use
ALTER TABLE to
ActualPC from 10 characters to 15 characters:
mysql> ALTER TABLE tt MODIFY ActualPC VARCHAR(15);
et.EMPLOYID are both
EXPLAIN statement again produces this result:
table type possible_keys key key_len ref rows Extra tt ALL AssignedPC,ClientID,ActualPC NULL NULL NULL 3872 Using where do ALL PRIMARY NULL NULL NULL 2135 range checked for each record (key map: 1) et_1 ALL PRIMARY NULL NULL NULL 74 range checked for each record (key map: 1) et eq_ref PRIMARY PRIMARY 15 tt.ActualPC 1
This is not perfect, but is much better (the product of the
values is now less by a factor of 74). This version is executed in a couple
A second alteration can be made to eliminate the column length mismatches
tt.AssignedPC = et_1.EMPLOYID and
mysql> ALTER TABLE tt MODIFY AssignedPC VARCHAR(15), -> MODIFY ClientID VARCHAR(15);
EXPLAIN produces the output shown here:
table type possible_keys key key_len ref rows Extra et ALL PRIMARY NULL NULL NULL 74 tt ref AssignedPC, ActualPC 15 et.EMPLOYID 52 Using where ClientID, ActualPC et_1 eq_ref PRIMARY PRIMARY 15 tt.AssignedPC 1 do eq_ref PRIMARY PRIMARY 15 tt.ClientID 1
This is almost as good as it can get.
The remaining problem is that, by default, MySQL assumes that values
tt.ActualPC column are evenly distributed, and that isn't the
case for the
tt table. Fortunately, it is easy to tell MySQL
shell> myisamchk --analyze PATH_TO_MYSQL_DATABASE/tt shell> mysqladmin refresh
Now the join is perfect, and
EXPLAIN produces this result:
table type possible_keys key key_len ref rows Extra tt ALL AssignedPC NULL NULL NULL 3872 Using where ClientID, ActualPC et eq_ref PRIMARY PRIMARY 15 tt.ActualPC 1 et_1 eq_ref PRIMARY PRIMARY 15 tt.AssignedPC 1 do eq_ref PRIMARY PRIMARY 15 tt.ClientID 1
Note that the
rows column in the output from
EXPLAIN is an
educated guess from the MySQL join optimiser. To optimise a
query, you should check if the numbers are even close to the truth. If not,
you may get better performance by using
STRAIGHT_JOIN in your
SELECT statement and trying to list the tables in a different order in
In most cases you can estimate the performance by counting disk seeks.
For small tables, you can usually find the row in 1 disk seek (as the
index is probably cached). For bigger tables, you can estimate that
(using B++ tree indexes) you will need:
log(index_block_length / 3 * 2 / (index_length + data_pointer_length)) +
1 seeks to find a row.
In MySQL an index block is usually 1024 bytes and the data
pointer is usually 4 bytes. A 500,000 row table with an
index length of 3 (medium integer) gives you:
log(500,000)/log(1024/3*2/(3+4)) + 1 = 4 seeks.
As the above index would require about 500,000 * 7 * 3/2 = 5.2M, (assuming that the index buffers are filled to 2/3, which is typical) you will probably have much of the index in memory and you will probably only need 1-2 calls to read data from the OS to find the row.
For writes, however, you will need 4 seek requests (as above) to find where to place the new index and normally 2 seeks to update the index and write the row.
Note that the above doesn't mean that your application will slowly degenerate by log N! As long as everything is cached by the OS or SQL server things will only go marginally slower while the table gets bigger. After the data gets too big to be cached, things will start to go much slower until your applications is only bound by disk-seeks (which increase by log N). To avoid this, increase the index cache as the data grows. See section 5.5.2 Tuning Server Parameters.
In general, when you want to make a slow
SELECT ... WHERE faster, the
first thing to check is whether you can add an index. See section 5.4.3 How MySQL Uses Indexes. All references between different tables
should usually be done with indexes. You can use the
to determine which indexes are used for a
See section 5.2.1
EXPLAIN Syntax (Get Information About a
Some general tips:
myisamchk --analyzeon a table after it has been loaded with relevant data. This updates a value for each index part that indicates the average number of rows that have the same value. (For unique indexes, this is always 1, of course.) MySQL will use this to decide which index to choose when you connect two tables with 'a non-constant expression'. You can check the result from the
analyzerun by doing
SHOW INDEX FROM table_nameand examining the
myisamchk --sort-index --sort-records=1(if you want to sort on index 1). If you have a unique index from which you want to read all records in order according to that index, this is a good way to make that faster. Note, however, that this sorting isn't written optimally and will take a long time for a large table!
WHERE optimisations are put in the
SELECT part here because
they are mostly used with
SELECT, but the same optimisations apply for
Also note that this section is incomplete. MySQL does many optimisations, and we have not had time to document them all.
Some of the optimisations performed by MySQL are listed here:
((a AND b) AND c OR (((a AND b) AND (c AND d)))) -> (a AND b AND c) OR (a AND b AND c AND d)
(a<b AND b=c) AND a=5 -> b>5 AND b=c AND a=5
(B>=5 AND B=5) OR (B=6 AND 5=5) OR (B=7 AND 5=6) -> B=5 OR B=6
COUNT(*)on a single table without a
WHEREis retrieved directly from the table information for
HEAPtables. This is also done for any
NOT NULLexpression when used with only one table.
SELECTstatements are impossible and returns no rows.
HAVINGis merged with
WHEREif you don't use
GROUP BYor group functions (
WHEREis constructed to get a fast
WHEREevaluation for each sub-join and also to skip records as soon as possible.
WHEREclause on a
UNIQUEindex, or a
PRIMARY KEY, where all index parts are used with constant expressions and the index parts are defined as
mysql> SELECT * FROM t WHERE primary_key=1; mysql> SELECT * FROM t1,t2 -> WHERE t1.primary_key=1 AND t2.primary_key=t1.id;
ORDER BYand in
GROUP BYcome from the same table, then this table is preferred first when joining.
ORDER BYclause and a different
GROUP BYclause, or if the
GROUP BYcontains columns from tables other than the first table in the join queue, a temporary table is created.
SQL_SMALL_RESULT, MySQL will use an in-memory temporary table.
HAVINGclause are skipped.
Some examples of queries that are very fast:
mysql> SELECT COUNT(*) FROM tbl_name; mysql> SELECT MIN(key_part1),MAX(key_part1) FROM tbl_name; mysql> SELECT MAX(key_part2) FROM tbl_name -> WHERE key_part_1=constant; mysql> SELECT ... FROM tbl_name -> ORDER BY key_part1,key_part2,... LIMIT 10; mysql> SELECT ... FROM tbl_name -> ORDER BY key_part1 DESC,key_part2 DESC,... LIMIT 10;
The following queries are resolved using only the index tree (assuming the indexed columns are numeric):
mysql> SELECT key_part1,key_part2 FROM tbl_name WHERE key_part1=val; mysql> SELECT COUNT(*) FROM tbl_name -> WHERE key_part1=val1 AND key_part2=val2; mysql> SELECT key_part2 FROM tbl_name GROUP BY key_part1;
The following queries use indexing to retrieve the rows in sorted order without a separate sorting pass:
mysql> SELECT ... FROM tbl_name -> ORDER BY key_part1,key_part2,... ; mysql> SELECT ... FROM tbl_name -> ORDER BY key_part1 DESC,key_part2 DESC,... ;
MySQL can do the same optimisation on
column IS NULL as it can do
column = constant_value. For example, MySQL can use
indexes and ranges to search for
SELECT * FROM table_name WHERE key_col IS NULL; SELECT * FROM table_name WHERE key_col <=> NULL; SELECT * FROM table_name WHERE key_col=# OR key_col=# OR key_col IS NULL
If you use
column_name IS NULL on a
NOT NULL in a WHERE clause
on table that is not used
OUTER JOIN that expression will be optimised
MySQL 4.1.1 can additionally optimise the combination
expr AND column IS NULL, an form that is common in resolved sub
EXPLAIN will show
ref_or_null when this
optimisation is used.
This optimisation can handle one
IS NULL for any key part.
Some examples of queries that are optimised (assuming key on t2 (a,b)):
SELECT * FROM t1 WHERE t1.a=expr OR t1.a IS NULL; SELECT * FROM t1,t2 WHERE t1.a=t2.a OR t2.a IS NULL; SELECT * FROM t1,t2 WHERE (t1.a=t2.a OR t2.a IS NULL) AND t2.b=t1.b; SELECT * FROM t1,t2 WHERE t1.a=t2.a AND (t2.b=t1.b OR t2.b IS NULL); SELECT * FROM t1,t2 WHERE (t1.a=t2.a AND t2.a IS NULL AND ...) OR (t1.a=t2.a AND t2.a IS NULL AND ...);
ref_or_null works by first doing a read on the reference key
and after that a separate search after rows with NULL key.
Note that the optimisation can only handle one
IS NULL level.
SELECT * FROM t1,t2 where (t1.a=t2.a AND t2.a IS NULL) OR (t1.b=t2.b AND t2.b IS NULL);
Int the above case MySQL will only use key lookups on the part
(t1.a=t2.a AND t2.a IS NULL) and not be able to use the key part on
DISTINCT is converted to a
GROUP BY on all columns,
DISTINCT combined with
ORDER BY will in many cases also
need a temporary table.
Note that as
DISTINCT may use
GROUP BY, you should be aware of
how MySQL works with in fields in
ORDER BY or
are not part of the selected fields. See section 188.8.131.52
GROUP BY with Hidden Fields.
LIMIT row_count with
DISTINCT, MySQL will stop
as soon as it finds
row_count unique rows.
If you don't use columns from all used tables, MySQL will stop the scanning of the not used tables as soon as it has found the first match.
SELECT DISTINCT t1.a FROM t1,t2 where t1.a=t2.a;
In the case, assuming
t1 is used before
t2 (check with
EXPLAIN), then MySQL will stop reading from
t2 (for that
particular row in
t1) when the first row in
t2 is found.
A LEFT JOIN B join_condition in MySQL is implemented as follows:
Bis set to be dependent on table
Aand all tables that
Ais dependent on.
Ais set to be dependent on all tables (except
B) that are used in the
LEFT JOINcondition is used to decide how we should retrieve rows from table B. (In other words, any condition in the
WHEREclause is not used).
WHEREoptimisations are done.
Athat matches the
WHEREclause, but there wasn't any row in
Bthat matched the
ONcondition, then an extra
Brow is generated with all columns set to
LEFT JOINto find rows that don't exist in some table and you have the following test:
column_name IS NULLin the
WHEREpart, where column_name is a column that is declared as
NOT NULL, then MySQL will stop searching after more rows (for a particular key combination) after it has found one row that matches the
RIGHT JOIN is implemented analogously as
The table read order forced by
LEFT JOIN and
will help the join optimiser (which calculates in which order tables
should be joined) to do its work much more quickly, as there are fewer
table permutations to check.
Note that the above means that if you do a query of type:
SELECT * FROM a,b LEFT JOIN c ON (c.key=a.key) LEFT JOIN d (d.key=a.key) WHERE b.key=d.key
MySQL will do a full scan on
b as the
LEFT JOIN will force
it to be read before
The fix in this case is to change the query to:
SELECT * FROM b,a LEFT JOIN c ON (c.key=a.key) LEFT JOIN d (d.key=a.key) WHERE b.key=d.key
Starting from 4.0.14 MySQL does the following left join optimisation:
WHERE condition is always be false for the generated
NULL row, the
LEFT JOIN is changed to a normal join.
For example, in the following query the
WHERE clause would be
false if t2.column would be
NULL so it's safe to convert to
a normal join.
SELECT * FROM t1 LEFT t2 ON (column) WHERE t2.column2 =5; -> SELECT * FROM t1,t2 WHERE t2.column2=5 AND t1.column=t2.column;
this can be made faster as MySQL can now use table
t1 if this would result in a better query plan. To force a
specific table order one should use
In some cases MySQL can uses index to satisfy an
ORDER BY or
GROUP BY request without doing any extra sorting.
The index can also be used even if the
ORDER BY doesn't match the
index exactly, as long as all the unused index parts and all the extra
ORDER BY columns are constants in the
clause. The following queries will use the index to resolve the
ORDER BY /
GROUP BY part:
SELECT * FROM t1 ORDER BY key_part1,key_part2,... SELECT * FROM t1 WHERE key_part1=constant ORDER BY key_part2 SELECT * FROM t1 WHERE key_part1=constant GROUP BY key_part2 SELECT * FROM t1 ORDER BY key_part1 DESC,key_part2 DESC SELECT * FROM t1 WHERE key_part1=1 ORDER BY key_part1 DESC,key_part2 DESC
Some cases where MySQL can not use indexes to resolve the
BY: (Note that MySQL will still use indexes to find the rows that
ORDER BYon different keys:
SELECT * FROM t1 ORDER BY key1,key2
ORDER BYusing non-consecutive key parts.
SELECT * FROM t1 WHERE key2=constant ORDER BY key_part2
SELECT * FROM t1 ORDER BY key_part1 DESC,key_part2 ASC
SELECT * FROM t1 WHERE key2=constant ORDER BY key1
ORDER BYon are not all from the first not-
consttable that is used to retrieve rows (This is the first table in the
EXPLAINoutput which doesn't use a
constrow fetch method).
In the cases where MySQL have to sort the result, it uses the following algorithm:
WHEREclause are skipped.
MERGEBUFF(7) regions to one block in another temporary file. Repeat until all blocks from the first file are in the second file.
MERGEBUFF2(15) blocks left.
You can with
EXPLAIN SELECT ... ORDER BY check if MySQL can use
indexes to resolve the query. If you get
Using filesort in the
extra column, then MySQL can't use indexes to resolve the
ORDER BY. See section 5.2.1
EXPLAIN Syntax (Get Information About a
If you want to have a higher
ORDER BY speed, you should first
see if you can get MySQL to use indexes instead of having to do an extra
sorting phase. If this is not possible, then you can do:
tmpdirto point to a dedicated disk with lots of empty space. If you use MySQL 4.1 or later you can spread load between several physical disks by setting
tmpdirto a list of paths separated by colon
;on Windows). They will be used in round-robin fashion. Note: These paths should end up on different physical disks, not different partitions of the same disk.
MySQL by default sorts all
GROUP BY x,y[,...] queries as if you
would have specified
ORDER BY x,y[,...]. MySQL will optimise
ORDER BY as above without any speed penalty. If you by
in some cases don't want to have the result sorted you can specify
ORDER BY NULL:
INSERT INTO foo SELECT a,COUNT(*) FROM bar GROUP BY a ORDER BY NULL;
In some cases MySQL will handle the query differently when you are
LIMIT row_count and not using
LIMIT, MySQL will use indexes in some cases when it normally would prefer to do a full table scan.
ORDER BY, MySQL will end the sorting as soon as it has found the first
row_countlines instead of sorting the whole table.
DISTINCT, MySQL will stop as soon as it finds
GROUP BYcan be resolved by reading the key in order (or do a sort on the key) and then calculate summaries until the key value changes. In this case
LIMIT row_countwill not calculate any unnecessary
#rows to the client, it will abort the query (if you are not using
LIMIT 0will always quickly return an empty set. This is useful to check the query and to get the column types of the result columns.
LIMIT row_countis used to calculate how much space is required.
The time to insert a record consists approximately of:
where the numbers are somewhat proportional to the overall time. This does not take into consideration the initial overhead to open tables (which is done once for each concurrently running query).
The size of the table slows down the insertion of indexes by log N (B-trees).
Some ways to speed up inserts:
INSERTstatements. This is much faster (many times in some cases) than using separate
INSERTstatements. If you are adding data to non-empty table, you may tune up the
bulk_insert_buffer_sizevariable to make it even faster. See section 184.108.40.206
INSERT DELAYEDstatement. See section 6.4.3
MyISAMtables you can insert rows at the same time
SELECTs are running if there are no deleted rows in the tables.
LOAD DATA INFILE. This is usually 20 times faster than using a lot of
INSERTstatements. See section 6.4.9
LOAD DATA INFILESyntax.
LOAD DATA INFILErun even faster when the table has many indexes. Use the following procedure:
CREATE TABLE. For example, using
FLUSH TABLESstatement or the shell command
myisamchk --keys-used=0 -rq /path/to/db/tbl_name. This will remove all usage of all indexes from the table.
LOAD DATA INFILE. This will not update any indexes and will therefore be very fast.
myisampackon it to make it smaller. See section 220.127.116.11 Compressed Table Characteristics.
myisamchk -r -q /path/to/db/tbl_name. This will create the index tree in memory before writing it to disk, which is much faster because it avoids lots of disk seeks. The resulting index tree is also perfectly balanced.
FLUSH TABLESstatement or the shell command
LOAD DATA INFILEalso does the above optimisation if you insert into an empty table; the main difference with the above procedure is that you can let
myisamchkallocate much more temporary memory for the index creation that you may want MySQL to allocate for every index recreation. Since MySQL 4.0 you can also use
ALTER TABLE tbl_name DISABLE KEYSinstead of
myisamchk --keys-used=0 -rq /path/to/db/tbl_nameand
ALTER TABLE tbl_name ENABLE KEYSinstead of
myisamchk -r -q /path/to/db/tbl_name. This way you can also skip
mysql> LOCK TABLES a WRITE; mysql> INSERT INTO a VALUES (1,23),(2,34),(4,33); mysql> INSERT INTO a VALUES (8,26),(6,29); mysql> UNLOCK TABLES;The main speed difference is that the index buffer is flushed to disk only once, after all
INSERTstatements have completed. Normally there would be as many index buffer flushes as there are different
INSERTstatements. Locking is not needed if you can insert all rows with a single statement. For transactional tables, you should use
LOCK TABLESto get a speedup. Locking will also lower the total time of multi-connection tests, but the maximum wait time for some threads will go up (because they wait for locks). For example:
thread 1 does 1000 inserts thread 2, 3, and 4 does 1 insert thread 5 does 1000 insertsIf you don't use locking, 2, 3, and 4 will finish before 1 and 5. If you use locking, 2, 3, and 4 probably will not finish before 1 or 5, but the total time should be about 40% faster. As
DELETEoperations are very fast in MySQL, you will obtain better overall performance by adding locks around everything that does more than about 5 inserts or updates in a row. If you do very many inserts in a row, you could do a
LOCK TABLESfollowed by an
UNLOCK TABLESonce in a while (about each 1000 rows) to allow other threads access to the table. This would still result in a nice performance gain. Of course,
LOAD DATA INFILEis much faster for loading data.
To get some more speed for both
LOAD DATA INFILE and
INSERT, enlarge the key buffer. See section 5.5.2 Tuning Server Parameters.
Update queries are optimised as a
SELECT query with the additional
overhead of a write. The speed of the write is dependent on the size of
the data that is being updated and the number of indexes that are
updated. Indexes that are not changed will not be updated.
Also, another way to get fast updates is to delay updates and then do many updates in a row later. Doing many updates in a row is much quicker than doing one at a time if you lock the table.
Note that, with dynamic record format, updating a record to
a longer total length may split the record. So if you do this often,
it is very important to
OPTIMIZE TABLE sometimes.
See section 4.5.1
OPTIMIZE TABLE Syntax.
If you want to delete all rows in the table, you should use
TRUNCATE TABLE table_name. See section 6.4.7
The time to delete a record is exactly proportional to the number of indexes. To delete records more quickly, you can increase the size of the index cache. See section 5.5.2 Tuning Server Parameters.
Unsorted tips for faster systems:
thread_cache_sizevariable. See section 5.5.2 Tuning Server Parameters.
EXPLAINcommand. See section 5.2.1
EXPLAINSyntax (Get Information About a
MyISAMtables that are updated a lot. This is to avoid problems with table locking.
MyISAMtables can insert rows in a table without deleted rows at the same time another table is reading from it. If this is important for you, you should consider methods where you don't have to delete rows or run
OPTIMIZE TABLEafter you have deleted a lot of rows.
ALTER TABLE ... ORDER BY expr1,expr2...if you mostly retrieve rows in
expr1,expr2...order. By using this option after big changes to the table, you may be able to get higher performance.
SELECT * FROM table_name WHERE hash=MD5(CONCAT(col1,col2)) AND col_1='constant' AND col_2='constant'
BLOBcolumns. You will get dynamic row length as soon as you are using a single
BLOBcolumn. See section 7 MySQL Table Types.
UPDATE table SET count=count+1 WHERE index_column=constantis very fast! This is really important when you use MySQL table types like MyISAM and ISAM that only have table locking (multiple readers / single writers). This will also give better performance with most databases, as the row locking manager in this case will have less to do.
INSERT /*! DELAYED */when you do not need to know when your data is written. This speeds things up because many records can be written with a single disk write.
INSERT /*! LOW_PRIORITY */when you want your selects to be more important.
SELECT /*! HIGH_PRIORITY */to get selects that jump the queue. That is, the select is done even if there is somebody waiting to do a write.
INSERTstatement to store many rows with one SQL command (many SQL servers supports this).
LOAD DATA INFILEto load bigger amounts of data. This is faster than normal inserts and will be even faster when
myisamchkis integrated in
AUTO_INCREMENTcolumns to make unique values.
OPTIMIZE TABLEonce in a while to avoid fragmentation when using a dynamic table format. See section 4.5.1
HEAPtables to get more speed when possible. See section 7 MySQL Table Types.
customer_namein the customer table). To make your names portable to other SQL servers you should keep them shorter than 18 characters.
MyISAMdirectly, you could get a speed increase of 2-5 times compared to using the SQL interface. To be able to do this the data must be on the same server as the application, and usually it should only be accessed by one process (because external file locking is really slow). One could eliminate the above problems by introducing low-level
MyISAMcommands in the MySQL server (this could be one easy way to get more performance if needed). By carefully designing the database interface, it should be quite easy to support this types of optimisation.
DELAY_KEY_WRITE=1will make the updating of indexes faster, as these are not logged to disk until the file is closed. The downside is that you should run
myisamchkon these tables before you start
mysqldto ensure that they are okay if something killed
mysqldin the middle. As the key information can always be generated from the data, you should not lose anything by using
You can find a discussion about different locking methods in the appendix. See section E.4 Locking methods.
All locking in MySQL is deadlock-free, except for
BDB type tables.
This is managed by always
requesting all needed locks at once at the beginning of a query and always
locking the tables in the same order.
InnoDB type tables automatically acquire their row locks and
BDB type tables
their page locks during the processing of SQL statements, not at the start
of the transaction.
The locking method MySQL uses for
WRITE locks works as follows:
The locking method MySQL uses for
READ locks works as follows:
When a lock is released, the lock is made available to the threads in the write lock queue, then to the threads in the read lock queue.
This means that if you have many updates on a table,
statements will wait until there are no more updates.
To work around this for the case where you want to do many
SELECT operations on a table, you can insert rows in a temporary
table and update the real table with the records from the temporary table
once in a while.
This can be done with the following code:
mysql> LOCK TABLES real_table WRITE, insert_table WRITE; mysql> INSERT INTO real_table SELECT * FROM insert_table; mysql> TRUNCATE TABLE insert_table; mysql> UNLOCK TABLES;
You can use the
LOW_PRIORITY options with
SELECT if you want to prioritise retrieval in some specific
cases. You can also start
to get the same behaveour.
SQL_BUFFER_RESULT can also help making table locks shorter.
See section 6.4.1
You could also change the locking code in `mysys/thr_lock.c' to use a single queue. In this case, write locks and read locks would have the same priority, which might help some applications.
The table locking code in MySQL is deadlock free.
MySQL uses table locking (instead of row locking or column
locking) on all table types, except
to achieve a very
high lock speed. For large tables, table locking is much better than
row locking for most applications, but there are, of course, some
BDB tables, MySQL only uses table
locking if you explicitly lock the table with
For these table types we recommend you to not use
LOCK TABLES at all, because
InnoDB uses automatic
row level locking and
BDB uses page level locking to
ensure transaction isolation.
In MySQL Version 3.23.7 and above, you can insert rows into
MyISAM tables at the same time other threads are reading from the
table. Note that currently this only works if there are no holes after
deleted rows in the table at the time the insert is made. When all holes
has been filled with new data, concurrent inserts will automatically be
Table locking enables many threads to read from a table at the same time, but if a thread wants to write to a table, it must first get exclusive access. During the update, all other threads that want to access this particular table will wait until the update is ready.
As updates on tables normally are considered to be more important than
SELECT, all statements that update a table have higher priority
than statements that retrieve information from a table. This should
ensure that updates are not 'starved' because one issues a lot of heavy
queries against a specific table. (You can change this by using
LOW_PRIORITY with the statement that does the update or
HIGH_PRIORITY with the
Starting from MySQL Version 3.23.7 one can use the
max_write_lock_count variable to force MySQL to
temporary give all
SELECT statements, that wait for a table, a
higher priority after a specific number of inserts on a table.
Table locking is, however, not very good under the following senario:
SELECTthat takes a long time to run.
UPDATEon a used table. This client will wait until the
SELECTstatement on the same table. As
UPDATEhas higher priority than
SELECTwill wait for the
UPDATEto finish. It will also wait for the first
full disk, in which case all threads that wants to access the problem table will also be put in a waiting state until more disk space is made available.
Some possible solutions to this problem are:
SELECTstatements to run faster. You may have to create some summary tables to do this.
--low-priority-updates. This will give all statements that update (modify) a table lower priority than a
SELECTstatement. In this case the last
SELECTstatement in the previous scenario would execute before the
DELETEstatement lower priority with the
mysqldwith a low value for
READlocks after a certain number of
SET LOW_PRIORITY_UPDATES=1. See section 5.5.6
SELECTis very important with the
HIGH_PRIORITYattribute. See section 6.4.1
SELECT, switch to use the new
MyISAMtables as these support concurrent
INSERTwill probably solve your problems. See section 6.4.3
DELETEmay help. See section 6.4.6
MySQL keeps row data and index data in separate files. Many (almost all) other databases mix row and index data in the same file. We believe that the MySQL choice is better for a very wide range of modern systems.
Another way to store the row data is to keep the information for each column in a separate area (examples are SDBM and Focus). This will cause a performance hit for every query that accesses more than one column. Because this degenerates so quickly when more than one column is accessed, we believe that this model is not good for general purpose databases.
The more common case is that the index and data are stored together (as in Oracle/Sybase et al). In this case you will find the row information at the leaf page of the index. The good thing with this layout is that it, in many cases, depending on how well the index is cached, saves a disk read. The bad things with this layout are:
One of the most basic optimisation is to get your data (and indexes) to take as little space on the disk (and in memory) as possible. This can give huge improvements because disk reads are faster and normally less main memory will be used. Indexing also takes less resources if done on smaller columns.
MySQL supports a lot of different table types and row formats. Choosing the right table format may give you a big performance gain. See section 7 MySQL Table Types.
You can get better performance on a table and minimise storage space using the techniques listed here:
MEDIUMINTis often better than
NOT NULLif possible. It makes everything faster and you save one bit per column. Note that if you really need
NULLin your application you should definitely use it. Just avoid having it on all columns by default.
BLOBcolumns), a fixed-size record format is used. This is faster but unfortunately may waste some space. See section 7.1.2
Indexes are used to find rows with a specific value of one column fast. Without an index MySQL has to start with the first record and then read through the whole table until it finds the relevant rows. The bigger the table, the more this costs. If the table has an index for the columns in question, MySQL can quickly get a position to seek to in the middle of the datafile without having to look at all the data. If a table has 1000 rows, this is at least 100 times faster than reading sequentially. Note that if you need to access almost all 1000 rows it is faster to read sequentially because we then avoid disk seeks.
All MySQL indexes (
INDEX) are stored in B-trees. Strings are automatically prefix-
and end-space compressed. See section 6.5.7
CREATE INDEX Syntax.
Indexes are used to:
MIN()value for a specific indexed column. This is optimised by a preprocessor that checks if you are using
WHEREkey_part_# = constant on all key parts < N. In this case MySQL will do a single key lookup and replace the
MIN()expression with a constant. If all expressions are replaced with constants, the query will return at once:
SELECT MIN(key_part2),MAX(key_part2) FROM table_name where key_part1=10
ORDER BY key_part_1,key_part_2). The key is read in reverse order if all key parts are followed by
DESC. See section 5.2.8 How MySQL Optimises
SELECT key_part3 FROM table_name WHERE key_part1=1
Suppose you issue the following
mysql> SELECT * FROM tbl_name WHERE col1=val1 AND col2=val2;
If a multiple-column index exists on
appropriate rows can be fetched directly. If separate single-column
indexes exist on
col2, the optimiser tries to
find the most restrictive index by deciding which index will find fewer
rows and using that index to fetch the rows.
If the table has a multiple-column index, any leftmost prefix of the
index can be used by the optimiser to find rows. For example, if you
have a three-column index on
(col1,col2,col3), you have indexed
search capabilities on
MySQL can't use a partial index if the columns don't form a
leftmost prefix of the index. Suppose you have the
statements shown here:
mysql> SELECT * FROM tbl_name WHERE col1=val1; mysql> SELECT * FROM tbl_name WHERE col2=val2; mysql> SELECT * FROM tbl_name WHERE col2=val2 AND col3=val3;
If an index exists on
(col1,col2,col3), only the first of the preceding
queries uses the index. The second and third queries do involve
indexed columns, but
(col2,col3) are not
leftmost prefixes of
MySQL also uses indexes for
LIKE comparisons if the argument
LIKE is a constant string that doesn't start with a wildcard
character. For example, the following
SELECT statements use indexes:
mysql> SELECT * FROM tbl_name WHERE key_col LIKE "Patrick%"; mysql> SELECT * FROM tbl_name WHERE key_col LIKE "Pat%_ck%";
In the first statement, only rows with
"Patrick" <= key_col <
"Patricl" are considered. In the second statement, only rows with
"Pat" <= key_col < "Pau" are considered.
SELECT statements will not use indexes:
mysql> SELECT * FROM tbl_name WHERE key_col LIKE "%Patrick%"; mysql> SELECT * FROM tbl_name WHERE key_col LIKE other_col;
In the first statement, the
LIKE value begins with a wildcard
character. In the second statement, the
LIKE value is not a
MySQL 4.0 does another optimisation on
LIKE. If you use
... LIKE "%string%" and
string is longer than 3 characters,
MySQL will use the
Turbo Boyer-Moore algorithm to initialise the
pattern for the string and then use this pattern to perform the search
column_name IS NULL will use indexes if column_name
is an index.
MySQL normally uses the index that finds the least number of rows. An
index is used for columns that you compare with the following operators:
BETWEEN, and a
LIKE with a non-wildcard prefix like
Any index that doesn't span all
AND levels in the
is not used to optimise the query. In other words: To be able to use an
index, a prefix of the index must be used in every
WHERE clauses use indexes:
... WHERE index_part1=1 AND index_part2=2 AND other_column=3 ... WHERE index=1 OR A=10 AND index=2 /* index = 1 OR index = 2 */ ... WHERE index_part1='hello' AND index_part_3=5 /* optimised like "index_part1='hello'" */ ... WHERE index1=1 and index2=2 or index1=3 and index3=3; /* Can use index on index1 but not on index2 or index 3 */
WHERE clauses do NOT use indexes:
... WHERE index_part2=1 AND index_part3=2 /* index_part_1 is not used */ ... WHERE index=1 OR A=10 /* Index is not used in both AND parts */ ... WHERE index_part1=1 OR index_part2=10 /* No index spans all rows */
Note that in some cases MySQL will not use an index, even if one would be available. Some of the cases where this happens are:
LIMITto only retrieve part of the rows, MySQL will use an index anyway, as it can much more quickly find the few rows to return in the result.
All MySQL column types can be indexed. Use of indexes on the
relevant columns is the best way to improve the performance of
The maximum number of keys and the maximum index length is defined per storage engine. See section 7 MySQL Table Types. You can with all storage engines have at least 16 keys and a total index length of at least 256 bytes.
VARCHAR columns, you can index a prefix of a
column. This is much faster and requires less disk space than indexing the
whole column. The syntax to use in the
CREATE TABLE statement to
index a column prefix looks like this:
KEY index_name (col_name(length))
The example here creates an index for the first 10 characters of the
mysql> CREATE TABLE test ( -> name CHAR(200) NOT NULL, -> KEY index_name (name(10)));
TEXT columns, you must index a prefix of the
column. You cannot index the entire column.
In MySQL Version 3.23.23 or later, you can also create special
FULLTEXT indexes. They are used for full-text search. Only the
MyISAM table type supports
FULLTEXT indexes. They can be
created only from
Indexing always happens over the entire column and partial indexing is not
supported. See section 6.8 MySQL Full-text Search for details.
MySQL can create indexes on multiple columns. An index may
consist of up to 15 columns. (On
VARCHAR columns you
can also use a prefix of the column as a part of an index.)
A multiple-column index can be considered a sorted array containing values that are created by concatenating the values of the indexed columns.
MySQL uses multiple-column indexes in such a way that queries are
fast when you specify a known quantity for the first column of the index in a
WHERE clause, even if you don't specify values for the other columns.
Suppose a table is created using the following specification:
mysql> CREATE TABLE test ( -> id INT NOT NULL, -> last_name CHAR(30) NOT NULL, -> first_name CHAR(30) NOT NULL, -> PRIMARY KEY (id), -> INDEX name (last_name,first_name));
Then the index
name is an index over
first_name. The index will be used for queries that specify
values in a known range for
last_name, or for both
name index will be used in the following queries:
mysql> SELECT * FROM test WHERE last_name="Widenius"; mysql> SELECT * FROM test WHERE last_name="Widenius" -> AND first_name="Michael"; mysql> SELECT * FROM test WHERE last_name="Widenius" -> AND (first_name="Michael" OR first_name="Monty"); mysql> SELECT * FROM test WHERE last_name="Widenius" -> AND first_name >="M" AND first_name < "N";
name index will NOT be used in the following queries:
mysql> SELECT * FROM test WHERE first_name="Michael"; mysql> SELECT * FROM test WHERE last_name="Widenius" -> OR first_name="Michael";
For more information on the manner in which MySQL uses indexes to improve query performance, see section 5.4.3 How MySQL Uses Indexes.
When you run
mysqladmin status, you'll see something like this:
Uptime: 426 Running threads: 1 Questions: 11082 Reloads: 1 Open tables: 12
This can be somewhat perplexing if you only have 6 tables.
MySQL is multi-threaded, so it may have many queries on the same table
simultaneously. To minimise the problem with two threads having
different states on the same file, the table is opened independently by
each concurrent thread. This takes some memory but will normaly increase
MyISAM tables this also requires
one extra file descriptor for the datafile. With these table types the index
file descriptor is shared between all threads.
You can read more about this topic in the next section. See section 5.4.7 How MySQL Opens and Closes Tables.
affect the maximum number of files the server keeps open. If you
increase one or both of these values, you may run up against a limit
imposed by your operating system on the per-process number of open file
descriptors. However, you can increase the limit on many systems.
Consult your OS documentation to find out how to do this, because the
method for changing the limit varies widely from system to system.
table_cache is related to
max_connections. For example,
for 200 concurrent running connections, you should have a table cache of
200 * n, where
n is the maximum number of tables
in a join. You also need to reserve some extra file descriptors for
temporary tables and files.
Make sure that your operating system can handle the number of open file
descriptors implied by the
table_cache setting. If
table_cache is set too high, MySQL may run out of file
descriptors and refuse connections, fail to perform queries, and be very
unreliable. You also have to take into account that the
engine needs two file descriptors for each unique open table. You can
in increase the number of file descriptors available for MySQL with
--open-files-limit=# startup option. See section A.2.17 File Not Found.
The cache of open tables will be kept at a level of
entries. The default value is 64; this can be changed with the
table_cache=# option to
mysqld). Note that MySQL may
temporarily open even more tables to be able to execute queries.
A not used table is closed and removed from the table cache under the following circumstances:
table_cacheentries and a thread is no longer using a table.
When the table cache fills up, the server uses the following procedure to locate a cache entry to use:
A table is opened for each concurrent access. This means that
if you have two threads accessing the same table or access the table
twice in the same query (with
AS) the table needs to be opened twice.
The first open of any table takes two file descriptors; each additional
use of the table takes only one file descriptor. The extra descriptor
for the first open is used for the index file; this descriptor is shared
among all threads.
If you are opening a table with the
HANDLER table_name OPEN
statement, a dedicated table object is allocated for the thread.
This table object is not shared by other threads an will not be closed
until the thread calls
HANDLER table_name CLOSE or the thread dies.
See section 6.4.2
HANDLER Syntax. When this happens, the table is put
back in the table cache (if it isn't full).
You can check if your table cache is too small by checking the
Opened_tables. If this is quite big, even if you
haven't done a lot of
FLUSH TABLES, you should increase your table
cache. See section 18.104.22.168
If you have many files in a directory, open, close, and create operations will
be slow. If you execute
SELECT statements on many different tables,
there will be a little overhead when the table cache is full, because for
every table that has to be opened, another must be closed. You can reduce
this overhead by making the table cache larger.
We start with the system level things since some of these decisions have to be made very early. In other cases a fast look at this part may suffice because it not that important for the big gains. However, it is always nice to have a feeling about how much one could gain by changing things at this level.
The default OS to use is really important! To get the most use of multiple-CPU machines one should use Solaris (because the threads works really nice) or Linux (because the 2.2 kernel has really good SMP support). Also on 32-bit machines Linux has a 2G file-size limit by default. Hopefully this will be fixed soon when new filesystems are released (XFS/Reiserfs). If you have a desperate need for files bigger than 2G on Linux-intel 32 bit, you should get the LFS patch for the ext2 filesystem.
Because we have not run MySQL in production on that many platforms, we advice you to test your intended platform before choosing it, if possible.
--skip-external-lockingMySQL option to avoid external locking. Note that this will not impact MySQL's functionality as long as you only run one server. Just remember to take down the server (or lock relevant parts) before you run
myisamchk. On some system this switch is mandatory because the external locking does not work in any case. The
--skip-external-lockingoption is on by default when compiling with MIT-pthreads, because
flock()isn't fully supported by MIT-pthreads on all platforms. It's also on default for Linux as Linux file locking are not yet safe. The only case when you can't use
--skip-external-lockingis if you run multiple MySQL servers (not clients) on the same data, or run
myisamchkon the table without first flushing and locking the
mysqldserver tables first. You can still use
UNLOCK TABLESeven if you are using
You can get the default buffer sizes used by the
with this command:
shell> mysqld --help
This command produces a list of all
mysqld options and configurable
variables. The output includes the default values and looks something
Possible variables for option --set-variable (-O) are: back_log current value: 5 bdb_cache_size current value: 1048540 binlog_cache_size current value: 32768 connect_timeout current value: 5 delayed_insert_timeout current value: 300 delayed_insert_limit current value: 100 delayed_queue_size current value: 1000 flush_time current value: 0 interactive_timeout current value: 28800 join_buffer_size current value: 131072 key_buffer_size current value: 1048540 lower_case_table_names current value: 0 long_query_time current value: 10 max_allowed_packet current value: 1048576 max_binlog_cache_size current value: 4294967295 max_connections current value: 100 max_connect_errors current value: 10 max_delayed_threads current value: 20 max_heap_table_size current value: 16777216 max_join_size current value: 4294967295 max_sort_length current value: 1024 max_tmp_tables current value: 32 max_write_lock_count current value: 4294967295 myisam_sort_buffer_size current value: 8388608 net_buffer_length current value: 16384 net_retry_count current value: 10 net_read_timeout current value: 30 net_write_timeout current value: 60 read_buffer_size current value: 131072 read_rnd_buffer_size current value: 262144 slow_launch_time current value: 2 sort_buffer current value: 2097116 table_cache current value: 64 thread_concurrency current value: 10 tmp_table_size current value: 1048576 thread_stack current value: 131072 wait_timeout current value: 28800
Please note that
--set-variable is deprecated since MySQL 4.0,
--var=option on its own.
If there is a
mysqld server currently running, you can see what
values it actually is using for the variables by executing this command:
shell> mysqladmin variables
You can find a full description for all variables in the
section in this manual. See section 22.214.171.124
You can also see some statistics from a running server by issuing the command
SHOW STATUS. See section 126.96.36.199
MySQL uses algorithms that are very scalable, so you can usually run with very little memory. If you, however, give MySQL more memory, you will normally also get better performance.
When tuning a MySQL server, the two most important variables to use
table_cache. You should first feel
confident that you have these right before trying to change any of the
If you have much memory (>=256M) and many tables and want maximum performance with a moderate number of clients, you should use something like this:
shell> mysqld_safe -O key_buffer=64M -O table_cache=256 \ -O sort_buffer=4M -O read_buffer_size=1M &
If you have only 128M and only a few tables, but you still do a lot of sorting, you can use something like:
shell> mysqld_safe -O key_buffer=16M -O sort_buffer=1M
If you have little memory and lots of connections, use something like this:
shell> mysqld_safe -O key_buffer=512k -O sort_buffer=100k \ -O read_buffer_size=100k &
shell> mysqld_safe -O key_buffer=512k -O sort_buffer=16k \ -O table_cache=32 -O read_buffer_size=8k -O net_buffer_length=1K &
If you are doing a
GROUP BY or
ORDER BY on files that are
much bigger than your available memory you should increase the value of
read_rnd_buffer_size to speed up the reading of rows after the sorting
When you have installed MySQL, the `support-files' directory will contain some different `my.cnf' example files, `my-huge.cnf', `my-large.cnf', `my-medium.cnf', and `my-small.cnf', you can use as a base to optimise your system.
If there are very many connections, ``swapping problems'' may occur unless
mysqld has been configured to use very little memory for each
mysqld performs better if you have enough memory for all
connections, of course.
Note that if you change an option to
mysqld, it remains in effect only
for that instance of the server.
To see the effects of a parameter change, do something like this:
shell> mysqld -O key_buffer=32m --help
Make sure that the
--help option is last; otherwise, the effect of any
options listed after it on the command-line will not be reflected in the
Most of the following tests are done on Linux with the MySQL benchmarks, but they should give some indication for other operating systems and workloads.
You get the fastest executable when you link with
On Linux, you will get the fastest code when compiling with
-O3. To compile `sql_yacc.cc' with these options, you
need about 200M memory because
gcc/pgcc needs a lot of memory to
make all functions inline. You should also set
configuring MySQL to avoid inclusion of the
library (it is not needed). Note that with some versions of
the resulting code will only run on true Pentium processors, even if you
use the compiler option that you want the resulting code to be working on
all x586 type processors (like AMD).
By just using a better compiler and/or better compiler options you can get a 10-30% speed increase in your application. This is particularly important if you compile the SQL server yourself!
We have tested both the Cygnus CodeFusion and Fujitsu compilers, but when we tested them, neither was sufficiently bug free to allow MySQL to be compiled with optimisations on.
When you compile MySQL you should only include support for the
character sets that you are going to use. (Option
The standard MySQL binary distributions are compiled with support
for all character sets.
Here is a list of some measurements that we have done:
pgccand compile everything with
mysqldserver is 1% faster than with
-static), the result is 13% slower on Linux. Note that you still can use a dynamic linked MySQL library. It is only the server that is critical for performance.
strip libexec/mysqld, the resulting binary can be up to 4% faster.
localhost, MySQL will, by default, use sockets.)
--with-debug=full, you will lose 20% for most queries. Some queries may take substantially longer (for example, the MySQL benchmarks ran 35% slower). If you use
--with-debug, then you will only lose 15%. For a
mysqldversion that has been compiled with
--with-debug=full, you can disable memory checking at runtime by starting it with the
--skip-safemallocoption. The end result in this case should be close to when configuring with
gcc2.95.2 for UltraSPARC with the option
-mcpu=v8 -Wa,-xarch=v8plusagives 4% more performance.
--log-binmakes mysqld 1% slower.
The MySQL-Linux distribution provided by MySQL AB used
to be compiled with
pgcc, but we had to go back to regular gcc
because of a bug in
pgcc that would generate the code that does
not run on AMD. We will continue using gcc until that bug is resolved.
In the meantime, if you have a non-AMD machine, you can get a faster
binary by compiling with
pgcc. The standard MySQL
Linux binary is linked statically to get it faster and more portable.
The following list indicates some of the ways that the
uses memory. Where applicable, the name of the server variable relevant
to the memory use is given:
key_buffer_size) is shared by all threads; other buffers used by the server are allocated as needed. See section 5.5.2 Tuning Server Parameters.
thread_stack), a connection buffer (variable
net_buffer_length), and a result buffer (variable
net_buffer_length). The connection buffer and result buffer are dynamically enlarged up to
max_allowed_packetwhen needed. When a query is running, a copy of the current query string is also allocated.
MyISAMtables are memory mapped. This is because the 32-bit memory space of 4 GB is not large enough for most big tables. When systems with a 64-bit address space become more common we may add general support for memory mapping.
HEAP) tables. Temporary tables with a big record length (calculated as the sum of all column lengths) or that contain
BLOBcolumns are stored on disk. One problem in MySQL versions before Version 3.23.2 is that if a
HEAPtable exceeds the size of
tmp_table_size, you get the error
The table tbl_name is full. In newer versions this is handled by automatically changing the in-memory (
HEAP) table to a disk-based (
MyISAM) table as necessary. To work around this problem, you can increase the temporary table size by setting the
mysqld, or by setting the SQL option
BIG_TABLESin the client program. See section 5.5.6
SETSyntax. In MySQL Version 3.20, the maximum size of the temporary table was
record_buffer*16, so if you are using this version, you have to increase the value of
record_buffer. You can also start
--big-tablesoption to always store temporary tables on disk. However, this will affect the speed of many complicated queries.
3 * nis allocated (where
nis the maximum row length, not counting
BLOBuses 5 to 8 bytes plus the length of the
MyISAMstorage engines will use one extra row buffer for internal usage.
BLOBcolumns, a buffer is enlarged dynamically to read in larger
BLOBvalues. If you scan a table, a buffer as large as the largest
BLOBvalue is allocated.
mysqladmin flush-tablescommand closes all tables that are not in use and marks all in-use tables to be closed when the currently executing thread finishes. This will effectively free most in-use memory.
ps and other system status programs may report that
uses a lot of memory. This may be caused by thread-stacks on different
memory addresses. For example, the Solaris version of
the unused memory between stacks as used memory. You can verify this by
checking available swap with
swap -s. We have tested
mysqld with commercial memory-leakage detectors, so there should
be no memory leaks.
When a new thread connects to
mysqld will spawn a
new thread to handle the request. This thread will first check if the
hostname is in the hostname cache. If not the thread will call
gethostbyname_r() to resolve the
If the operating system doesn't support the above thread-safe calls, the
thread will lock a mutex and call
gethostbyname() instead. Note that in this case no other thread
can resolve other hostnames that is not in the hostname cache until the
first thread is ready.
You can disable DNS host lookup by starting
--skip-name-resolve. In this case you can however only use IP
names in the MySQL privilege tables.
If you have a very slow DNS and many hosts, you can get more performance by
either disabling DNS lookop with
--skip-name-resolve or by
HOST_CACHE_SIZE define (default: 128) and recompile
You can disable the hostname cache with
can clear the hostname cache with
FLUSH HOSTS or
If you don't want to allow connections over
TCP/IP, you can do this
SET [GLOBAL | SESSION] sql_variable=expression, [[GLOBAL | SESSION] sql_variable=expression...]
SET sets various options that affect the operation of the
server or your client.
The following examples shows the different syntaxes one can use to set variables:
In old MySQL versions we allowed the use of the
SET OPTION syntax,
but this syntax is now deprecated.
In MySQL 4.0.3 we added the
and access to most important startup variables.
LOCAL can be used as a synonym for
If you set several variables on the same command line, the last used
GLOBAL | SESSION mode is used.
SET sort_buffer_size=10000; SET @@local.sort_buffer_size=10000; SET GLOBAL sort_buffer_size=1000000, SESSION sort_buffer_size=1000000; SET @@sort_buffer_size=1000000; SET @@global.sort_buffer_size=1000000, @@local.sort_buffer_size=1000000;
@@variable_name syntax is supported to make MySQL syntax
compatible with some other databases.
The different system variables one can set are described in the system variable section of this manual. See section 6.1.5 System Variables.
If you are using
SESSION (the default) the option you set remains
in effect until the current session ends, or until you set the option to
a different value. If you use
GLOBAL, which require the
SUPER privilege, the option is remembered and used for new
connections until the server restarts. If you want to make an option
permanent, you should set it in one of the MySQL option
files. See section 4.1.2 `my.cnf' Option Files.
To avoid wrong usage MySQL will give an error if you use
GLOBAL with a variable that can only be used with
SET SESSION or if
you are not using
SET GLOBAL with a global variable.
If you want to set a
SESSION variable to the
GLOBAL value or a
GLOBAL value to the MySQL default value, you can set it to
This is identical to:
If you want to restrict the maximum value a startup option can be set to
SET command, you can specify this by using the
--maximum-variable-name command line option. See section 4.1.1
mysqld Command-line Options.
You can get a list of most variables with
See section 188.8.131.52
SHOW VARIABLES. You can get the value for a specific value with
SHOW VARIABLES like "max_join_size"; SHOW GLOBAL VARIABLES like "max_join_size"; SELECT @@max_join_size, @@global.max_join_size;
Here follows a description of the variables that uses a the variables
that uses a non-standard
SET syntax and some of the other
variables. The other variable definitions can be found in the system
variable section, among the startup options or in the description of
SHOW VARIABLES. See section 6.1.5 System Variables. See section 4.1.1
mysqld Command-line Options. See section 184.108.40.206
CHARACTER SET character_set_name | DEFAULT
cp1251_koi8, but you can easily add new mappings by editing the `sql/convert.cc' file in the MySQL source distribution. The default mapping can be restored by using a
DEFAULT. Note that the syntax for setting the
CHARACTER SEToption differs from the syntax for setting the other options.
PASSWORD = PASSWORD('some password')
PASSWORD FOR user = PASSWORD('some password')
mysqldatabase can do this. The user should be given in
hostnameare exactly as they are listed in the
Hostcolumns of the
mysql.usertable entry. For example, if you had an entry with
'%.loc.gov', you would write:
mysql> SET PASSWORD FOR bob@"%.loc.gov" = PASSWORD("newpass");Which is equivalent to:
mysql> UPDATE mysql.user SET password=PASSWORD("newpass") -> WHERE user="bob" AND host="%.loc.gov";
SQL_AUTO_IS_NULL = 0 | 1
1(default) then one can find the last inserted row for a table with an
AUTO_INCREMENTcolumn with the following construct:
WHERE auto_increment_column IS NULL. This is used by some ODBC programs like Access.
AUTOCOMMIT= 0 | 1
1all changes to a table will be done at once. To start a multi-command transaction, you have to use the
BEGINstatement. See section 6.7.1
ROLLBACKSyntax. If set to
0you have to use
ROLLBACKto accept/revoke that transaction. See section 6.7.1
ROLLBACKSyntax. Note that when you change from not
AUTOCOMMITmode, MySQL will do an automatic
COMMITon any open transactions.
BIG_TABLES = 0 | 1
1, all temporary tables are stored on disk rather than in memory. This will be a little slower, but you will not get the error
The table tbl_name is fullfor big
SELECToperations that require a large temporary table. The default value for a new connection is
0(that is, use in-memory temporary tables). This option was before named
SQL_BIG_TABLES. In MySQL 4.0 you should normally never need this flag as MySQL will automatically convert in memory tables to disk based ones if need.
SQL_BIG_SELECTS = 0 | 1
0, MySQL will abort if a
SELECTis attempted that probably will take a very long time, which is defined as if the number of examined rows is probably going to be bigger than
MAX_JOIN_SIZE. This is useful when an inadvisable
WHEREstatement has been issued. A big query is defined as a
SELECTthat probably will have to examine more than
max_join_sizerows. The default value for a new connection is
1(which will allow all
SELECTstatements). If you set
MAX_JOIN_SIZEto another value than
SQL_BIG_SELECTSwill be set to 0.
SQL_BUFFER_RESULT = 0 | 1
SQL_BUFFER_RESULTwill force the result from
SELECTs to be put into a temporary table. This will help MySQL free the table locks early and will help in cases where it takes a long time to send the result set to the client.
LOW_PRIORITY_UPDATES = 0 | 1
LOCK TABLE WRITEstatements wait until there is no pending
LOCK TABLE READon the affected table. This option was before named
MAX_JOIN_SIZE = value | DEFAULT
SELECTs that will probably need to examine more than
valuerow combinations or is likely to do more than
valuedisk seeks. By setting this value, you can catch
SELECTs where keys are not used properly and that would probably take a long time. Setting this to a value other than
DEFAULTwill reset the
SQL_BIG_SELECTSflag. If you set the
SQL_BIG_SELECTSflag again, the
SQL_MAX_JOIN_SIZEvariable will be ignored. You can set a default value for this variable by starting
-O max_join_size=#. This option was before named
SQL_MAX_JOIN_SIZE. Note that if the result of the query is already in the query cache, the above check will not be made. Instead, MySQL will send the result to the client. Since the query result is already computed and it will not burden the server to send the result to the client.
QUERY_CACHE_TYPE = OFF | ON | DEMAND
QUERY_CACHE_TYPE = 0 | 1 | 2
|0 or OFF||Don't cache or retrieve results.|
|1 or ON|| Cache all results except |
|2 or DEMAND|| Cache only |
SQL_SAFE_UPDATES = 0 | 1
1, MySQL will abort if an
DELETEis attempted that doesn't use a key or
WHEREclause. This makes it possible to catch wrong updates when creating SQL commands by hand.
SQL_SELECT_LIMIT = value | DEFAULT
SELECTstatements. If a
LIMITtakes precedence over the value of
SQL_SELECT_LIMIT. The default value for a new connection is ``unlimited.'' If you have changed the limit, the default value can be restored by using a
SQL_LOG_OFF = 0 | 1
1, no logging is done to the standard log for this client, if the client has the
SQL_LOG_BIN = 0 | 1
0, no logging is done to the binary log for the client, if the client has the
SQL_LOG_UPDATE = 0 | 1
0, no logging is done to the update log for the client, if the client has the
SUPERprivilege. This variable is deprecated starting from version 5.0.
SQL_QUOTE_SHOW_CREATE = 0 | 1
SHOW CREATE TABLEwill quote table and column names. This is on by default, for replication of tables with fancy column names to work. section 220.127.116.11
SHOW CREATE TABLE.
TIMESTAMP = timestamp_value | DEFAULT
timestamp_valueshould be a Unix epoch timestamp, not a MySQL timestamp.
LAST_INSERT_ID = #
LAST_INSERT_ID(). This is stored in the binary log when you use
LAST_INSERT_ID()in a command that updates a table.
INSERT_ID = #
ALTER TABLEcommand when inserting an
AUTO_INCREMENTvalue. This is mainly used with the binary log.
hdparmto configure your disk's interface! The following should be quite good
hdparmoptions for MySQL (and probably many other applications):
hdparm -m 16 -d 1Note that the performance/reliability when using the above depends on your hardware, so we strongly suggest that you test your system thoroughly after using
hdparm! Please consult the
hdparmman page for more information! If
hdparmis not used wisely, filesystem corruption may result. Backup everything before experimenting!
-o asyncoption to set the filesystem to be updated asynchronously. If your computer is reasonably stable, this should give you more performance without sacrificing too much reliability. (This flag is on by default on Linux.)
You can move tables and databases from the database directory to other locations and replace them with symbolic links to the new locations. You might want to do this, for example, to move a database to a file system with more free space or increase the speed of your system by spreading your tables to different disk.
The recommended way to do this, is to just symlink databases to a different disk and only symlink tables as a last resort.
The way to symlink a database is to first create a directory on some disk where you have free space and then create a symlink to it from the MySQL database directory.
shell> mkdir /dr1/databases/test shell> ln -s /dr1/databases/test mysqld-datadir
MySQL doesn't support that you link one directory to multiple
databases. Replacing a database directory with a symbolic link will
work fine as long as you don't make a symbolic link between databases.
Suppose you have a database
db1 under the MySQL data
directory, and then make a symlink
db2 that points to
shell> cd /path/to/datadir shell> ln -s db1 db2
Now, for any table
db1, there also appears to be
db2. If one thread updates
and another thread updates
db2.tbl_a, there will be problems.
If you really need this, you must change the following code in `mysys/mf_format.c':
if (flag & 32 || (!lstat(to,&stat_buff) && S_ISLNK(stat_buff.st_mode)))
On Windows you can use internal symbolic links to directories by compiling
-DUSE_SYMDIR. This allows you to put different
databases on different disks. See section 18.104.22.168 Distributing Data Across Different Disks on Windows.
Before MySQL 4.0 you should not symlink tables, if you are not
very careful with them. The problem is that if you run
REPAIR TABLE or
OPTIMIZE TABLE on a symlinked
table, the symlinks will be removed and replaced by the original
files. This happens because the above command works by creating a
temporary file in the database directory and when the command is
complete, replace the original file with the temporary file.
You should not symlink tables on systems that don't have a fully
realpath() call. (At least Linux and Solaris support
In MySQL 4.0 symlinks are fully supported only for
tables. For other table types you will probably get strange problems
when doing any of the above mentioned commands.
The handling of symbolic links in MySQL 4.0 works the following
way (this is mostly relevant only for
mysqldis not running) or with the
INDEX/DATA DIRECTORY="path-to-dir"command in
CREATE TABLE. See section 6.5.3
myisamchkwill not replace a symlink with the data or index file but work directly on the file the symlink points to. Any temporary files will be created in the same directory where the data or index file is located.
rootor allow persons to have write access to the MySQL database directories.
ALTER TABLE RENAMEand you don't move the table to another database, the symlinks in the database directory will be renamed to the new names and the data and index files will be renamed accordingly.
ALTER TABLE RENAMEto move a table to another database, the table will be moved to the other database directory and the old symlinks and the files they pointed to will be deleted. (In other words, the new table will not be symlinked.)
mysqldto ensure that no one can drop or rename a file outside of the
Things that are not yet supported:
ALTER TABLEignores all
CREATE TABLEdoesn't report if the table has symbolic links.
mysqldumpdoesn't include the symbolic link information in the output.
RESTORE TABLEdon't respect symbolic links.
Go to the first, previous, next, last section, table of contents.