\input texinfo  @c -*-texinfo-*-
@c Copyright 1997, 1998 TcX AB, Detron HB and Monty Program KB
@c
@c *********************************************************
@c Note that @node names are used on our Website.
@c So do not change node names without checking
@c Makefile.am and SitePages first.
@c *********************************************************
@c
@c %**start of header
@setfilename mysql.info
@c We want the types in the same index
@syncodeindex tp fn
@c Get version info
@include include.texi
@ifclear tex-debug
@c This removes the black squares in the right margin
@finalout
@end ifclear
@c Set background for HTML
@set _body_tags BGCOLOR=#FFFFFF TEXT=#000000 LINK=#101090 VLINK=#7030B0
@settitle @strong{MySQL} Reference Manual for version @value{mysql_version}.
@setchapternewpage on
@paragraphindent 0
@c %**end of header

@set default_port 3306

@ifinfo
@format
START-INFO-DIR-ENTRY
* mysql: (mysql).               @strong{MySQL} documentation.
END-INFO-DIR-ENTRY
@end format
@end ifinfo

@c @iftex
@c @headings off
@c @everyheading @| @thispage @| @thischapter
@c @everyfooting @| @| Version: @value{mysql_version} @today{}
@c @end iftex

@titlepage
@sp 10
@center @titlefont{@strong{MySQL} Reference Manual}
@sp 10
@center Copyright @copyright{} 1997, 1998, 1999 TcX AB, Detron HB and Monty Program KB
@end titlepage

@node Top, Introduction, (dir), (dir)

@ifhtml
<IMG SRC="Img/mysql5.gif">
@end ifhtml

@ifinfo
This is a manual for @strong{MySQL}. This version is about the
@value{mysql_version} version of @strong{MySQL}. For a @strong{3.20}
version see the relevant distribution.
@end ifinfo

@menu
* Introduction::                General Information about @strong{MySQL}
* Questions::                   @strong{MySQL} mailing lists and how to ask questions or report errors (bugs)
* Licensing and Support::       @strong{MySQL} licensing and support
* Installing::                  Installing @strong{MySQL}
* Compatibility::               How standards-compatible is @strong{MySQL}?
* Privilege system::            The @strong{MySQL} access privilege system
* Reference::                   @strong{MySQL} language reference
* Tutorial::                    @strong{MySQL} Tutorial
* Server::                      @strong{MySQL} Server
* Performance::                 Getting maximum performance from @strong{MySQL}
* Benchmarks::                  The @strong{MySQL} benchmark suite
* Tools::                       @strong{MySQL} Utilities
* Maintenance::                 Maintaining a @strong{MySQL} installation
* Adding functions::            Adding new functions to @strong{MySQL}
* Adding procedures::           Adding new procedures to @strong{MySQL}
* ODBC::                        @strong{MySQL} ODBC Support
* Problems::                    Problems
* Common problems::             Solving some common problems with @strong{MySQL}
* Clients::                     @strong{MySQL} client tools and APIs
* Comparisons::                 How does @strong{MySQL} compare with other databases?
* Users::                       Some @strong{MySQL} users
* Contrib::                     Contributed programs
* Credits::                     Contributors to @strong{MySQL}
* News::                        @strong{MySQL} change history
* Bugs::                        Known errors and design deficiencies in @strong{MySQL}
* TODO::                        List of things we want to add to @strong{MySQL} in the future (The TODO)
* Porting::                     Comments on porting to other systems
* Regexp::                      Description of @strong{MySQL} regular expression syntax
* Unireg::                      What is Unireg?
* Public license::              The @strong{MySQL} server license
* Win license::                 The @strong{MySQL} license for Microsoft operating systems
* Function Index::              SQL command, type and function index
* Concept Index::               Concept Index

@end menu

@cindex Overview
@cindex General Information
@node Introduction, Questions, Top, Top
@chapter General Information about @strong{MySQL}

@menu
* What-is::                     What is @strong{MySQL}?
* Manual-info::                 About this manual
* History::                     History of @strong{MySQL}
* Features::                    The main features of @strong{MySQL}
* Stability::                   How stable is @strong{MySQL}?
* Year 2000 compliance::        Year 2000 compliance
* General-SQL::                 General SQL information and tutorials
* Useful Links::                Useful @strong{MySQL}-related links
@end menu

This is the @strong{MySQL} reference manual; it documents @strong{MySQL}
version @value{mysql_version}.


@strong{MySQL} is a very fast, multi-threaded, multi-user and robust SQL
(Structured Query Language) database server.

For Unix and OS/2 platforms, @strong{MySQL} is basically free; for Microsoft
platforms you must get a @strong{MySQL} license after a trial time of 30
days. @xref{Licensing and Support}.

@uref{http://www.mysql.com/, The @strong{MySQL} home page}
provides the latest information about @strong{MySQL}.

For a discussion of @strong{MySQL}'s capabilities, see @ref{Features}.

For installation instructions, see @ref{Installing}. For tips on porting
@strong{MySQL} to new machines or operating systems, see @ref{Porting}.

For information about upgrading from a 3.21 release, see
@ref{Upgrading-from-3.21}.

For a tutorial introduction to MySQL, see
@ref{Tutorial}.

For examples of SQL and benchmarking information, see the benchmarking
directory.  For source distributions, this is the @file{bench}
directory.  For binary distributions, this is the @file{sql-bench}
directory.

For a history of new features and bug fixes, see @ref{News}.

For a list of currently known bugs and misfeatures, see @ref{Bugs}.

For future plans, see @ref{TODO}.

For a list of all the contributors to this product, see @ref{Credits}.

@strong{IMPORTANT:}

Send bug (error) reports, questions and comments to the mailing list at
@email{mysql@@lists.mysql.com}.  @xref{Bug reports}.

For source distributions, the @code{mysqlbug} script can be found in the
@file{scripts} directory.  For binary distributions, @code{mysqlbug} can be
found in the @file{bin} directory.

If you have any suggestions concerning additions or corrections to this
manual, please send them to the @strong{MySQL} mailing list
(@email{mysql@@lists.mysql.com}) with the following subject line:
@code{documentation suggestion: [Insert Topic Here]}.
@xref{Mailing-list}.

@cindex @strong{MySQL}, what it is
@node What-is, Manual-info, Introduction, Introduction
@section What is @strong{MySQL}?

@strong{MySQL} is a true multi-user, multi-threaded SQL database server. SQL
is the most popular database language in the world. @strong{MySQL} is a
client/server implementation that consists of a server daemon @code{mysqld}
and many different client programs and libraries.

SQL is a standardized language that makes it easy to store,
update and access information. For example, you can use SQL to retrieve
product information and store customer information for a web site.
@strong{MySQL} is also fast and flexible enough to allow you to store
logs and pictures in it.

The main goals of @strong{MySQL} are speed, robustness and ease of use.
@strong{MySQL} was originally developed because we at TcX needed a SQL server
that could handle very large databases an order of magnitude faster than what
any database vendor could offer to us. We have now been using @strong{MySQL}
since 1996 in an environment with more than 40 databases containing 10,000
tables, of which more than 500 have more than 7 million rows. This is about
100 gigabytes of mission-critical data.

The base upon which @strong{MySQL} is built is a set of routines that have
been used in a highly demanding production environment for many years.
Although @strong{MySQL} is still under development, it already offers a rich
and highly useful function set.

@cindex How to pronounce @strong{MySQL}
@cindex @strong{MySQL}, how to pronounce
The official way to pronounce @strong{MySQL} is ``My Ess Que Ell'' (Not
MY-SEQUEL).

@cindex Manual information
@node Manual-info, History, What-is, Introduction
@section About this manual

@menu
* Manual conventions::          Conventions used in this manual
@end menu

This manual is currently available in Texinfo, plain text, Info, HTML,
PostScript and PDF versions.  Because of their size, PostScript and PDF
versions are not included with the main @strong{MySQL} distribution, but
are available for separate download at
@uref{http://www.mysql.com}.

The primary document is the Texinfo file. The HTML version is produced
automatically with a modified version of @code{texi2html}. The plain text and
Info versions are produced with @code{makeinfo}. The Postscript version is
produced using @code{texi2dvi} and @code{dvips}.  The PDF version is produced
with the Ghostscript utility @code{ps2pdf}.

This manual is written and maintained by David Axmark, Michael (Monty)
Widenius, Paul DuBois and Kim Aldale. For other contributors, see
@ref{Credits}.

@node Manual conventions,  , Manual-info, Manual-info
@subsection Conventions used in this manual

This manual uses certain typographical conventions:

@table @asis
@item @code{constant}
Constant-width font is used for command names and options; SQL statements;
database, table and column names; C and Perl code; and environment variables.
Example: ``To see how @code{mysqladmin} works, invoke it with the
@code{--help} option.''

@item @file{filename}
Constant-width font with surrounding quotes is used for filenames and
pathnames.  Example: ``The distribution is installed under the
@file{/usr/local/} directory.''

@item @samp{c}
Constant-width font with surrounding quotes is also used to indicate
character sequences.  Example: ``To specify a wildcard, use the @samp{%}
character.''

@item @emph{italic}
Italic font is used for emphasis, @emph{like this}.

@item @strong{boldface}
Boldface font is used for access privilege names (e.g., ``do not grant the
@strong{process} privilege lightly'') and to convey @strong{especially strong
emphasis}.
@end table

When commands are shown that are meant to be executed by a particular
program, the program is indicated by the prompt shown with the command.  For
example, @code{shell>} indicates a command that you execute from your login
shell, and @code{mysql>} indicates a command that you execute from the
@code{mysql} client:

@example
shell> type a shell command here
mysql> type a mysql command here
@end example

Shell commands are shown using Bourne shell syntax.  If you are using a
@code{csh}-style shell, you may need to issue commands slightly differently.
For example, the sequence to set an environment variable and run a command
looks like this in Bourne shell syntax:

@example
shell> VARNAME=value some_command
@end example

For @code{csh}, you would execute the sequence like this:

@example
shell> setenv VARNAME value
shell> some_command
@end example

Database, table and column names often must be substituted into commands.  To
indicate that such substitution is necessary, this manual uses
@code{db_name}, @code{tbl_name} and @code{col_name}.  For example, you might
see a statement like this:

@example
mysql> SELECT col_name FROM db_name.tbl_name;
@end example

This means that if you were to enter a similar statement, you would supply
your own database, table and column names, perhaps like this:

@example
mysql> SELECT author_name FROM biblio_db.author_list;
@end example

SQL statements may be written in uppercase or lowercase.  When this manual
shows a SQL statement, uppercase is used for particular keywords if those
keywords are under discussion (to emphasize them) and lowercase is used for
the rest of the statement.  So you might see the following in a discussion of
the @code{SELECT} statement:

@example
mysql> SELECT count(*) FROM tbl_name;
@end example

On the other hand, in a discussion of the @code{COUNT()} function, the
statement would be written like this:

@example
mysql> select COUNT(*) from tbl_name;
@end example

If no particular emphasis is intended, all keywords are written uniformly
in uppercase.

In syntax descriptions, square brackets (@samp{[} and @samp{]}) are used
to indicate optional words or clauses:

@example
DROP TABLE [IF EXISTS] tbl_name
@end example

When a syntax element consists of a number of alternatives, the alternatives
are separated by vertical bars (@samp{|}).  When one member from a set of
choices may be chosen, the alternatives are listed within square brackets.
When one member from a set of choices must be chosen, the alternatives are
listed within braces (@samp{@{} and @samp{@}}):

@example
TRIM([[BOTH | LEADING | TRAILING] [remstr] FROM] str)
@{DESCRIBE | DESC@} tbl_name @{col_name | wild@}
@end example

@cindex @strong{MySQL} version
@node History, Features, Manual-info, Introduction
@section History of @strong{MySQL}

We once started off with the intention of using @code{mSQL} to connect to our
tables using our own fast low-level (ISAM) routines. However, after some
testing we came to the conclusion that @code{mSQL} was not fast enough or
flexible enough for our needs. This resulted in a new SQL interface to our
database but with almost the same API interface as @code{mSQL}. This API was
chosen to ease porting of third-party code.

The derivation of the name @strong{MySQL} is not perfectly clear.  Our base
directory and a large number of our libraries and tools have had the prefix
``my'' for well over 10 years. However, Monty's daughter (some years younger)
is also named My. So which of the two gave its name to @strong{MySQL} is
still a mystery, even for us.

@node Features, Stability, History, Introduction
@section The main features of @strong{MySQL}

The following list describes some of the important characteristics
of @strong{MySQL}:

@c This list is too technical and should be divided into one feature
@c list comparable to commercial competition and a very technical on
@c with max limits (from crash-me) and so on.
@itemize @bullet
@item
Fully multi-threaded using kernel threads. That means it easily can
use multiple CPUs if available.

@item
C, C++, Java, Perl, PHP, Python and TCL APIs. @xref{Clients}.

@item
Works on many different platforms. @xref{Which OS}.

@item
Many column types: signed/unsigned integers 1, 2, 3, 4 and 8 bytes
long, @code{FLOAT}, @code{DOUBLE}, @code{CHAR}, @code{VARCHAR},
@code{TEXT}, @code{BLOB}, @code{DATE}, @code{TIME}, @code{DATETIME},
@code{TIMESTAMP}, @code{YEAR}, @code{SET} and @code{ENUM} types. @xref{Column
types}.

@item
Very fast joins using an optimized one-sweep multi-join.

@item
Full operator and function support in the @code{SELECT} and @code{WHERE}
parts of queries. Example:
@example
mysql> SELECT CONCAT(first_name, " ", last_name) FROM tbl_name
           WHERE income/dependents > 10000 AND age > 30;
@end example

@item
SQL functions are implemented through a highly-optimized class library and
should be as fast as they can get! Usually there shouldn't be any memory
allocation at all after query initialization.

@item
Full support for SQL @code{GROUP BY} and @code{ORDER BY} clauses. Support for
group functions (@code{COUNT()}, @code{AVG()}, @code{STD()}, @code{SUM()},
@code{MAX()} and @code{MIN()}).

@item
Support for @code{LEFT OUTER JOIN} with ANSI SQL and ODBC syntax.

@item
You can mix tables from different databases in the same query (as of
version 3.22).

@item
A privilege and password system which is very flexible and secure, and
which allows host-based verification.  Passwords are secure since all
password traffic when connecting to a server is encrypted.

@item
ODBC (Open-DataBase-Connectivity) for Windows95 (with source). All ODBC
2.5 functions and many others.  You can, for example, use Access to
connect to your @strong{MySQL} server. @xref{ODBC}.

@item
Very fast B-tree disk tables with index compression.

@item
16 indexes per table are allowed. Each index may consist of 1 to 15 columns
or parts of columns. The maximum index length is 256 bytes (this may be
changed when compiling @strong{MySQL}). An index may use a prefix of a
@code{CHAR} or @code{VARCHAR} field.

@item
Fixed-length and variable-length records.

@item
In-memory hash tables which are used as temporary tables.

@item
Handles large databases.  We are using @strong{MySQL} with some
databases that contain 50,000,000 records.

@item
All columns have default values.  You can use @code{INSERT} to insert a
subset of a table's columns; those columns that are not explicitly given
values are set to their default values.

@item
Uses GNU Automake, Autoconf, and @code{libtool} for portability.

@item
Written in C and C++. Tested with a broad range of different compilers.

@item
A very fast thread-based memory allocation system.

@item
No memory leaks. Tested with a commercial memory leakage detector
(@code{purify}).

@item
Includes @code{isamchk}, a very fast utility for table checking, optimization
and repair.
@xref{Maintenance}.

@item
Full support for the ISO-8859-1 Latin1 character set. For example, the
Scandinavian characters @ringaccent{a}, @"a and @"o are allowed in table and
column names.

@item
All data are saved in ISO-8859-1 Latin1 format. All comparisons for normal
string columns are case insensitive.

@item
Sorting is done according to the ISO-8859-1 Latin1 character set (the Swedish
way at the moment). It is possible to change this in the source by adding new
sort order arrays. To see an example of very advanced sorting, look at the
Czech sorting code. @strong{MySQL} supports many different character sets
that can be specified at compile time.

@item
Aliases on tables and columns as in the SQL92 standard.

@item
@code{DELETE}, @code{INSERT}, @code{REPLACE}, and @code{UPDATE} return
how many rows were changed (affected).

@item
Function names do not clash with table or column names. For example, @code{ABS}
is a valid column name. The only restriction is that for a function call, no
spaces are allowed between the function name and the @samp{(} that follows it.
@xref{Reserved words}.

@item
All @strong{MySQL} programs can be invoked with the @code{--help} or @code{-?}
options to obtain online assistance.

@item
The server can provide error messages to clients in many
languages. @xref{Languages}.

@item
Clients connect to the @strong{MySQL} server using TCP/IP connections or Unix
sockets, or named pipes under NT.

@item
The @strong{MySQL}-specific @code{SHOW} command can be used to retrieve
information about databases, tables and indexes. The @code{EXPLAIN} command
can be used to determine how the optimizer resolves a query.
@end itemize

@cindex Stability
@node Stability, Year 2000 compliance, Features, Introduction
@section How stable is @strong{MySQL}?

This section addresses the questions, ``how stable is
@strong{MySQL}?'' and, ``can I depend on @strong{MySQL} in this project?''
Here we will try to clarify some issues and to answer some of the more
important questions that seem to concern many people.  This section has been
put together from information gathered from the mailing list (which is very
active in reporting bugs).

At TcX, @strong{MySQL} has worked without any problems in our projects since
mid-1996. When @strong{MySQL} was released to a wider public, we noticed that
there were some pieces of ``untested code'' that were quickly found by the
new users who made queries in a manner different than our own.  Each new
release has had fewer portability problems than the previous one (even though
each has had many new features), and we hope that it will be possible to label
one of the next releases ``stable''.

Each release of @strong{MySQL} has been usable and there have been problems
only when users start to use code from ``the gray zones''. Naturally, outside
users can't know what the gray zones are; this section attempts to indicate
those that are currently known.  The descriptions deal with the 3.22.x
version of @strong{MySQL}. All known and reported bugs are fixed in the
latest version, with the exception of the bugs listed in the bugs section,
which are things that are ``design''-related.  @xref{Bugs}.

@strong{MySQL} is written in multiple layers and different independent
modules.  These modules are listed below with an indication of how
well-tested each of them is:

@table @strong
@item The ISAM table handler --- Stable
This manages storage and retrieval of all data. In all @strong{MySQL}
releases there hasn't been a single (reported) bug in this code. The only
known way to get a corrupted table is to kill the server in the middle of an
update.  Even that is unlikely to destroy any data beyond rescue, because all
data are flushed to disk between each query.  There hasn't been a single bug
report about lost data because of bugs in @strong{MySQL}, either.

@item The parser and lexical analyser --- Stable
There hasn't been a single reported bug in this system for a long time.

@item The C client code --- Stable
No known problems. In early 3.20 releases, there were some limitations in
the send/receive buffer size. As of 3.21.x, the buffer size is now dynamic up
to a default of 24M.

@item Standard client programs --- Stable
These include @code{mysql}, @code{mysqladmin} and @code{mysqlshow},
@code{mysqldump}, and @code{mysqlimport}.

@item Basic SQL --- Stable
The basic SQL function system and string classes and dynamic memory
handling. Not a single reported bug in this system.

@item Query optimizer --- Gamma

@item Range optimizer --- Stable

@item Join optimizer --- Stable

@item Locking --- Gamma
This is very system-dependent. On some systems there are big problems
using standard OS locking (@code{fcntl()}).  In these cases, you should run the
@strong{MySQL} daemon with the @code{--skip-locking} flag.  Problems are known
to occur on some Linux systems and on SunOS when using NFS-mounted file
systems.

@item Linux threads --- Gamma
The only problem found has been with the @code{fcntl()} call, which is fixed
by using the @w{@code{--skip-locking}} option to @code{mysqld}. Some people
have reported lockup problems with the 0.5 release.

@item Solaris 2.5+ pthreads --- Stable
We use this for all our production work.

@item MIT-pthreads (Other systems) --- Gamma
There have been no reported bugs since 3.20.15 and no known bugs since
3.20.16. On some systems, there is a ``misfeature'' where some operations are
quite slow (a 1/20 second sleep is done between each query). Of course,
MIT-pthreads may slow down everything a bit, but index-based @code{SELECT}
statements are usually done in one time frame so there shouldn't be a mutex
locking/thread juggling.

@item Other thread implementions --- Alpha - Beta
The ports to other systems are still very new and may have bugs, possibly
in @strong{MySQL}, but most often in the thread implementation itself.

@item @code{LOAD DATA ...}, @code{INSERT ... SELECT} --- Stable
Some people have thought they have found bugs here, but these usually have
turned out to be misunderstandings. Please check the manual before reporting
problems!

@item @code{ALTER TABLE} --- Gamma
Small changes in 3.22.12.

@item DBD --- Gamma
Now maintained by Jochen Wiedmann
@email{wiedmann@@neckar-alb.de}. Thanks!

@item @code{mysqlaccess} --- Gamma
Written and maintained by Yves Carlier
@email{Yves.Carlier@@rug.ac.be}. Thanks!

@item @code{GRANT} --- Beta
Big changes made in @strong{MySQL} 3.22.12.

@item @strong{MyODBC} (uses ODBC SDK 2.5) --- Beta
It seems to work well with some programs.
@end table

TcX provides email support for paying customers, but the @strong{MySQL}
mailing list usually provides answers to common questions. Bugs are
usually fixed right away with a patch; for serious bugs, there is almost
always a new release.

@cindex Year 2000 compliance
@node Year 2000 compliance, General-SQL, Stability, Introduction
@section Year 2000 compliance

@strong{MySQL} itself has no problems with Year 2000 (Y2K) compliance:

@itemize @bullet
@item
@strong{MySQL} uses Unix time functions and has no problems with dates
until @code{2069}; all 2-digit years are regarded to be in the range
@code{1970} to @code{2069}, which means that if you store @code{01} in a
@code{year} column, @strong{MySQL} treats it as @code{2001}.

@item
All @strong{MySQL} date
functions are stored in one file @file{sql/time.cc} and coded very carefully
to be year 2000-safe.

@item
In @strong{MySQL} 3.22 and later versions, the new @code{YEAR} column type
can store years @code{0} and @code{1901} to @code{2155} in 1 byte and display
them using 2 or 4 digits.
@end itemize

You may run into problems with applications that use @strong{MySQL} in a
way that is not Y2K-safe.  For example, many old applications store
or manipulate years using 2-digit values (which are ambiguous) rather than
4-digit values.  This problem may be compounded by applications that use
values such as @code{00} or @code{99} as ``missing'' value indicators.

Unfortunately, these problems may be difficult to fix, since different
applications may be written by different programmers, each of whom may
use a different set of conventions and date-handling functions.

Here is a simple demonstration illustrating that @strong{MySQL} doesn't have
any problems with dates until the year 2030!

@example
mysql> DROP TABLE IF EXISTS y2k;
mysql> CREATE TABLE y2k (date date, date_time datetime, time_stamp timestamp);
mysql> INSERT INTO y2k VALUES ("1998-12-31","1998-12-31 23:59:59",19981231235959);
mysql> INSERT INTO y2k VALUES ("1999-01-01","1999-01-01 00:00:00",19990101000000);
mysql> INSERT INTO y2k VALUES ("1999-09-09","1999-09-09 23:59:59",19990909235959);
mysql> INSERT INTO y2k VALUES ("2000-01-01","2000-01-01 00:00:00",20000101000000);
mysql> INSERT INTO y2k VALUES ("2000-02-28","2000-02-28 00:00:00",20000228000000);
mysql> INSERT INTO y2k VALUES ("2000-02-29","2000-02-29 00:00:00",20000229000000);
mysql> INSERT INTO y2k VALUES ("2000-03-01","2000-03-01 00:00:00",20000301000000);
mysql> INSERT INTO y2k VALUES ("2000-12-31","2000-12-31 23:59:59",20001231235959);
mysql> INSERT INTO y2k VALUES ("2001-01-01","2001-01-01 00:00:00",20010101000000);
mysql> INSERT INTO y2k VALUES ("2004-12-31","2004-12-31 23:59:59",20041231235959);
mysql> INSERT INTO y2k VALUES ("2005-01-01","2005-01-01 00:00:00",20050101000000);
mysql> INSERT INTO y2k VALUES ("2030-01-01","2030-01-01 00:00:00",20300101000000);
mysql> INSERT INTO y2k VALUES ("2050-01-01","2050-01-01 00:00:00",20500101000000);
mysql> SELECT * FROM y2k;
+------------+---------------------+----------------+
| date       | date_time           | time_stamp     |
+------------+---------------------+----------------+
| 1998-12-31 | 1998-12-31 23:59:59 | 19981231235959 |
| 1999-01-01 | 1999-01-01 00:00:00 | 19990101000000 |
| 1999-09-09 | 1999-09-09 23:59:59 | 19990909235959 |
| 2000-01-01 | 2000-01-01 00:00:00 | 20000101000000 |
| 2000-02-28 | 2000-02-28 00:00:00 | 20000228000000 |
| 2000-02-29 | 2000-02-29 00:00:00 | 20000229000000 |
| 2000-03-01 | 2000-03-01 00:00:00 | 20000301000000 |
| 2000-12-31 | 2000-12-31 23:59:59 | 20001231235959 |
| 2001-01-01 | 2001-01-01 00:00:00 | 20010101000000 |
| 2004-12-31 | 2004-12-31 23:59:59 | 20041231235959 |
| 2005-01-01 | 2005-01-01 00:00:00 | 20050101000000 |
| 2030-01-01 | 2030-01-01 00:00:00 | 20300101000000 |
| 2050-01-01 | 2050-01-01 00:00:00 | 00000000000000 |
+------------+---------------------+----------------+

13 rows in set (0.00 sec)
mysql> DROP TABLE y2k;
@end example

This shows that the @code{DATE} and @code{DATETIME} types are @strong{Date
Data} compliant, while the @code{TIMESTAMP} type, that is used to store the
current time, has a range up to only @code{2030-01-01}. @code{TIMESTAMP} has
a range of @code{1970} to @code{2030} on 32-bit machines.

Even though @strong{MySQL} is Y2K-compliant, it is your responsibility to
provide unambiguous input.  See @ref{Y2K issues} for @strong{MySQL}'s rules
for dealing with ambiguous date input data (data containing 2-digit year
values).

@node General-SQL, Useful Links, Year 2000 compliance, Introduction
@section General SQL information and tutorials

This book has been recommended by a several people on the @strong{MySQL}
mailing list:

@example
Judith S. Bowman, Sandra L. Emerson and Marcy Darnovsky
The Practical SQL Handbook: Using Structured Query Language
Second Edition
Addison-Wesley
ISBN 0-201-62623-3
http://www.awl.com
@end example

This book has also received some recommendations on the mailing list:

@example
Martin Gruber
Understanding SQL
ISBN 0-89588-644-8
Publisher Sybex 510 523 8233
Alameda, CA USA
@end example

A SQL tutorial is available on the net at
@url{http://w3.one.net/~jhoffman/sqltut.htm}.

@node Useful Links,  , General-SQL, Introduction
@section Useful @strong{MySQL}-related links

@subheading Web development tools that support @strong{MySQL}

@itemize @bullet
@item
@uref{http://www.php.net/, PHP: A server-side HTML-embedded scripting
language}
@item
@uref{http://www.voicenet.com/~zellert/tjFM, A JDBC driver for @strong{MySQL}}
@item
@uref{http://www.wernhart.priv.at/php/, @strong{MySQL} + PHP demos}
@item
@uref{http://www.dbwww.com/, ForwardSQL: HTML interface to manipulate @strong{MySQL} databases}
@item
@uref{http://www.daa.com.au/~james/www-sql/, WWW-SQL: Display database
information}
@item
@uref{http://www.minivend.com/minivend/, Minivend: A Web shopping cart}
@item
@uref{http://www.heitml.com/, HeiTML: A server-side extension of HTML and
a 4GL language at the same time}
@item
@uref{http://www.metahtml.com/, Metahtml: A Dynamic Programming Language
for WWW Applications}
@item
@uref{http://www.binevolve.com/, VelocityGen for Perl and TCL}
@item
@uref{http://hawkeye.net/, Hawkeye Internet Server Suite}
@item
@uref{http://www.fastflow.com/, Network Database Connection For Linux}
@item
@uref{http://www.wdbi.net/,
WDBI: Web browser as a universal front end to databases which supports
@strong{MySQL} well.}
@item
@uref{http://www.webgroove.com/, WebGroove Script: HTML compiler and server-side scripting language}
@item
@uref{http://www.ihtml.com/, A server-side web site scripting language}
@item
@uref{http://www.pbc.ottawa.on.ca,Visual Basic class generator for Active X}
@item
@uref{ftp://ftp.igc.org/pub/myodbc/README, How to use @strong{MySQL} with Coldfusion on Solaris}
@item
@uref{http://calistra.com/MySQL/,Calistra's ODBC @strong{MySQL} Administrator}
@item
@uref{http://www.webmerger.com, Webmerger}
This CGI tool interprets files and generates dynamic output
based on a set of simple tags. Ready-to-run drivers for @strong{MySQL} and PostgreSQL
through ODBC.
@end itemize

@subheading Web servers with @strong{MySQL} tools

@itemize @bullet
@item
@uref{http://bourbon.netvision.net.il/mysql/mod_auth_mysql/, An Apache
authentication module}
@item
@uref{http://www.roxen.com/, The Roxen Challenger Web server}
@end itemize

@subheading Examples and source

@itemize @bullet
@item
@c Added 990601
@c EMAIL: thuss@little6.com (Todd Huss)
@uref{http://www.little6.com/about/linux/, Little6 Inc} An online contract and job finding site that is powered by @strong{MySQL}, PHP3 and Linux.
@item
@c Added 990521
@c EMAIL: nh@delec.com (Hillbrecht Nicole)
@uref{http://www.delec.com/is/products/prep/examples/BookShelf/index.html, DELECis} A tool which makes it very easy to create an automatically generated table documentation. They have used @strong{MySQL} as an example.
@item
@c Added 990531
@c EMAIL: sfambro@hotmail.com (Steve Fambro)
@uref{http://shredder.elen.utah.edu/steve.html, Steve Fambro} Uses @strong{MySQL} and webmerger. There is an employee database, and a license plate database with all of the
registered Utah vehicles (over 1.2 million). The License plate field is
indexed.....so the *searches* are instantaneous.
@item
@c Added 990521
@c EMAIL: info@worldrecords.com (Jim Rota)
@uref{http://www.worldrecords.com, World Records} A search engine for information about music that uses @strong{MySQL} and PHP.
@item
@uref{http://webdev.berber.co.il/, Examples using @strong{MySQL}; (check Top 10)}
@item
@uref{http://www.webtechniques.com/features/1998/01/note/note.shtml,
A Contact Database using @strong{MySQL} and PHP}
@item
@uref{http://modems.rosenet.net/mysql/, Web based interface and Community Calender with PHP}
@item
@uref{http://www.odbsoft.com/cook/sources.htm, Perl package to generate html from a SQL table structure and for generating SQL statements from an html form.}
@item
@uref{http://www.gus.ml.org/proj/telsql/,Basic telephone database using @code{DBI}/@code{DBD}}.
@item
@uref{http://www.productivity.org/projects/mysql/, @strong{TmySQL}; A library to use @strong{MySQL} with Delphi}
@item
@uref{http://www.iserver.com/support/contrib/perl5/modules.html,Installing new Perl modules that require locally installed modules}
@item
@uref{http://tecfa.unige.ch/guides/java/staf2x/ex/jdbc/coffee-break, JDBC examples by Daniel K. Schneider}
@item
@uref{http://www.spade.com/linux/howto/PostgreSQL-HOWTO-41.html,SQL BNF}
@item
@uref{http://www.ooc.com/, Object Oriented Concepts Inc; CORBA applications with examples in source}
@item
@uref{http://www.pbc.ottawa.on.ca/,DBWiz; Includes an example of how to manage own cursors in VB}
@item
@uref{http://keilor.cs.umass.edu/pluribus/, Pluribus}
Pluribus, is a free search engine that learns to improve
the quality of its results over time. Pluribus works by recording
which pages a user prefers among those returned for a query. A user
votes for a page by selecting it; Pluribus then uses that knowledge
to improve the quality of the results when someone else submits the
same (or similar) query. Uses PHP and @strong{MySQL}.
@item
@c EMAIL: paul@sword.damocles.com (Paul Bannister)
@uref{http://www.stopbit.com/, Stopbit}
A technology news site using @strong{MySQL} and PHP
@item
@uref{http://www.jokes2000.com/scripts/, Example scripts at Jokes2000}
@end itemize

@subheading @strong{ODBC} related links

@itemize @bullet
@item
@uref{http://www.openlinksw.com/iodbc/,Popular iODBC Driver Manager now available in Open Source format}
@item
@uref{http://users.ids.net/~bjepson/freeODBC/,The FreeODBC Pages}
@end itemize

@subheading @strong{API} related links

@itemize @bullet
@item
@uref{http://www.jppp.com, www.jppp.com}
Partially implemented TDataset-compatible components for @strong{MySQL}.
@end itemize


@subheading Other @strong{MySQL}-related links

@itemize @bullet
@item
@uref{http://www.wix.com/mysql-hosting, Registry of Web providers who
support @strong{MySQL}}
@uref{http://www.softagency.co.jp/mysql/index.en.phtml, Links about using
@strong{MySQL} in Japan/Asia}
@item
@uref{http://www.open.com.au/products.html, Commercial Web defect tracking
system}
@item
@uref{http://www.stonekeep.com/pts/, PTS: Project Tracking System}
@item
@uref{http://tomato.nvgc.vt.edu/~hroberts/mot, Job and software tracking
system}
@item
@uref{http://www.seawood.org/msql_bind/, Support for BIND (The Internet
Domain Name Server)}
@item
@uref{http://home.wxs.nl/cgi-bin/planeteers/pgidszoek.cgi, Full-text search engine using @strong{MySQL}}
@item
@uref{http://www.cynergi.net/non-secure/exportsql/, ExportSQL: A script
to export data from Access95+}
@item
@uref{http://SAL.KachinaTech.COM/H/1/MYSQL.html, SAL (Scientific
Applications on Linux) @strong{MySQL} entry}

@c Removed 990510
@c @item
@c @uref{http://www.cgishop.com/bin/mysqllist, @strong{MySQL} Apps and
@c Utilities Listing}

@c @item
@c @uref{http://www.luth.se/~goggi/proj/mysql/man/mysql.pdf, The
@c @strong{MySQL} reference manual in Adobe PDF format}

@item
@uref{http://www.infotech-nj.com/itech/index.shtml, A consulting company
which mentions @strong{MySQL} in the right company}
@item
@uref{http://www.pmpcs.com/, PMP Computer Solutions. Database developers using
@strong{MySQL} and @code{mSQL}}
@item
@uref{http://www.aewa.org, Airborne Early Warning Association }
@item
@uref{http://abattoir.cc.ndsu.nodak.edu/~nem/mysql/udf/, @strong{MySQL} UDF Registry}
@end itemize

@subheading SQL and database interfaces
@itemize @bullet
@item
@c EMAIL: bilhaut_f@mail.cpod.fr (Frédérik Bilhaut)
@uref{http://www.penguinpowered.com/~kmysql, KMySQL}
KMySQL is a database client for KDE that primarily supports @strong{MySQL}.
@item
@uref{http://java.sun.com/products/jdbc/, The JDBC database access API}
@item
@uref{http://tfdec1.fys.kuleuven.ac.be/~michael/fpc-linux/mysql,
@strong{MySQL} binding to Free Pascal}
@item
@uref{http://www.gagme.com/mysql, Patch for @code{mSQL} TCL}
@item
@uref{http://www.amsoft.ru/easysql/, EasySQL: An ODBC-like driver manager}
@item
@uref{http://www.lightlink.com/hessling/rexxsql.html, A REXX interface to SQL databases}
@item
@uref{http://www.binevolve.com/~tdarugar/tcl-sql, TCL interface}
@item
@uref{http://tim.desert.net/~tim/imger/,Example of storing/retrieving images with @strong{MySQL} and CGI}
@end itemize

@subheading General database links
@itemize @bullet
@item
@uref{http://www.pcslink.com/~ej/dbweb.html, Database Jump Site}
@item
@uref{http://black.hole-in-the.net/guy/webdb/, Homepage of the webdb-l
(Web Databases) mailing list.}
@item
@uref{http://www.symbolstone.org/technology/perl/DBI/index.html,
Perl @code{DBI}/@code{DBD} modules homepage}
@item
@uref{http://www-public.rz.uni-duesseldorf.de/~tolj, Cygwin tools (MySQL +Apache + PHP under Win32}
@item
@uref{http://dbasecentral.com/, dbasecentral.com; Development and distribution of powerful and easy-to-use database applications and systems.}
@item
@uref{http://www.Tek-Tips.com, Tek-Tips Forums} Tek-Tips Forums are 800+
independent peer-to-peer non-commercial support forums for Computer
Professionals.  Features include automatic e-mail notification of
responses, a links library, and member confidentiality guaranteed.
@end itemize

There are also many web pages that use
@strong{MySQL}. @xref{Users}. Send any additions to this list to
@email{webmaster@@mysql.com}.

@cindex Reporting errors
@cindex @strong{MySQL} mailing lists
@node Questions, Licensing and Support, Introduction, Top
@chapter @strong{MySQL} mailing lists and how to ask questions or report errors (bugs)

@menu
* Mailing-list::                The @strong{MySQL} mailing lists
* Asking questions::            Asking questions or reporting bugs
* Bug reports::                 How to report bugs or problems
* Answering questions::         Guidelines for answering questions on the mailing list
@end menu

@node Mailing-list, Asking questions, Questions, Questions
@section The @strong{MySQL} mailing lists

To subscribe to the main @strong{MySQL} mailing list, send a message to the
electronic mail address @email{mysql-subscribe@@lists.mysql.com}.

To unsubscribe from the main @strong{MySQL} mailing list, send a message to
the electronic mail address @email{mysql-unsubscribe@@lists.mysql.com}.

Only the address to which you send your messages is significant.  The
subject line and the body of the message are ignored.

@c the last two addresses in this paragraph are NOT @email because they
@c shouldn't be live links.
If your reply address is not valid, you can specify your address explicitly.
Adding a hyphen to the subscribe or unsubscribe command word, followed by
your address with the @samp{@@} character in your address replaced by a
@samp{=}.  For example, to subscribe @code{john@@host.domain}, send a message
to @code{mysql-subscribe-john=host.domain@@lists.mysql.com}.

Mail to @email{mysql-subscribe@@lists.mysql.com} or
@email{mysql-unsubscribe@@lists.mysql.com} is handled automatically by the
ezmlm mailing list processor.  Information about ezmlm is available at
@uref{http://www.ezmlm.org,the ezmlm Website}.

To post a message to the list itself, send your message to
@code{mysql@@lists.mysql.com}.  However, please @emph{do not} send mail about
subscribing or unsubscribing to @email{mysql@@lists.mysql.com}, since any
mail sent to that address is distributed automatically to thousands of other
users.

Your local site may have many subscribers to @email{mysql@@lists.mysql.com}.
If so, it may have a local mailing list, so that messages sent from
@code{lists.mysql.com} to your site are propagated to the local list. In such
cases, please contact your system administrator to be added to or dropped
from the local @strong{MySQL} list.

The following @strong{MySQL} mailing lists exist:

@table @code
@item announce
This is for announcement of new versions of @strong{MySQL} and related
programs. This is a low volume list that we think all @strong{MySQL}
users should be on.

@item mysql
The main list for general @strong{MySQL} discussion. Please note that some
topics are better discussed on the more-specialized lists. If you post to the
wrong list, you may not get an answer!

@item mysql-digest
The @code{mysql} list in digest form. That means you get all individual
messages, sent as one large mail message once a day.

@item java
Discussion about @strong{MySQL} and Java. Mostly about the JDBC drivers.

@item java-digest
A digest version of the @code{java} list.

@item win32
All things concerning @strong{MySQL} on Microsoft operating systems such as
Windows NT.

@item win32-digest
A digest version of the @code{win32} list.

@item myodbc
All things concerning connecting to @strong{MySQL} with ODBC.

@item myodbc-digest
A digest version of the @code{myodbc} list.

@item msql-mysql-modules
A list about the Perl support in @strong{MySQL}.

@item msql-mysql-modules-digest
A digest version of the @code{msql-mysql-modules} list.

@item developer
A list for people who work on the @strong{MySQL} code.

@item developer-digest
A digest version of the @code{developer} list.
@end table

You subscribe or unsubscribe to all lists in the same way as described
above.  In your subscribe or unsubscribe message, just put the appropriate
mailing list name rather than @code{mysql}.  For example, to subscribe to or
unsubscribe from the @code{myodbc} list, send a message to
@email{myodbc-subscribe@@lists.mysql.com} or
@email{myodbc-unsubscribe@@lists.mysql.com}.

@cindex Net etiquette
@node Asking questions, Bug reports, Mailing-list, Questions
@section Asking questions or reporting bugs

Before posting a bug report or question, please do the following:

@itemize @bullet
@item
Start by searching the @strong{MySQL} online manual at:

@example
@uref{http://www.mysql.com/Manual_chapter/manual_toc.html}
@end example

We try to keep the manual up to date by
updating it frequently with solutions to newly found problems!

@item
Search the @strong{MySQL} mailing list archives:

@example
@uref{http://www.mysql.com/doc.html}
@end example

@item
You can also use @uref{http://www.mysql.com/search.html} to search all the
web pages (including the manual) that are located at
@uref{http://www.mysql.com/}.
@end itemize

If you can't find an answer in the manual or the archives, check with your
local @strong{MySQL} expert. If you still can't find an answer to your
question, go ahead and read the next section about how to send mail to
@email{mysql@@lists.mysql.com}.

@cindex Bug reports
@cindex Reporting bugs
@node Bug reports, Answering questions, Asking questions, Questions
@section How to report bugs or problems

Writing a good bug report takes patience, but doing it right the first time
saves time for us and for you. This section will help you write your report
correctly so that you don't waste your time doing things that may not help us
much or at all.

We encourage everyone to use the @code{mysqlbug} script to generate a bug
report (or a report about any problem), if possible.  @code{mysqlbug} can be
found in the @file{scripts} directory in the source distribution, or, for a
binary distribution, in the @file{bin} directory under your @strong{MySQL}
installation directory.  If you are unable to use @code{mysqlbug}, you should
still include all the necessary information listed in this section.

The @code{mysqlbug} script helps you generate a report by determining much
of the following information automatically, but if something important is
missing, please include it with your message! Please read this section
carefully and make sure that all the information described here is included
in your report.

Remember that it is possible to respond to a message containing too much
information, but not to one containing too little.  Often people omit facts
because they think they know the cause of a problem and assume that some
details don't matter.  A good principle is: if you are in doubt about stating
something, state it!  It is a thousand times faster and less troublesome to
write a couple of lines more in your report than to be forced to ask again
and wait for the answer because you didn't include enough information the
first time.

The most common errors are that people don't indicate the version number of
the @strong{MySQL} distribution they are using, or don't indicate what
platform they have @strong{MySQL} installed on (including the platform
version number).  This is highly relevant information and in 99 cases out of
100 the bug report is useless without it!  Very often we get questions like
``Why doesn't this work for me?''  and then we find that the feature
requested wasn't implemented in that @strong{MySQL} version, or that a bug
described in a report has been fixed already in newer @strong{MySQL}
versions.  Sometimes the error is platform dependent; in such cases, it is
next to impossible to fix anything without knowing the operating system and
the version number of the platform.

Remember also to provide information about your compiler, if it is related to
the problem.  Often people find bugs in compilers and think the problem is
@strong{MySQL} related. Most compilers are under development all the time and
become better version by version, too.  To determine whether or not your
problem depends on your compiler, we need to know what compiler is used.
Note that every compiling problem should be regarded as a bug report and
reported accordingly.

It is most helpful when a good description of the problem is included in the
bug report.  That is, a good example of all the things you did that led to
the problem and the problem itself exactly described.  The best reports are
those that include a full example showing how to reproduce the bug or
problem.

If a program produces an error message, it is very important to include the
message in your report! If we try to search for something from the archives
using programs, it is better that the error message reported exactly matches
the one that the program produces.  (Even the case sensitivity should be
observed!) You should never try to remember what the error message was;
instead, copy and paste the entire message into your report!

Please include the following information in your report:

@itemize @bullet
@item
The version number of the @strong{MySQL} distribution you are using (for
example, @strong{MySQL} 3.22.22). You can find out which version you are
running by executing @code{mysqladmin version}. @code{mysqladmin} can be
found in the @file{bin} directory under your @strong{MySQL} installation
directory.

@item
The manufacturer and model of the machine you are working on.

@item
The operating system name and version. For most operating systems, you can
get this information by executing the Unix command @code{uname -a}.

@item
Sometimes the amount of memory (real and virtual) is relevant.
If in doubt, include these values.

@item
If you are using a source distribution of @strong{MySQL}, the name and
version number of the compiler used is needed.
If you have a binary distribution, the distribution name is needed.

@item
If the problem occurs during compilation, include the exact error
message(s) and also a few lines of context around the offending code in the
file where the error occurred.

@item
If any database table is related to the problem, include the output from
@code{mysqldump --no-data db_name tbl_name1 tbl_name2 ...} This is very easy
to do and is a powerful way to get information about any table in a database
that will help us create a situation matching the one you have.

@item
For speed-related bugs or problems with @code{SELECT} statements, you should
always include the output of @code{EXPLAIN SELECT ...}, and at least the
number of rows that the @code{SELECT} statement produces.  The more
information you give about your situation, the more likely it is that someone
can help you!  For example, the following is an example of a very good bug
report (it should of course be posted with the @code{mysqlbug} script):

Example run under the @code{mysql} command line tool:

@example
mysql> SHOW VARIABLES;
mysql> EXPLAIN SELECT ...
       <output-from-EXPLAIN>
mysql> FLUSH STATUS;
mysql> SELECT ...
       <A short version of the output from SELECT,
       including the time taken to run the query>
mysql> SHOW STATUS;
       <output from SHOW STATUS>
@end example

@item
If a bug or problem occurs while running @strong{MySQL}, try to provide an
input script that will reproduce the anomaly. This script should include any
necessary source files. The more closely the script can reproduce your
situation, the better.

If you can't provide a script, you should at least include the output
from @code{mysqladmin variables extended-status processlist} in your mail to
provide some information of how your system is performing!

@item
If you think that @strong{MySQL} produces a strange result from a query,
include not only the result, but also your opinion of what the result
should be and an account describing the basis for your opinion.

@item
When giving an example of the problem, it's better to use the variable names,
table names, etc., that exist in your actual situation than to come up with
new names. The problem could be related to the name of a variable, table,
etc.!  These cases are rare, perhaps, but it is better to be safe than
sorry.  After all, it should be easier for you to provide an example that
uses your actual situation and it is by all means better for us.  In case you
have data you don't want to show to others, you can use @code{ftp} to
transfer it to @uref{ftp://www.mysql.com/pub/mysql/secret/}.  If the data are
really top secret and you don't want to show them even to us, then go ahead
and provide an example using other names, but please regard this as the last
choice.

@item
Include all the options given to the relevant programs, if possible.  For
example, indicate the options that you use when you start the @code{mysqld}
daemon and that you use to run any @strong{MySQL} client programs.  The
options to programs like @code{mysqld} and @code{mysql}, and to the
@code{configure} script are often keys to answers and very relevant!  It is
never a bad idea to include them anyway!  If you use any modules, such as
Perl or PHP, please include the version number(s) of those as well.

@item
If you can't produce a test case in a few rows, or if the test table
is too big to be mailed to the mailing list (more than 10 rows), you should
dump your tables using @code{mysqldump} and create a @file{README} file
that describes your problem.

Create a compressed archive of your files using
@code{tar} and @code{gzip} or @code{zip}, and use @code{ftp}
to transfer the archive to @uref{ftp://www.mysql.com/pub/mysql/secret/}.
Then send a short description of the problem to
@email{mysql@@lists.mysql.com}.

@item
If your question is related to the privilege system, please include the
output of @code{mysqlaccess}, the output of @code{mysqladmin reload} and all
the error messages you get when trying to connect!  When you test your
privileges, you should first run @code{mysqlaccess}. After this, execute
@code{mysqladmin reload version}, and last you should try to connect with the
program that gives you trouble.  @code{mysqlaccess} can be found in the
@file{bin} directory under your @strong{MySQL} installation directory.

@item
If you have a patch for a bug, that is good.  But don't assume the patch is
all we need or that we will use it even if you don't provide some necessary
information such as test cases showing the bug that your patch fixes.  We
might find problems with your patch or we might not understand it at all; if
so, we can't use it.

If we can't verify exactly what the patch is meant for, we won't use it.
Test cases will help us here.  Show that the patch will handle all the
situations that may occur. If we find a borderline case (even a rare one)
where the patch won't work, the patch may be useless.

@item
Guesses about what the bug is, why it occurs, or what it depends on,
are usually wrong. Even we can't guess such things without first
using a debugger to determine the real cause of a bug.

@item
Indicate in your mail message that you have checked the reference manual
and mail archive so others know that you have tried to solve your
problem yourself.

@item
If you get a @code{parse error}, please check your syntax closely! If you
can't find something wrong with it, it's extremely likely that your current
version of @strong{MySQL} doesn't support the query you are using.  If you
are using the current version and the manual at
@uref{http://www.mysql.com/doc.html} doesn't cover the syntax you are using,
@strong{MySQL} doesn't support your query.  In this case, your only options
are to implement the syntax yourself or email @email{mysql-support@@mysql.com}
and ask for an offer to implement it!

If the manual covers the syntax you are using, but you have an older version
of @strong{MySQL}, you should check the @strong{MySQL} change history to see
when the syntax was implemented.  @xref{News}.  In this case, you have the
option of upgrading to a newer version of @strong{MySQL}.

@item
If you have a problem such that your data appears corrupt or you get
errors when you access some particular table, you should first check and then
try repairing your tables with @code{isamchk}.
@xref{Maintenance}.

@item
If you often get corrupted tables you should try to find out when and
why this happens!  In this case, the
@file{mysql-data-directory/'hostname'.err} file may contain some
information about what happened.  Please include any relevant
information from this file in your bug report!  Normally @code{mysqld} should
@strong{NEVER} crash a table if nothing killed it in the middle of an
update!  If you can find the source of why @code{mysqld} dies, it's much
easier for us to provide you with a fix for the problem!

@item
If possible, download the most recent version of @strong{MySQL} and check
whether or not it solves your problem.  All versions of @strong{MySQL} are
thoroughly tested and should work without problems!  We believe in making
everything as backward compatible as possible and you should be able to
switch @strong{MySQL} versions in minutes!  @xref{Which version}.
@end itemize

If you are a support customer, please cross-post the bug report to
@email{mysql-support@@mysql.com} for higher priority treatment, as well as to
the appropriate mailing list to see if someone else has experienced (and
perhaps solved) the problem.

For information on reporting bugs in @strong{MyODBC}, see @ref{ODBC
Problems}.

For solutions to some common problems, see @xref{Problems}.

When answers are sent to you individually and not to the mailing list,
it is considered good etiquette to summarize the answers and send the
summary to the mailing list so that others may have the benefit of
responses you received that helped you solve your problem!

@cindex Net etiquette
@node Answering questions,  , Bug reports, Questions
@section Guidelines for answering questions on the mailing list

If you consider your answer to have broad interest, you may want to post it
to the mailing list instead of replying directly to the individual who
asked.  Try to make your answer general enough that people other than the
original poster may benefit from it.  When you post to the list, please make
sure that your answer is not a duplication of a previous answer.

Try to summarize the essential part of the question in your reply; don't feel
obliged to quote the entire original message.

Please don't post mail messages from your browser with HTML mode turned on!
Many users doesn't read mail with a browser!

@cindex Licensing terms
@cindex Support terms
@node Licensing and Support, Installing, Questions, Top
@chapter @strong{MySQL} licensing and support

@menu
* Licensing policy::            @strong{MySQL} licensing policy
* Copyright::                   Copyrights used by @strong{MySQL}
* Commercial use::              Distributing @strong{MySQL} commercially
* Licensing examples::          Example licensing situations
* Cost::                        @strong{MySQL} licensing and support costs
* Support::                     Types of commercial support
@end menu

This chapter describes @strong{MySQL} licensing and support arrangements,
including:

@itemize @bullet
@item
Our licensing policies for non-Microsoft and Microsoft operating systems

@item
The copyrights under which @strong{MySQL} is distributed
(@pxref{Copyright})

@item
Sample situations illustrating when a license is required
(@pxref{Licensing examples})

@item
Licensing and support costs (@pxref{Cost}), and
support benefits (@pxref{Support})
@end itemize

@cindex Licensing policy
@node Licensing policy, Copyright, Licensing and Support, Licensing and Support
@section @strong{MySQL} licensing policy

The formal terms of the license for non-Microsoft operating systems such as
Unix or OS/2 are specified in @ref{Public license}.  Basically, our licensing
policy is as follows:

@itemize @bullet
@item
For normal internal use, @strong{MySQL} generally costs nothing.  You do not
have to pay us if you do not want to.

@item
A license is required if:

@itemize @minus
@item
You sell the @strong{MySQL} server directly or as a part of another product
or service

@item
You charge for installing and maintaining a @strong{MySQL} server at some
client site

@item

You include @strong{MySQL} in a distribution that is non redistributable
and you charge for some part of that distribution
@end itemize

@item
For circumstances under which a @strong{MySQL} license is required, you need
a license per machine that runs the @code{mysqld} server.  However, a
multiple-CPU machine counts as a single machine, and there is no restriction
on the number of @strong{MySQL} servers that run on one machine, or on the
number of clients concurrently connected to a server running on that
machine!

@item
You do not need a license to include client code in commercial programs.  The
client access part of @strong{MySQL} is in the public domain. The
@code{mysql} command line client includes code from the @code{readline}
library that is under the GNU Public License.

@item
@cindex @code{pack_isam}
For customers who have purchased 10 licenses or a high enough level of
support, we provide additional functionality.  Currently, this means we
provide the @code{pack_isam} utility for creating fast compressed read-only
databases.  (The server includes support for reading such databases but not
the packing tool used to create them.)  If support agreements generate
sufficient revenue, we will probably release this tool under the same
license as the @strong{MySQL} server.

@item
If your use of @strong{MySQL} does not require a license, but you like
@strong{MySQL} and want to encourage further development, you are certainly
welcome to purchase a license anyway.

@item
If you use @strong{MySQL} in a commercial context such that
you profit by its use, we ask that you further the development of
@strong{MySQL} by purchasing some level of support.  We feel that if
@strong{MySQL} helps your business, it is reasonable to ask that you help
@strong{MySQL}.  (Otherwise, if you ask us support questions, you are not
only using for free something into which we've put a lot a work, you're
asking us to provide free support, too.)
@end itemize

For use under Microsoft operating systems (Win95/Win98/WinNT), you need a
@strong{MySQL} license after a trial period of 30 days, with the exception
that licenses may be obtained upon request at no cost for educational
use or for university- or government-sponsored research settings.  @xref{Win
license}. A shareware version of @strong{MySQL}-Win32 that you can try before
buying is available at @uref{http://www.mysql.com/mysql_w32.htmy}.  After
you have paid, you will get a password that will enable you to access
the newest @strong{MySQL}-Win32 version.

If you have any questions as to whether or not a license is required for your
particular use of @strong{MySQL}, please contact us.
@xref{Contact information}.

If you require a @strong{MySQL} license, the easiest way to pay for it is to
use the license form at TcX's secure server at
@url{https://www.tcx.se/license.htmy}.  Other forms of payment are discussed
in @ref{Payment information}.

@cindex Copyright
@node Copyright, Commercial use, Licensing policy, Licensing and Support
@section Copyrights used by @strong{MySQL}

@menu
* Copyright changes::           Possible future copyright changes
@end menu

There are several different copyrights on the @strong{MySQL} distribution:

@enumerate
@item
The @strong{MySQL}-specific source needed to build the @code{mysqlclient}
library and programs in the @file{client} directory is in the public
domain. Each file that is in the public domain has a header which clearly
states so. This includes everything in the @file{client} directory and some parts of
the @code{mysys}, @code{mystring} and @code{dbug} libraries.

@item
Some small parts of the source (GNU @code{getopt}) are covered by the
``GNU LIBRARY LIBRARY GENERAL PUBLIC LICENSE''.  See the
@file{mysys/COPYING.LIB} file.

@item
Some small parts of the source (GNU @code{readline}) are covered by the
``GNU GENERAL PUBLIC LICENSE''. See the @file{readline/COPYING} file.

@item
Some parts of the source (the @code{regexp} library) are covered by a Berkeley
style copyright.

@item
The other source needed for the @strong{MySQL} server on non-Microsoft
platforms is covered by the ``MySQL FREE PUBLIC LICENSE'', which is based on
the ``Aladdin FREE PUBLIC LICENSE.'' @xref{Public license}. When running
@strong{MySQL} on any Microsoft operating system, other licensing applies.
@end enumerate

The following points set forth the philosophy behind our copyright policy:

@itemize @bullet
@item
The SQL client library should be totally free so that it can be included in
commercial products without limitations.

@item
People who want free access to the software into which we have put a lot of
work can have it, so long as they do not try to make money directly by
distributing it for profit.

@item
People who want the right to keep their own software proprietary, but also
want the value from our work, can pay for the privilege.

@item
That means normal in-house use is FREE. But if you use @strong{MySQL} for
something important to you, you may want to help further its development by
purchasing a license or a support contract.  @xref{Support}.
@end itemize

@node Copyright changes,  , Copyright, Copyright
@subsection Possible future copyright changes

We may choose to distribute older versions of @strong{MySQL} with the GPL in
the future. However, these versions will be identified as @strong{GNU MySQL}.
Also, all copyright notices in the relevant files will be changed to the
GPL.

@node Commercial use, Licensing examples, Copyright, Licensing and Support
@section Distributing @strong{MySQL} commercially

This section is a clarification of the license terms that are set forth in
the ``MySQL FREE PUBLIC LICENSE'' (FPL).  @xref{Public license}.

@strong{MySQL} may be @strong{used} freely, including by commercial
entities for evaluation or unsupported internal use. However,
@strong{distribution} for commercial purposes of @strong{MySQL}, or
anything containing or derived from @strong{MySQL} in whole or in part,
requires a written commercial license from TcX AB, the sole entity
authorized to grant such licenses.

You may not include @strong{MySQL} ``free'' in a package containing
anything for which a charge is being made, except as noted below.

The intent of the exception provided in the second clause of the license is
to allow commercial organizations operating an FTP server or a bulletin board
to distribute @strong{MySQL} freely from it, provided that:

@enumerate
@item
The organization complies with the other provisions of the FPL, which
include among other things a requirement to distribute the full source
code of @strong{MySQL} and of any derived work, and to distribute the
FPL itself along with @strong{MySQL};

@item
The only charge for downloading @strong{MySQL} is a charge based on the
distribution service and not one based on the content of the information
being retrieved (i.e., the charge would be the same for retrieving a
random collection of bits of the same size);

@item
The server or BBS is accessible to the general public, i.e., the phone
number or IP address is not kept secret, and anyone may obtain access to
the information (possibly by paying a subscription or access fee that is
not dependent on or related to purchasing anything else).
@end enumerate

If you want to distribute software in a commercial context that incorporates
@strong{MySQL} and you do @strong{not} want to meet these conditions, you
should contact TcX AB to find out about commercial licensing, which involves
a payment. The only ways you legally can distribute @strong{MySQL} or
anything containing @strong{MySQL} are by distributing @strong{MySQL} under
the requirements of the FPL, or by getting a commercial license from TcX AB.

@node Licensing examples, Cost, Commercial use, Licensing and Support
@section Example licensing situations

@menu
* Products that use MySQL::     Selling products that use @strong{MySQL}
* MySQL services::              Selling @strong{MySQL}-related services
* ISP::                         ISP @strong{MySQL} services
* Web server::                  Running a web server using @strong{MySQL}.
@end menu

This section describes some situations illustrating whether or not you must
license the @strong{MySQL} server.  Generally these examples involve
providing @strong{MySQL} as part of a product or service that you are selling
to a customer, or requiring that @strong{MySQL} be used in conjunction with
your product.  In such cases, it is your responsibility to obtain a license
for the customer if one is necessary.  (This requirement is waived if your
customer already has a @strong{MySQL} license.  But the seller must send
customer information and the license number to TcX, and the license must be a
full license, not an OEM license.)

Note that a single @strong{MySQL} license covers any number of
CPUs/users/customers/@code{mysqld} servers on a machine!

@node Products that use MySQL, MySQL services, Licensing examples, Licensing examples
@subsection Selling products that use @strong{MySQL}

To determine whether or not you need a @strong{MySQL} license when selling
your application, you should ask whether the proper functioning of your
application is contingent on the use of @strong{MySQL} and whether you
include @strong{MySQL} with your product.  There are several cases to
consider:

@itemize @bullet
@item
Does your application require @strong{MySQL} to function properly?

If your product requires @strong{MySQL}, you need a license for any machine
that runs the @code{mysqld} server.  For example, if you've designed your
application around @strong{MySQL}, then you've really made a commercial
product that requires the engine, so you need a license.

If your application does not require @strong{MySQL}, you need not obtain a
license.  For example, if @strong{MySQL} just added some new optional
features to your product (such as adding logging to a database if
@strong{MySQL} is used rather than logging to a text file), it should fall
within normal use, and a license would not be required.

In other words, you need a license if you sell a product designed
specifically for use with @strong{MySQL} or that requires the @strong{MySQL}
server to function at all.  This is true whether or not you provide
@strong{MySQL} for your client as part of your product distribution.

It also depends on what you're doing for the client.  Do you plan to provide
your client with detailed instructions on installing @strong{MySQL} with your
software?  Then your product may be contingent on the use of @strong{MySQL};
if so, you need to buy a license.  If you are simply tying into a database
that you expect already to have been installed by the time your software is
purchased, then you probably don't need a license.

@item
Do you include @strong{MySQL} in a distribution and charge for that
distribution?

If you include @strong{MySQL} with a distribution that you sell to customers,
you will need a license for any machine that runs the @code{mysqld} server,
because in this case you are selling a system that includes @strong{MySQL}.

This is true whether the use of @strong{MySQL} with your product
is required or optional.

@item
Do you neither require for your product nor include @strong{MySQL} with it?

Suppose you want to sell a product that is designed generally to use ``some
database'' and that can be configured to use any of several supported
alternative database systems (@strong{MySQL}, PostgreSQL, or something
else).  That is, your product does not not require @strong{MySQL}, but can
support any database with a base level of functionality, and you don't rely
on anything that only @strong{MySQL} supports.  Does one of you owe us money
if your customer actually does choose to use @strong{MySQL}?

In this case, if you don't provide, obtain or set up @strong{MySQL} for the
customer should the customer decide to use it, neither of you need a
license.  If you do perform that service, see @ref{MySQL services, ,
@strong{MySQL} services}.
@end itemize

@node MySQL services, ISP, Products that use MySQL, Licensing examples
@subsection Selling @strong{MySQL}-related services

If you perform @strong{MySQL} installation on a client's machine and any
money changes hands for the service (directly or indirectly), then you must
buy a @strong{MySQL} license.

If you sell an application for which @strong{MySQL} is not strictly required
but can be used, a license may be indicated, depending on how @strong{MySQL}
is set up.  Suppose your product neither requires @strong{MySQL} nor includes
it in your product distribution, but can be configured to use @strong{MySQL}
for those customers who so desire.  (This would be the case, for example, if
your product can use any of a number of database engines.)

If the customer obtains and installs @strong{MySQL}, no license is needed.
If you perform that service for your customer, then a license is needed
because then you are selling a service that includes @strong{MySQL}.

@node ISP, Web server, MySQL services, Licensing examples
@subsection ISP @strong{MySQL} services

Internet Service Providers (ISPs) often host @strong{MySQL} servers for
their customers.

If you are an ISP that allows customers to install and administer
@strong{MySQL} for themselves on your machine with no assistance from you,
neither you nor your customer need a @strong{MySQL} license.

If you charge for @strong{MySQL} installation and administrative support as
part of your customer service, then you need a license because you are selling
a service that includes @strong{MySQL}.

@node Web server,  , ISP, Licensing examples
@subsection Running a web server using @strong{MySQL}

If you use @strong{MySQL} in conjunction with a web server, you don't have to
pay for a license.

This is true even if you run a commercial web server that uses
@strong{MySQL}, since you are not selling @strong{MySQL} itself.  However, in
this case we would like you to purchase @strong{MySQL} support, because
@strong{MySQL} is helping your enterprise.

@cindex Costs, licensing and support
@cindex Licensing costs
@cindex Support costs
@node Cost, Support, Licensing examples, Licensing and Support
@section @strong{MySQL} licensing and support costs

@menu
* Payment information::         Payment information
* Contact information::         Contact information
@end menu

Our current license prices are shown below. All prices are in US
Dollars. If you pay by credit card, the currency is EURO (European Union Euro)
so the prices will differ slightly.

@multitable @columnfractions .25 .2 .3
@item @strong{Number of licenses} @tab @strong{Price per copy} @tab @strong{Total}
@item 1                  @tab US $200 @tab US $200
@item 10 pack            @tab US $150 @tab US $1500
@item 50 pack            @tab US $120 @tab US $6000
@end multitable

For high volume (OEM) purchases, the following prices apply:

@multitable @columnfractions .25 .2 .3 .25
@item @strong{Number of licenses}  @tab @strong{Price per copy} @tab @strong{Minimum at one time}        @tab @strong{Minimum payment}
@item 100-999   @tab US $40        @tab 100                     @tab US $4000
@item 1000-2499 @tab US $25        @tab 200                     @tab US $5000
@item 2500-4999 @tab US $20        @tab 400                     @tab US $8000
@end multitable

For OEM purchases, you must act as the middle-man for eventual problems
or extension requests from your users. We also require that OEM
customers have at least an extended email support contract.

If you have a low-margin high-volume product, you can always talk to us
about other terms (for example, a percent of the sale price). If you do,
please be informative about your product, pricing, market and any other
information that may be relevant.

@cindex @code{pack_isam}
After buying 10 @strong{MySQL} licenses, you will get a personal copy of
the @code{pack_isam} utility.  You are not allowed to redistribute this
utility but you can distribute tables packed with it.

A full-price license is not a support agreement and includes very minimal
support. This means that we try to answer any relevant question. If the
answer is in the documentation, we will direct you to the appropriate
section. If you have not purchased a license or support, we probably will not
answer at all.

If you discover what we consider a real bug, we are likely to fix it in
any case. But if you pay for support we will notify you about the fix
status instead of just fixing it in a later release.

More comprehensive support is sold separately.  Descriptions of what each
level of support includes are given in @ref{Support}.  Costs for the various
types of commercial support are shown below.  Support level prices are in
EURO (European Union Euro). One EURO is about 1.17 USD.

@multitable @columnfractions .3 .3
@item @strong{Type of support} @tab @strong{Cost per year}
@item Basic email support      @tab EURO 170
@item Extended email support   @tab EURO 1000
@item Login support            @tab EURO 2000
@item Extended login support   @tab EURO 5000
@end multitable

You may upgrade from any
lower level of support to a higher level of support for the difference
between the prices of the two support levels.

@cindex Payment information
@node Payment information, Contact information, Cost, Cost
@subsection Payment information

Currently we can take SWIFT payments, cheques or credit cards.

Payment should be made to:
@example
Postgirot Bank AB
105 06 STOCKHOLM, SWEDEN

T.C.X DataKonsult AB
BOX 6434
11382 STOCKHOLM, SWEDEN

SWIFT address: PGSI SESS
Account number: 96 77 06 - 3
@end example

Specify: license and/or support and your name and email address.

In Europe and Japan you can use EuroGiro (that should be less expensive) to the
same account.

If you want to pay by cheque, make it payable to ``Monty Program KB'' and
mail it to the address below:

@example
T.C.X DataKonsult AB
BOX 6434
11382 STOCKHOLM, SWEDEN
@end example

If you want to pay by credit card over the Internet, you can use
@uref{https://www.tcx.se/license.htmy, TcX's secure license form}.

You can also print a copy of the license form, fill it in and send it by fax
to:

+46-8-729 69 05

If you want us to bill you, you can use the license form and write ``bill
us'' in the comment field.  You can also mail a message to
@email{mysql-c@@mysql.com} (@strong{not} @email{mysql@@lists.mysql.com}!)
with your company information and ask us to bill you.

@cindex Contact information
@node Contact information,  , Payment information, Cost
@subsection Contact information

For commercial licensing, or if you have any questions about any of the
information in this section, please contact:

@example
David Axmark
Detron HB
Kungsgatan 65 B
753 21 UPPSALA
SWEDEN
Voice Phone +46-18-10 22 80     (Swedish and English spoken)
Fax +46-8-729 69 05             (Email *much* preferred)
E-Mail: mysql-licensing@@mysql.com
@end example

@cindex Support, types
@cindex Types of support
@node Support,  , Cost, Licensing and Support
@section Types of commercial support

@menu
* Basic email support::         Basic email support
* Extended email support::      Extended email support
* Login support::               Login support
* Extended login support::      Extended login support
@end menu

@node Basic email support, Extended email support, Support, Support
@subsection Basic email support

Basic email support is a very inexpensive support option and should be
thought of more as a way to support our development of @strong{MySQL} than as
a real support option.

At this support level, the @strong{MySQL} mailing lists are the preferred
means of communication.  Questions normally should be mailed to the primary
mailing list (@email{mysql@@lists.mysql.com}) or one of the other regular
lists (for example, @email{mysql-win32@@lists.mysql.com} for Windows-related
@strong{MySQL} questions), as someone else already may have experienced and
solved the problem you have.  @xref{Asking questions}.

However, by purchasing basic email support, you also have access to the
support address @email{mysql-support@@mysql.com}, which is not available as part
of the minimal support that you get by purchasing a @strong{MySQL} license.
This means that for especially critical questions, you can cross-post your
message to @email{mysql-support@@mysql.com}.  (If the message contains sensitive
data, you should post only to @email{mysql-support@@mysql.com}.)  Whenever you
send a message to @email{mysql-support@@mysql.com}, always remember to include
your registration number and expiration date to ensure a quick response.

Basic email support includes the following types of service:

@itemize @bullet
@item
If your question is already answered in the manual, we will inform you of the
correct section in which you can find the answer.  If the answer is not in
the manual, we will point you in the right direction to solve your problem.

@item
We guarantee a timely answer for your email messages.  We can't guarantee
that we can solve any problem, but at least you will receive an answer if we
can contact you by email.

@item
We will help with unexpected problems when you install @strong{MySQL} from a
binary distribution on supported platforms.  This level of support does not
cover installing @strong{MySQL} from a source distribution.  ``Supported''
platforms are those for which @strong{MySQL} is known to work.
@xref{Which OS}.

@item
We will help you with bugs and missing features. Any bugs that are found are
fixed for the next @strong{MySQL} release. If the bug is critical for
you, we will mail you a patch for it as soon the bug is fixed.  Critical
bugs always have the highest priority for us, to ensure that they are
fixed as soon as possible.

@item
Your suggestions for the further development of @strong{MySQL} will be
taken into consideration. By taking email support you have already
helped the further development of @strong{MySQL}. If you want to have
more input, upgrade to a higher level of support.

@item
If you want us to help optimize your system, you must upgrade to a
higher level of support.
@end itemize

@node Extended email support, Login support, Basic email support, Support
@subsection Extended email support

Extended email support includes everything in basic email support with
these additions:

@itemize @bullet
@item
Your email will be dealt with before mail from basic email support users and
non-registered users.

@item
Your suggestions for the further development of @strong{MySQL} will
receive strong consideration. Simple extensions that suit the basic
goals of @strong{MySQL} are implemented in a matter of days. By taking
extended email support you have already helped the further development
of @strong{MySQL}.

@item
@cindex @code{pack_isam}
We include a binary version of the @code{pack_isam} packing tool for creating
fast compressed read-only databases (it does not support @code{BLOB} or
@code{TEXT} types yet). The current server includes support for reading such
databases but not the packing tool used to create them.

@item
Typical questions that are covered by extended email support are:

@itemize @minus
@item
We will answer and (within reason) solve questions that relate to possible
bugs in @strong{MySQL}.  As soon as the bug is found and corrected, we
will mail a patch for it.

@item
We will help with unexpected problems when you install @strong{MySQL} from a
source or binary distribution on supported platforms.

@item
We will answer questions about missing features and offer hints how to work
around them.

@item
We will provide hints on optimizing @code{mysqld} for your situation.
@end itemize

@item
You are allowed to influence the priority of items on the @strong{MySQL}
TODO. This will ensure that the features you really need will be implemented
sooner than they might be otherwise.
@end itemize

@node Login support, Extended login support, Extended email support, Support
@subsection Login support

Login support includes everything in extended email support with
these additions:

@itemize @bullet
@item
Your email will be dealt with even before mail from extended email
support users.

@item
Your suggestions for the further development of @strong{MySQL} will
be taken into very high consideration.  Realistic extensions that can be
implemented in a couple of hours and that suit the basic goals of
@strong{MySQL} will be implemented as soon as possible.

@item
If you have a very specific problem, we can try to log in on your system
to solve the problem ``in place.''

@item
Like any database vendor, we can't guarantee that we can rescue any data from
crashed tables, but if the worst happens we will help you rescue as much as
possible. @strong{MySQL} has proven itself very reliable, but anything is
possible due to circumstances beyond our control (for example, if your system
crashes or someone kills the server by executing a @code{kill -9} command).

@item
We will provide hints on optimizing your system and your queries.

@item
You are allowed to call a @strong{MySQL} developer (in moderation) and
discuss your @strong{MySQL}-related problems.
@end itemize

@node Extended login support,  , Login support, Support
@subsection Extended login support

Extended login support includes everything in login support with these
additions:

@itemize @bullet
@item
Your email has the highest possible priority.

@item
We will actively examine your system and help you optimize it and your
queries. We may also optimize and/or extend @strong{MySQL} to better
suit your needs.

@item
You may also request special extensions just for you. For example:
@example
mysql> select MY_CALCULATION(col_name1,col_name2) from tbl_name;
@end example

@item
We will provide a binary distribution of all important @strong{MySQL}
releases for your system, as long as we can get an account on a
similar system. In the worst case, we may require access to your system
to be able to create a binary distribution.

@item
If you can provide accommodations and pay for traveler fares, you can even
get a @strong{MySQL} developer to visit you and offer you help with your
troubles. Extended login support entitles you to one personal
encounter per year, but we are as always very flexible towards our customers!
@end itemize

@node Installing, Compatibility, Licensing and Support, Top
@chapter Installing @strong{MySQL}

@menu
* Getting MySQL::               How to get @strong{MySQL}
* Which OS::                    Operating systems supported by @strong{MySQL}
* Which version::               Which @strong{MySQL} version to use
* Many versions::               How and when updates are released
* Installation layouts::        Installation layouts
* Installing binary::           Installing a @strong{MySQL} binary distribution
* Installing source::           Installing a @strong{MySQL} source distribution
* Compilation problems::        Problems compiling?
* MIT-pthreads::                MIT-pthreads notes
* Perl support::                Perl installation comments
* Source install system issues::  System-specific issues
* Win32::                       Win32 notes
* OS/2::                        OS/2 notes
* TcX binaries::                TcX binaries
* Post-installation::           Post-installation setup and testing
* Upgrade::                     Is there anything special to do when upgrading/downgrading @strong{MySQL}?
@end menu

This chapter describes how to obtain and install @strong{MySQL}:

@itemize @bullet
@item
For a list of sites from which you can obtain @strong{MySQL}, see
@ref{Getting MySQL, , Getting @strong{MySQL}}.

@item
To see which platforms are supported, see @ref{Which OS}.

@item
Several versions of
@strong{MySQL} are available, in both binary and source distributions.
To determine which version and type of distribution
you should use, see @ref{Many versions}.

@item
Installation instructions for binary and source distributions are described
in @ref{Installing binary}, and @ref{Installing source}.  Each set of
instructions includes a section on system-specific problems you may run
into.

@item
For post-installation procedures, see @ref{Post-installation}.  These
procedures apply whether you install @strong{MySQL} using a binary or
source distribution.
@end itemize

@cindex Downloading
@cindex @strong{MySQL} version
@cindex Version, latest
@cindex Getting @strong{MySQL}
@node Getting MySQL, Which OS, Installing, Installing
@section How to get @strong{MySQL}

Check the @uref{http://www.mysql.com/, @strong{MySQL} home page} for
information about the current version and for downloading instructions.

However, the Internet connection at TcX is not so fast; we would
@emph{prefer} that you do the actual downloading from one of the mirror sites
listed below.

Please report bad or out of date mirrors to @email{webmaster@@mysql.com}.

@strong{Europe:}

@itemize @bullet
@item
@c EMAIL: sl@iuinfo.tuwien.ac.at (Tony Sprinzl)
@image{Img/austria} Austria [Univ. of Technology/Vienna] @ 
@uref{http://gd.tuwien.ac.at/db/mysql/, WWW}
@uref{ftp://gd.tuwien.ac.at/db/mysql/, FTP}
@item
@c EMAIL: delian@naturella.com (Delian Delchev)
@image{Img/bulgaria} Bulgaria [Naturella] @ 
@uref{ftp://ftp.ntrl.net/pub/mirror/mysql, FTP}
@item
@c EMAIL: mkyed@ake.dk (Michael Kyed)
@image{Img/denmark} Denmark [Ake] @ 
@uref{http://mysql.ake.dk, WWW}
@item
@c EMAIL: mkp@socsci.auc.dk (Martin Kasper Petersen)
@image{Img/denmark} Denmark [SunSITE] @ 
@uref{http://SunSITE.auc.dk/mysql/, WWW}
@uref{ftp://SunSITE.auc.dk/pub/databases/mysql/, FTP}
@item
@c EMAIL: tonu@tradenet.ee (Tőnu Samuel)
@image{Img/estonia} Estonia [Tradenet] @ 
@uref{http://mysql.tradenet.ee, WWW}
@item
@c Changed 990531
@c EMAIL: Steeve.Devergne@minet.net (Steeve Devergne)
@image{Img/france} France [minet] @ 
@uref{http://www.minet.net/devel/mysql/, WWW}
@item
@c EMAIL: Jaakko.Hyvatti@eunet.fi
@image{Img/finland} Finland [EUnet] @
@uref{http://mysql.eunet.fi/, WWW}
@item
@c Added 981208
@c EMAIL: noel@uni-bonn.de (Noel Koethe)
@image{Img/germany} Germany [Bonn University, Bonn] @ 
@uref{http://www.wipol.uni-bonn.de/MySQL//, WWW}
@uref{ftp://ftp.wipol.uni-bonn.de/pub/mirror/MySQL/, FTP}
@item
@c EMAIL: th@rz.fh-wolfenbuettel.de (Thorsten Ludewig)
@image{Img/germany} Germany [Wolfenbuettel] @ 
@uref{http://www.fh-wolfenbuettel.de/ftp/pub/database/mysql/, WWW}
@uref{ftp://ftp.fh-wolfenbuettel.de/pub/database/mysql/, FTP}
@item
@c Ok 980114. Removed 981208 (down > 3 days) ok 981214
@c EMAIL: straub@gks.de (Hans-Peter Straub)
@image{Img/germany} Germany [Staufen] @ 
@uref{http://mysql.staufen.de/, WWW}
@item
@c Added 981208
@c EMAIL: christias@noc.ntua.gr (Panagiotis Christias)
@image{Img/greece} Greece [NTUA, Athens] @ 
@uref{http://www.ntua.gr/mysql/, WWW}
@uref{ftp://ftp.ntua.gr/pub/databases/mysql/, FTP}
@item
@c EMAIL: torlasz@xenia.sote.hu (Laszlo L. Tornoc)
@image{Img/hungary} Hungary [Xenia] @ 
@uref{http://xenia.sote.hu/ftp/mirrors/www.mysql.com/, WWW}
@uref{ftp://xenia.sote.hu/pub/mirrors/www.mysql.com/,FTP}
@item
@c EMAIL: bourbon@netvision.net.il (Zeev Suraski)
@image{Img/israel} Israel [Netvision] @ 
@uref{http://mysql.netvision.net.il/, WWW}
@c @item
@c Not working 99.03.06
@c EMAIL: maruzz@matrice.it (Giovanni Maruzzelli)
@c @image{Img/italy} Italy [Matrice] @ 
@c @uref{http://www.matrice.it/risorse/mysql/, WWW}
@item
@c EMAIL: irena@yacc.it
@image{Img/italy} Italy [Teta Srl] @ 
@uref{http://www.teta.it/mysql/, WWW}
@item
@c EMAIL: W.Sylwestrzak@icm.edu.pl (Wojtek Sylwestrzak)
@c mirroring nightly at 05:25
@image{Img/poland} Poland [Sunsite] @ 
@uref{http://sunsite.icm.edu.pl/mysql/, WWW}
@uref{ftp://sunsite.icm.edu.pl/pub/unix/mysql/, FTP}
@c @item
@c EMAIL: melo@co.telenet.pt (Pedro Melo)
@c Temp out of service (email from Pedro)
@c @image{Img/portugal} Portugal [Telenet] @ 
@c @uref{http://mysql.telenet.pt, WWW}
@item
@c EMAIL: Equipa de suporte do Leirianet <support@leirianet.pt>
@image{Img/portugal} Portugal [lerianet] @ 
@uref{http://mysql.leirianet.pt, WWW}
@uref{ftp://ftp.leirianet.pt/pub/mysql/,FTP}
@item
@c EMAIL: kuzmin@dn.ru (Roma Kuzmin)
@image{Img/russia} Russia [DirectNet] @ 
@uref{http://mysql.directnet.ru, WWW}
@c @item
@c down 990113
@c EMAIL: nikkic@cityline.ru (Nikki Chumakov)
@c @image{Img/russia} Russia [Cityline] @ 
@c @uref{ftp://mysql.cityline.ru/pub/mysql, FTP}
@c @uref{http://mysql.cityline.ru, WWW}
@c EMAIL: bar@izhcom.ru (Alexander I Barkov)
@item
@image{Img/russia} Russia [IZHCOM] @ 
@uref{http://mysql.udm.net/, WWW}
@uref{ftp://ftp.izhcom.ru/pub/mysql/,FTP}
@item
@c Added 990507
@c EMAIL: demon@gpad.ac.ru (Dima Sivachenko)
@image{Img/russia} Russia [Scientific Center/Chernogolovka] @ 
@uref{ftp://ftp.chg.ru/pub/databases/mysql/, FTP}
@item
@c EMAIL: sebi@dnttm.ro (Sebastian DEAC)
@image{Img/romania} Romania [Timisoara] @ 
@uref{http://www.dnttm.ro/mysql, WWW}
@uref{ftp://ftp.dnttm.ro/pub/mysql, FTP}
@item
@c EMAIL: tim@lbi.ro (Bogdan Surdu)
@image{Img/romania} Romania [Bucharest] @ 
@uref{http://www.lbi.ro/MySQL, WWW}
@uref{ftp://ftp.lbi.ro/mirrors/ftp.tcx.se, FTP}

@item
@c EMAIL: Patrik.Karen@sdi.slu.se (Patrik Karen)
@c ftp -> remove old files
@image{Img/sweden} Sweden [Sunet] @ 
@uref{http://ftp.sunet.se/pub/unix/databases/relational/mysql/, WWW}
@uref{ftp://ftp.sunet.se/pub/unix/databases/relational/mysql/, FTP}

@item
@c EMAIL: archive@sunsite.cnlab-switch.ch (Thomas Lenggenhager)
@image{Img/switzerland} Switzerland [Sunsite] @ 
@uref{http://sunsite.cnlab-switch.ch/ftp/mirror/mysql/, WWW}
@uref{ftp://sunsite.cnlab-switch.ch/mirror/mysql/, FTP}

@c @item
@c @c simon@oyster.co.uk (Simon Gornall)
@c @image{Img/great-britain} UK [Oyster/UK] @ 
@c @uref{ftp://ftp.oyster.co.uk/pub/mysql, FTP}

@item
@c gareth@omnipotent.net (Gareth Watts)
@image{Img/great-britain} UK [Omnipotent/UK] @ 
@uref{http://mysql.omnipotent.net/, WWW}
@uref{ftp://mysql.omnipotent.net/, FTP}

@item
@c keet@mordor.plig.net (Christiaan Keet)
@image{Img/great-britain} UK [PLiG/UK] @ 
@uref{http://ftp.plig.org/pub/mysql/, WWW}
@uref{ftp://ftp.plig.org/pub/mysql/, FTP}
@c @item
@c unknown
@c @image{Img/great-britain} UK [MicroMuse] @ 
@c @uref{ftp://ftp.micromuse.co.uk/pub/packages/unix/databases/mysql/, FTP}

@item
@c lmjm@icparc.ic.ac.uk (Lee McLoughlin)
@image{Img/great-britain} UK [SunSITE] @
@uref{http://sunsite.org.uk/packages/mysql/, WWW}
@uref{ftp://sunsite.org.uk/packages/mysql/, FTP}

@item
@c sander@paco.net (Alexander Ivanov)
@image{Img/ukraine} Ukraine [PACO] @
@uref{http://mysql.paco.net.ua, WWW}
@uref{ftp://mysql.paco.net.ua/, FTP}

@end itemize

@strong{North America:}

@itemize @bullet
@c @item
@c Not ok 990101 (only to 981007)
@c EMAIL: sysop@polarcom.com (Seamus Venasse)
@c @image{Img/canada} Canada [Polaris Computing] @ 
@c @uref{http://mysql.polaris.ca/, WWW}

@item
@c Ok 980109
@c EMAIL: wojtek@tryc.on.ca (Wojtjeck Tryc)
@image{Img/canada} Canada [Tryc] @ 
@uref{http://web.tryc.on.ca/mysql/, WWW}

@c @item
@c not updated 990218
@c EMAIL: rhooper@cyberus.ca (Roy Hooper)
@c @image{Img/canada} Canada [Cyberus] @ 
@c @uref{http://mysql.cyberus.ca/, WWW}
@c @uref{ftp://mysql.cyberus.ca/, FTP} 

@item
@c EMAIL:  mleber@he.net (Mike Leber)
@c Added 980312
@image{Img/usa} USA [Hurricane Electric/San Jose] @ 
@uref{http://mysql.he.net, WWW}

@item
@c EMAIL: tps@users.buoy.com (Tim Sailer) 
@image{Img/usa} USA [Buoy/New York] @ 
@uref{http://www.buoy.com/mysql/, WWW}

@c @item
@c EMAIL: db@hpnc.com (Douglas Bowyer)
@c Added 980107, removed 981124 because of 'file not found'
@c @image{Img/usa} USA [Hypernet Communications/Dallas] @ 
@c @uref{http://epsilon.hpnc.com/mysql, WWW}

@c @item @c **********************************
@c Not updated 980106
@c EX: twh@iquest.net (Thomas Holt) who no longer works there
@c @image{Img/usa} USA [IQuest/Indiana] @ 
@c @uref{http://mirrors.iquest.net/mysql/, WWW}

@c @item @c **********************************
@c Only a partial mirror so we exclude it from the list
@c EX: lindberg@id.wustl.edu (Fred Lindberg)
@c @image{Img/usa} USA [Washington University/St. Louis] @ 
@c @uref{ftp://ftp.id.wustl.edu/pub/database/mysql/, FTP}

@item
@c EMAIL: andrew@netcasting.net (Andrew Sawyers)
@image{Img/usa} USA [Netcasting/West Coast] @ 
@uref{ftp://ftp.netcasting.net/pub/mysql/, FTP}

@c @item
@c No mirror! 980809 David
@c EMAIL: savages@savages.com (Shaun Savage)
@c @image{Img/usa} USA [Savages/Oregon] @ 
@c @uref{http://mysql.savages.com, WWW}

@item
@c EMAIL: tcobb@staff.circle.net (Troy Cobb)
@image{Img/usa} USA [Circle Net/North Carolina] @ 
@uref{http://www.mysql.net, WWW}

@item
@c EMAIL: paul@gina.net (Paul Vining)
@c mirrors ftp.sunet.se
@image{Img/usa} USA [Gina net/Florida] @ 
@uref{http://www.gina.net/mysql/, WWW}

@item
@c EMAIL: wswanson@pingzero.net (Wylie Swanson)
@c mirrors mysql.org
@image{Img/usa} USA [pingzero/Los Angeles] @
@uref{http://mysql.pingzero.net/, WWW}

@item
@c EMAIL: ftp-admin@digex.net
@image{Img/usa} USA [DIGEX] @ 
@uref{ftp://ftp.digex.net/pub/packages/database/mysql/download.html, FTP}

@end itemize

@strong{South America:}

@itemize @bullet
@item
@c jpabuyer@vision.cl
@image{Img/chile} Chile [vision] @ 
@uref{http://mysql.vision.cl/}
@item
@c EMAIL: dan@amerikanclaris.com (Danilo Lotina F.)
@image{Img/chile} Chile [Amerikanclaris] @ 
@uref{http://www.labs.amerikanclaris.cl/mysql, WWW}
@uref{ftp://ftp.amerikanclaris.cl/pub/mysql, FTP}
@end itemize

@strong{Asia:}

@itemize @bullet
@item
@c EMAIL: ahmlhs@nmsvr.chosun.com (Ho-sun Lee)
@image{Img/south-korea} Korea [KREONet] @ 
@uref{http://linux.kreonet.re.kr/mysql/, WWW}
@c @item @c **********************************
@c ftp -> remove old files
@c EX: ahmlhs@nmsvr.chosun.com (Ho-sun Lee)
@c @image{Img/south-korea} Korea [KREONet] @ 
@c @uref{ftp://linux.kreonet.re.kr/pub/tools/db/mysql/, FTP}
@item
@c Ok 980805
@c EMAIL: takeshi@SoftAgency.co.jp
@image{Img/japan} Japan [Soft Agency] @ 
@uref{http://www.softagency.co.jp/MySQL, WWW}
@item
@c Ok 980109
@c EMAIL: satoshi@HappySize.co.jp (Satoshi TATSUOKA)
@image{Img/japan} Japan [Nagoya Syouka University] @ 
@uref{http://www.happysize.co.jp/mysql/, WWW}
@uref{ftp://ftp.happysize.co.jp/pub/mysql/, FTP}

@item
@c Ok 981204
@c EMAIL: hiroyuki@nucba.ac.jp (hiroyuki kurimoto)
@image{Img/japan} Japan [HappySize] @ 
@uref{http://mirror.nucba.ac.jp/mirror/mysql, WWW}
@uref{ftp://mirror.nucba.ac.jp/mirror/mysql, FTP}

@c @item
@c Removed 990308
@c EMAIL: terence@com5.net (Terence Chan)
@c @image{Img/singapore} Singapore [Com5 Productions] @ 
@c @uref{http://mysql.com5.net, WWW}
@c @uref{ftp://ftp.com5.net/pub/mysql, FTP}
@item
@c EMAIL: csy@hjc.edu.sg
@image{Img/singapore} Singapore [HJC] @
@uref{http://mysql.hjc.edu.sg, WWW}
@uref{ftp://ftp.hjc.edu.sg/mysql, FTP}
@item
@c Ok 980321
@c EMAIL: tby@ccca.nctu.edu.tw (Bao-Yi Tuang)
@image{Img/taiwan} Taiwan [NCTU] @ 
@uref{http://mysql.taconet.com.tw, WWW}
@item
@c EMAIL: dean@access.ttn.com.tw (Dean Lin)
@image{Img/taiwan} Taiwan [TTN] @ 
@uref{http://mysql.ttn.net, WWW}
@c @item @c **********************************
@c Error 980106
@c EX: WolfySu@acer.net (Wolfy Su)
@c @image{Img/taiwan} Taiwan [Acer] @ 
@c @uref{http://mysql.acer.net/, WWW}
@c @item @c **********************************
@c files to delete
@c EX: service@wownet.net
@c @image{Img/taiwan} Taiwan [Wownet] @ 
@c @uref{ftp://ftp.wownet.net/mysql/, FTP}
@c @item @c **********************************
@c No conntact 980106
@c EX: serge@oneway.net
@c @image{Img/taiwan} Taiwan [Oneway] @ 
@c @uref{ftp://ftp.oneway.com.tw/pub/mysql/, FTP}
@end itemize

@strong{Australia:}

@itemize @bullet
@item
@c Added 980610
@c EMAIL: jason@dstc.edu.au (Jason Andrade)
@image{Img/australia} Australia [AARNet/Queensland] @ 
@uref{http://mirror.aarnet.edu.au/mysql, WWW}
@uref{ftp://mirror.aarnet.edu.au/pub/mysql, FTP}

@item
@c Added 980805
@c EMAIL: sdd@ntccc.tas.gov.au (Scott Donovan)
@image{Img/australia} Australia [Tas] @ 
@uref{http://ftp.tas.gov.au/mysql, WWW}
@uref{ftp://ftp.tas.gov.au/pub/mysql, FTP}

@item
@c Ok 980623
@c EMAIL: samh@bluep.com (Sam Hadzajlic)
@image{Img/australia} Australia [Blue Planet/Melbourne] @ 
@uref{http://mysql.bluep.com/, WWW}
@uref{ftp://mysql.bluep.com/pub/mirror1/mysql/, FTP}

@item
@c Added 990531
@c EMAIL: gavin@itworks.com.au (Gavin Cameron)
@image{Img/australia} Australia [ITworks Consulting/Victoria] @ 
@uref{http://mysql.itworks.com.au, WWW}

@c @item
@c 980610 Only the toplevel dir!
@c EMAIL: lucifer@maths.uq.edu.au (David Conran)
@c @image{Img/australia} Australia FTP @ 
@c @uref{ftp://ftp.sage-au.org.au/pub/database/mysql, [Sage]}
@end itemize

@strong{Africa:}

@itemize @bullet

@item
@c Ok 981010
@c EMAIL: oskar@is.co.za (Oskar Pearson)
@image{Img/south-africa1} South-Africa [The Internet Solution/Johannesburg] @ 
@uref{ftp://ftp.is.co.za/linux/mysql/, FTP}

@item
@c Ok 981010
@c EMAIL: nick@mweb.com (Nick Rosenberg)
@image{Img/south-africa1} South-Africa [Mweb/] @ 
@uref{http://www.mysql.mweb.co.za, WWW}

@end itemize

@node Which OS, Which version, Getting MySQL, Installing
@section Operating systems supported by @strong{MySQL}

We use GNU Autoconf so it is possible to port @strong{MySQL} to all modern
systems with working Posix threads and a C++ compiler. (To compile only the
client code, a C++ compiler is required but not threads.)  We use and develop
the software ourselves primarily on Sun Solaris (versions 2.5 & 2.6) and to a
lesser extent on RedHat Linux 5.0.

@strong{MySQL} has been reported to compile sucessfully on the following
operating system/thread package combinations.  Note that for many operating
systems, the native thread support works only in the latest versions.

@itemize @bullet
@item
AIX 4.x with native threads
@item
BSDI 2.x with the included MIT-pthreads package
@item
BSDI 3.0, 3.1 and 4.x with native threads
@item
DEC UNIX 4.x with native threads
@item
FreeBSD 2.x with the included MIT-pthreads package
@item
FreeBSD 3.x with native threads
@item
HP-UX 10.20 with the included MIT-pthreads package
@item
HP-UX 11.x with the native threads.
@item
Linux 2.0+ with LinuxThreads 0.7.1 or @code{glibc} 2.0.7
@item
NetBSD 1.3 Intel and NetBSD 1.3 Alpha
@item
OpenBSD 2.x with the included MIT-pthreads package
@item
OS/2 Warp 3, FixPack 29 and OS/2 Warp 4, FixPack 4
@item
SGI Irix 6.x with native threads
@item
Solaris 2.5, 2.6 and 2.7 with native threads on SPARC and x86
@item
SunOS 4.x with the included MIT-pthreads package
@item
SCO OpenServer with a recent port of the FSU Pthreads package
@item
SCO UnixWare 7.0.1
@item
Tru64 Unix
@item
Win95, Win98 and NT (the newest version is currently available only for
users with a @strong{MySQL} license or @strong{MySQL} email support).
For those who wish to test before they buy, we have released
@uref{http://www.mysql.com/mysql_w32.htmy,@strong{MySQL} 3.21.29} (an
older version) as shareware.
@end itemize

@cindex @strong{MySQL} binary distribution
@cindex @strong{MySQL} source distribution
@cindex Release numbers
@cindex Version, choosing
@cindex Choosing version
@node Which version, Many versions, Which OS, Installing
@section Which @strong{MySQL} version to use

The first decision to make is whether you want to use the latest development
release or the last stable release:

@itemize @bullet
@item
Normally, if you are beginning to use @strong{MySQL} for the first time or
trying to port it to some system for which there is no binary distribution,
we recommend going with the development release (currently 3.22.x). This is
because there are usually no really serious bugs in the development release,
and you can easily test it on your machine with the @code{crash-me} and
benchmark tests.
@xref{Benchmarks}.

@item
Otherwise, if you are running an old system and want to upgrade, but don't
want to take chances with 3.22, you should upgrade to 3.21.33.  We have tried
to fix only fatal bugs and make small, relatively safe changes to that
version.
@end itemize

The second decision to make is whether you want to use a source distribution or
a binary distribution:

@itemize @bullet
@item
If you want to run @strong{MySQL} on a platform for which a current binary
distribution exists, use that.  Generally, it will be easier to install
than a source distribution.

@item
If you want to read (and/or modify) the C and C++ code that makes up
@strong{MySQL}, you should get a source distribution. The source code is
always the ultimate manual. Source distributions also contain more
tests and examples than binary distributions.
@end itemize

The @strong{MySQL} naming scheme uses release numbers that consist of three
numbers and a suffix.  For example, a release name like
@code{mysql-3.21.17-beta} is interpreted like this:

@itemize @bullet
@item
The first number (@code{3}) describes the file format.  All
version 3 releases have the same file format. When a version 4 appears, every
table will have to be converted to the new format (nice tools for this will
be included, of course).

@item
The second number (@code{21}) is the release level. Normally there are two to
choose from. One is the release/stable branch (currently @code{21}) and the
other is the development branch (currently @code{22}) . Normally both are
stable, but the development version may have quirks, missing documentation on
new features or may fail to compile on some systems.

@item
The third number (@code{17}) is the version number within the
release level. This is incremented for each new distribution. Usually you
want the latest version for the release level you have choosen.

@item
The suffix (@code{beta}) indicates the stability level of
the release.  The possible suffixes are:

@itemize @minus
@item @code{alpha} indicates that the release contains some large section of
new code that hasn't been 100% tested.  Known bugs (usually there are none)
should be documented in the News section.  @xref{News}.  There are also new
commands and extensions in most alpha releases.

@item
@code{beta} means that all new code has been tested. No major new features
were added. There should be no known bugs.

@item
@code{gamma} is a beta that has been around a while and seems to work fine.
This is what many other companies call a release.

@item
If there is no suffix, it means that the version has been run for a while
at many different sites with no reports of bugs other than platform-specific
bugs.  This is what we call a stable release.
@end itemize
@end itemize

All versions of @strong{MySQL} are run through our standard tests and
benchmarks to ensure that they are relatively safe to use.  Since the standard
tests are extended over time to check for all previously found bugs,
the test suite keeps getting better.

Note that all releases have been tested at least with:

@table @asis
@item An internal test suite
This is part of a production system for a customer. It has many tables with
hundreds of megabytes of data.

@item The @strong{MySQL} benchmark suite
This runs a range of common queries. It is also a test to see whether the
latest batch of optimizations actually made the code faster.
@xref{Benchmarks}.

@item The @code{crash-me} test
This tries to determine what features the database supports and what its
capabilities and limitations are.
@xref{Benchmarks}.
@end table

Another test is that we use the newest @strong{MySQL} version in our internal
production environment, on at least one machine.  We have more than 100
gigabytes of data to work with.

@node Many versions, Installation layouts, Which version, Installing
@section How and when updates are released

@strong{MySQL} is evolving quite rapidly here at TcX and we want
to share this with other @strong{MySQL} users. We try to make a release
when we have very useful features that others seem to have a need for.

We also try to help out users who request features that are easy to
implement. We also take note of what our licensed users want to have and
we especially take note of what our extended email supported customers
want and try to help them out.

No one has to download a new release. The News section will tell you if
the new release has something you really want. @xref{News}.

We use the following policy when updating @strong{MySQL}:

@itemize @bullet
@item
For each minor update, the last number in the version string is incremented.
When there are major new features or minor incompatibilities with previous
versions, the second number in the version string is incremented. When the
file format changes, the first number is increased.

@item
Stable tested releases are meant to appear about 1-2 times a year, but
if small bugs are found, a release with only bug-fixes will be released.

@item
Working releases are meant to appear about every 1-8 weeks.

@item
Binary distributions for some platforms will be made by us for major releases.
Other people may make binary distributions for other systems but probably
less frequently.

@item
We usually make patches available as soon as we have located and fixed
small bugs.

@item
For non-critical but annoying bugs, we will make patches available if they
are sent to us. Otherwise we will combine many of them into a larger
patch.

@item
If there is, by any chance, a fatal bug in a release we will make a new
release as soon as possible. We would like other companies to do this,
too. :)
@end itemize

The current stable release is 3.22; We have already moved active
development to 3.23. Bugs will still be fixed in the stable version. We
don't believe in a complete freeze, as this also leaves out bug fixes
and things that ``must be done''. ``Somewhat frozen'' means that we may
add small things that ``almost surely will not affect anything that's
already working''.

@node Installation layouts, Installing binary, Many versions, Installing
@section Installation layouts

This section describes the default layout of the directories created by
installing binary and source distributions.

A binary distribution is installed by unpacking it at the installation
location you choose (typically @file{/usr/local/mysql}) and creates the
following directories in that location:

@multitable @columnfractions .3 .7
@item @strong{Directory} @tab @strong{Contents of directory}
@item @file{bin}         @tab Client programs and the @code{mysqld} server
@item @file{data}        @tab Log files, databases
@item @file{include}     @tab Include (header) files
@item @file{lib}         @tab Libraries
@item @file{scripts}     @tab @code{mysql_install_db}
@item @file{share/mysql} @tab Error message files
@item @file{sql-bench}   @tab Benchmarks
@end multitable

A source distribution is installed after you configure and compile it.  By
default, the installation step installs files under @file{/usr/local}, in the
following subdirectories:

@multitable @columnfractions .3 .7
@item @strong{Directory} @tab @strong{Contents of directory}
@item @file{bin}         @tab Client programs and scripts
@item @file{include/mysql}  @tab Include (header) files
@item @file{info}	 @tab Documentation in Info format
@item @file{lib/mysql}   @tab Libraries
@item @file{libexec}     @tab The @code{mysqld} server
@item @file{share/mysql} @tab Error message files
@item @file{sql-bench}   @tab Benchmarks and @code{crash-me} test
@item @file{var}         @tab Databases and log files.
@end multitable

Within an installation directory, the layout of a source installation differs
from that of a binary installation in the following ways:

@itemize @bullet
@item
The @code{mysqld} server is installed in the @file{libexec}
directory rather than in the @file{bin} directory.

@item
The data directory is @file{var} rather than @file{data}.

@item
@code{mysql_install_db} is installed in the @file{/usr/local/bin} directory
rather than in @file{/usr/local/mysql/scripts}.

@item
The header file and library directories are @file{include/mysql} and
@file{lib/mysql} rather than @file{include} and @file{lib}.
@end itemize

@node Installing binary, Installing source, Installation layouts, Installing
@section Installing a @strong{MySQL} binary distribution

@menu
* Linux-RPM::                   Linux RPM files
* Building clients::            Building client programs
* Binary install system issues::  System-specific issues
@end menu

You need the following tools to install a @strong{MySQL} binary distribution:

@itemize @bullet
@item
GNU @code{gunzip} to uncompress the distribution.

@item
A reasonable @code{tar} to unpack the distribution. GNU @code{tar} is
known to work.
@end itemize

@cindex RPM
@cindex RedHat Package Manager
An alternative installation method under Linux is to use RPM (RedHat Package
Manager) distributions. @xref{Linux-RPM}.

@c texi2html fails to split chapters if I use strong for all of this.
If you run into problems, @strong{PLEASE ALWAYS USE} @code{mysqlbug} when
posting questions to @email{mysql@@lists.mysql.com}.  Even if the problem
isn't a bug, @code{mysqlbug} gathers system information that will help others
solve your problem.  By not using @code{mysqlbug}, you lessen the likelihood
of getting a solution to your problem!  You will find @code{mysqlbug} in the
@file{bin} directory after you unpack the distribution.  @xref{Bug reports}.

The basic commands you must execute to install and use a @strong{MySQL}
binary distribution are:

@example
shell> gunzip < mysql-VERSION-OS.tar.gz | tar xvf -
shell> ln -s mysql-VERSION-OS mysql
shell> cd mysql
shell> scripts/mysql_install_db
shell> bin/safe_mysqld &
@end example

You can add new users using the @code{bin/mysql_setpermission} script if
you install the @code{DBI} and @code{Msql-Mysql-modules} Perl modules.

Here follows a more detailed description:

To install a binary distribution, follow the steps below, then proceed
to @ref{Post-installation}, for post-installation setup and testing:

@enumerate
@item
Pick the directory under which you want to unpack the distribution, and move
into it.  In the example below, we unpack the distribution under
@file{/usr/local} and create a directory @file{/usr/local/mysql} into which
@strong{MySQL} is installed.  (The following instructions therefore assume
you have permission to create files in @file{/usr/local}.  If that directory
is protected, you will need to perform the installation as @code{root}.)

@item
Obtain a distribution file from one of the sites listed in
@ref{Getting MySQL, , Getting @strong{MySQL}}.

@strong{MySQL} binary distributions are provided as compressed @code{tar}
archives and have names like @file{mysql-VERSION-OS.tar.gz}, where
@code{VERSION} is a number (e.g., @code{3.21.15}), and @code{OS} indicates
the type of operating system for which the distribution is intended (e.g.,
@code{pc-linux-gnu-i586}).

@item
Unpack the distribution and create the installation directory:

@example
shell> gunzip < mysql-VERSION-OS.tar.gz | tar xvf -
shell> ln -s mysql-VERSION-OS mysql
@end example

The first command creates a directory named @file{mysql-VERSION-OS}.  The
second command makes a symbolic link to that directory.  This lets you refer
more easily to the installation directory as @file{/usr/local/mysql}.

@item
Change into the installation directory:

@example
shell> cd mysql
@end example

You will find several files and subdirectories in the @code{mysql} directory.
The most important for installation purposes are the @file{bin} and
@file{scripts} subdirectories.

@table @file
@item bin
@tindex PATH environment variable
@tindex Environment variable, PATH
This directory contains client programs and the server
You should add the full pathname of this directory to your
@code{PATH} environment variable so that your shell finds the @strong{MySQL}
programs properly.
@item scripts
This directory contains the @code{mysql_install_db} script used to initialize
the server access permissions.
@end table

@item
If you would like to use @code{mysqlaccess} and have the @strong{MySQL}
distribution in some nonstandard place, you must change the location where
@code{mysqlaccess} expects to find the @code{mysql} client. Edit the
@file{bin/mysqlaccess} script at approximately line 18. Search for a line
that looks like this:

@example
$MYSQL     = '/usr/local/bin/mysql';    # path to mysql executable
@end example

Change the path to reflect the location where @code{mysql} actually is
stored on your system.  If you do not do this, you will get a @code{broken
pipe} error when you run @code{mysqlaccess}.

@item
Create the @strong{MySQL} grant tables (necessary only if you haven't
installed @strong{MySQL} before):
@example
shell> scripts/mysql_install_db
@end example

@item
If you want to install support for the Perl @code{DBI}/@code{DBD} interface,
see @ref{Perl support}.

@item
If you would like @strong{MySQL} to start automatically when you boot your
machine, you can copy @code{support-files/mysql.server} to the location where
your system has its startup files. More information can be found in the
@code{support-files/mysql.server} script itself, and in @ref{Automatic
start}.

@end enumerate

After everything has been unpacked and installed, you should initialize
and test your distribution.

You can start the @strong{MySQL} server with the following command:

@example
shell> bin/safe_mysqld &
@end example

Note that @strong{MySQL} versions before 3.22.10 started the @strong{MySQL}
server when you run @code{mysql_install_db}.  This is no longer true!

@xref{Post-installation}.

@cindex RPM
@cindex RedHat Package Manager
@c This node name is special
@node Linux-RPM, Building clients, Installing binary, Installing binary
@subsection Linux RPM notes

The recommended way to install @strong{MySQL} on Linux is by using an RPM
file. The @strong{MySQL} RPMs are currently being built on a RedHat 5.2
system but should work on other versions of Linux that support @code{rpm} and
use @code{glibc}.

If you have problems with an RPM file, for example @code{Sorry, the host
'xxxx' could not be looked up}, see @ref{Binary notes-Linux}.

The RPM files you may want to use are:

@itemize @bullet
@item @code{MySQL-VERSION.i386.rpm}

The @strong{MySQL} server.  You will need this unless you only want to
connect to another @strong{MySQL} server running on another machine.

@item @code{MySQL-client-VERSION.i386.rpm}

The standard @strong{MySQL} client programs. You probably always want to
install this package.

@item @code{MySQL-bench-VERSION.i386.rpm}

Tests and benchmarks. Requires Perl and msql-mysql-modules RPMs.

@item @code{MySQL-devel-VERSION.i386.rpm}

Libraries and include files needed if you want to compile other
@strong{MySQL} clients, such as the Perl modules.

@item @code{MySQL-VERSION.src.rpm}

This contains the source code for all of the above packages. It can also
be used to try to build RPMs for other architectures (for example, Alpha
or SPARC).
@end itemize

To see all files in an RPM package:
@example
shell> rpm -qpl MySQL-VERSION.i386.rpm
@end example

To perform a standard minimal installation, run this command:

@example
shell> rpm -i MySQL-VERSION.i386.rpm MySQL-client-VERSION.i386.rpm
@end example

To install just the client package:

@example
shell> rpm -i MySQL-client-VERSION.i386.rpm
@end example

The RPM places data in @file{/var/lib/mysql}. The RPM also creates the
appropriate entries in @file{/sbin/rc.d/} to start the server automatically
at boot time.  (This means that if you have performed a previous
installation, you may want to make a copy of your previously-installed
@strong{MySQL} startup file if you made any changes to it, so you don't lose
your changes.)

After installing the RPM file(s), go to the binary install section and use
the instructions there, starting from the step that creates the
@strong{MySQL} grant tables.
@xref{Installing binary}.

@cindex Client programs, building
@cindex Linking
@node Building clients, Binary install system issues, Linux-RPM, Installing binary
@subsection Building client programs

If you compile @strong{MySQL} clients that you've written yourself or that
you obtain from a third party, they must be linked using the
@code{-lmysqlclient} option on the link command.  You may also need to
specify a @code{-L} option to tell the linker where to find the library.  For
example, if the library is installed in @file{/usr/local/mysql/lib}, use
@code{-L/usr/local/mysql/lib -lmysqlclient} on the link command.

For clients that use @strong{MySQL} header files, you may need to specify a
@code{-I} option when you compile them (for example,
@code{-I/usr/local/mysql/include}), so the compiler can find the header
files.

@node Binary install system issues,  , Building clients, Installing binary
@subsection System-specific issues

@menu
* Binary notes-Linux::          Linux notes
* Binary notes-HP-UX::          HP-UX notes
@end menu

The following sections indicate some of the issues that have been observed to
occur on particular systems when installing @strong{MySQL} from a binary
distribution.

@node Binary notes-Linux, Binary notes-HP-UX, Binary install system issues, Binary install system issues
@subsubsection Linux notes

@strong{MySQL} needs at least Linux 2.0.

The binary release is linked with @code{-static}, which means you not
normally need not worry about which version of the system libraries you
have. You need not install LinuxThreads, either.  A program linked with
@code{-static} is slightly bigger than a dynamically-linked program but
also slightly faster (3-5%).  The only problem is that you can't use
user definable functions (UDFs) with a statically-linked program.  If
you are going to write or use UDF functions (this is something only for
C or C++ programmers) you must compile @strong{MySQL} yourself, using
dynamic linking.

If you are using a @code{libc}-based system (instead of a @code{glibc2}
system), you will probably get some problems with hostname resolving
with the binary release.  (This is because @code{glibc} unfortunately
depends on some external libraries to resolve hostnames, even when
compiled with @code{-static}). In this case you probably get the
following error message when you run @code{mysql_install_db}:

@example
Sorry, the host 'xxxx' could not be looked up
@end example

You can solve this problem one of the following ways:

@itemize @bullet
@item
Get a @strong{MySQL} source distribution (an RPM or the @code{tar}
distribution) and install this instead.
@item
Execute @code{mysql_install_db --force}; This will not execute the
@code{resolveip} test in @code{mysql_install_db}.  The downside is that
you can't use host names in the grant tables; you must use IP numbers
instead (except for @code{localhost}).  If you are using an old @strong{MySQL}
release that doesn't support @code{--force} you have to remove the
@code{resolveip} test in @code{mysql_install} with an editor.
@end itemize

The Linux-Intel binary and RPM releases of @strong{MySQL} are configured
for the highest possible speed. We are always trying to use the fastest
stable compiler available.

@strong{MySQL} Perl support requires Perl 5.004_03 or newer.

@node Binary notes-HP-UX,  , Binary notes-Linux, Binary install system issues
@subsubsection HP-UX notes

The binary distribution of @strong{MySQL} for HP-UX is distributed as an
HP depot file.  This means that you must be running at least HP-UX 10.x
to have access to HP's software depot tools.

The HP version of @strong{MySQL} was compiled on an HP 9000/8xx server
under HP-UX 10.20, and uses MIT-pthreads. It is known to work
well under this configuration. This version does @strong{not} use HP's native
thread package. It is highly unlikely that @strong{MySQL} will use HP native
threads on anything but HP-UX 10.30 or later.

Other configurations that may work:

@itemize @bullet
@item
HP 9000/7xx running HP-UX 10.20+
@item
HP 9000/8xx running HP-UX 10.30 (does not use HP native threads)
@end itemize

The following configurations almost definitely won't work:

@itemize @bullet
@item
HP 9000/7xx or 8xx running HP-UX 10.x where x < 2
@item
HP 9000/7xx or 8xx running HP-UX 9.x
@end itemize

To install the distribution, use one of the commands below, where
@code{/path/to/depot} is the full pathname of the depot file:

@itemize @bullet
@item
To install everything, including the server, client and development tools:

@example
shell> /usr/sbin/swinstall -s /path/to/depot mysql.full
@end example

@item
To install only the server:

@example
shell> /usr/sbin/swinstall -s /path/to/depot mysql.server
@end example

@item
To install only the client package:

@example
shell> /usr/sbin/swinstall -s /path/to/depot mysql.client
@end example

@item
To install only the development tools:

@example
shell> /usr/sbin/swinstall -s /path/to/depot mysql.developer
@end example
@end itemize

The depot places binaries and libraries in @file{/opt/mysql} and data in
@file{/var/opt/mysql}. The depot also creates the appropriate entries in
@file{/sbin/init.d} and @file{/sbin/rc2.d} to start the server automatically
at boot time. Obviously, this entails being @code{root} to install.

@node Installing source, Compilation problems, Installing binary, Installing
@section Installing a @strong{MySQL} source distribution

You need the following tools to build and install @strong{MySQL} from source:

@itemize @bullet
@item
GNU @code{gunzip} to uncompress the distribution.

@item
A reasonable @code{tar} to unpack the distribution. GNU @code{tar} is
known to work.

@item
A working ANSI C++ compiler. @code{gcc} >= 2.8.1, @code{egcs} >=
1.0.2, SGI C++ and SunPro C++ are some of the compilers that are known to
work.  @code{libg++} is not needed when using @code{gcc}.  @code{gcc}
2.7.x has a bug that makes it impossible to compile some perfectly legal
C++ files, such as @file{sql/sql_base.cc}. If you only have @code{gcc} 2.7.x,
you must upgrade your @code{gcc} to be able to compile @strong{MySQL}.

@item
A good @code{make} program.  GNU @code{make} is always recommended and is
sometimes required.  If you have problems, we recommend trying GNU
@code{make} 3.75 or newer.
@end itemize

@c texi2html fails to split chapters if I use strong for all of this.
If you run into problems, @strong{PLEASE ALWAYS USE @code{mysqlbug}} when
posting questions to @email{mysql@@lists.mysql.com}.  Even if the problem
isn't a bug, @code{mysqlbug} gathers system information that will help others
solve your problem.  By not using @code{mysqlbug}, you lessen the likelihood
of getting a solution to your problem!  You will find @code{mysqlbug} in the
@file{scripts} directory after you unpack the distribution.  @xref{Bug
reports}.

@menu
* Quick install::               Quick installation overview
* Applying patches::            Applying patches
* configure options::           Typical @code{configure} options
@end menu

@node Quick install, Applying patches, Installing source, Installing source
@subsection Quick installation overview

The basic commands you must execute to install a @strong{MySQL} source
distribution are (from an unpacked @code{tar} file):

@example
shell> configure
shell> make
shell> make install
shell> scripts/mysql_install_db
shell> /usr/local/mysql/bin/safe_mysqld &
@end example

If you start from a source RPM, then do the following.

@example
shell> rpm --rebuild MySQL-VERSION.src.rpm
@end example

This will make a binary RPM that you can install.

You can add new users using the @code{bin/mysql_setpermission} script if
you install the @code{DBI} and @code{Msql-Mysql-modules} Perl modules.

Here follows a more detailed description:

To install a source distribution, follow the steps below, then proceed
to @ref{Post-installation}, for post-installation initialization and testing.

@enumerate
@item
Pick the directory under which you want to unpack the distribution, and move
into it.

@item
Obtain a distribution file from one of the sites listed in
@ref{Getting MySQL, , Getting @strong{MySQL}}.

@strong{MySQL} source distributions are provided as compressed @code{tar}
archives and have names like @file{mysql-VERSION.tar.gz}, where
@code{VERSION} is a number like @value{mysql_version}.

@item
Unpack the distribution into the current directory:
@example
shell> gunzip < mysql-VERSION.tar.gz | tar xvf -
@end example
This command creates a directory named @file{mysql-VERSION}.

@item
Change into the top-level directory of the unpacked distribution:
@example
shell> cd mysql-VERSION
@end example

@item
Configure the release and compile everything:
@example
shell> ./configure --prefix=/usr/local/mysql
shell> make
@end example
When you run @code{configure}, you might want to specify some options.
Run @code{./configure --help} for a list of options.
@ref{configure options, , @code{configure} options}, discusses some of the
more useful options.

If @code{configure} fails, and you are going to send mail to
@email{mysql@@lists.mysql.com} to ask for assistance, please include any
lines from @file{config.log} that you think can help solve the problem.  Also
include the last couple of lines of output from @code{configure} if
@code{configure} aborts. Post the bug report using the @code{mysqlbug}
script.  @xref{Bug reports}.

If the compile fails, see @ref{Compilation problems}, for help with
a number of common problems.

@item
Install everything:
@example
shell> make install
@end example
You might need to run this command as @code{root}.

@item
Create the @strong{MySQL} grant tables (necessary only if you haven't
installed @strong{MySQL} before):
@example
shell> scripts/mysql_install_db
@end example

@item
If you want to install support for the Perl @code{DBI}/@code{DBD} interface,
see @ref{Perl support}.

@item
If you would like @strong{MySQL} to start automatically when you boot your
machine, you can copy @code{support-files/mysql.server} to the location where
your system has its startup files. More information can be found in the
@code{support-files/mysql.server} script itself, and in @ref{Automatic
start}.
@end enumerate

After everything has been installed, you should initialize and test your
distribution.

You can start the @strong{MySQL} server with the following command,
where @code{BINDIR} is the directory in which @code{safe_mysqld} is
installed (@file{/usr/local/bin} by default):

@example
shell> BINDIR/safe_mysqld &
@end example

If that command fails immediately with @code{mysqld daemon ended} then you can
find some information in the file
@file{mysql-data-directory/'hostname'.err}.  The likely reason is that
you already have another @code{mysqld} server running.  @xref{Multiple
servers}.

Note that @strong{MySQL} versions before 3.22.10 started the @strong{MySQL}
server when you run @code{mysql_install_db}.  This is no longer true!

@xref{Post-installation}.

@node Applying patches, configure options, Quick install, Installing source
@subsection Applying patches

Sometimes patches appear on the mailing list or are placed in the
@uref{ftp://www.mysql.com/pub/mysql/Downloads/Patches,patches area} of the
@strong{MySQL} FTP site.

To apply a patch from the mailing list, save the message in which the patch
appears in a file, change into the top-level directory of your @strong{MySQL}
source tree and run these commands:

@example
shell> patch -p1 < patch-file-name
shell> rm config.cache
shell> make clean
@end example

Patches from the FTP site are distributed as plain text files or as files
compressed with @code{gzip} files.  Apply a plain patch as shown above for
mailing list patches.  To apply a compressed patch, change into the
top-level directory of your @strong{MySQL} source tree and run these
commands:

@example
shell> gunzip < patch-file-name.gz | patch -p1
shell> rm config.cache
shell> make clean
@end example

After applying a patch, follow the instructions for a normal source install,
beginning with the @code{./configure} step.  After running the @code{make
install} step, restart your @strong{MySQL} server.

You may need to bring down any currently running server before you run
@code{make install}.  (Use @code{mysqladmin shutdown} to do this.)  Some
systems do not allow you to install a new version of a program if it replaces
the version that is currently executing.

@node configure options,  , Applying patches, Installing source
@subsection Typical @code{configure} options

The @code{configure} script gives you a great deal of control over how you
configure your @strong{MySQL} distribution.  Typically you do this using
options on the @code{configure} command line.  You can also affect
@code{configure} using certain environment variables.  For a list of options
supported by @code{configure}, run this command:

@example
shell> ./configure --help
@end example

Some of the more commonly-used @code{configure} options are described below:

@itemize @bullet
@item
To compile just the @strong{MySQL} client libraries and client programs and
not the server, use the @code{--without-server} option:

@example
shell> ./configure --without-server
@end example

If you don't have a C++ compiler, @code{mysql} will not compile (it is the
one client program that requires C++).  In this case,
you can remove the code in @code{configure} that tests for the C++ compiler
and then run @code{./configure} with the @code{--without-server} option. The
compile step will still try to build @code{mysql}, but you can ignore any
warnings about @file{mysql.cc}.  (If @code{make} stops, try @code{make -k}
to tell it to continue with the rest of the build even if errors occur.)

@item
If you don't want your log files and database directories located under
@file{/usr/local/var}, use a @code{configure} command something like one
of these:
@example
shell> ./configure --prefix=/usr/local/mysql
shell> ./configure --prefix=/usr/local \
           --localstatedir=/usr/local/mysql/data
@end example
The first command changes the installation prefix so that everything is
installed under @file{/usr/local/mysql} rather than the default of
@file{/usr/local}.  The second command preserves the default installation
prefix, but overrides the default location for database directories
(normally @file{/usr/local/var}) and changes it to
@code{/usr/local/mysql/data}.

@item
If you are using Unix and you want the @strong{MySQL} socket located somewhere
other than the default location (normally in the directory @file{/tmp} or
@file{/var/run}, use a @code{configure} command like this:
@example
shell> ./configure --with-unix-socket-path=/usr/local/mysql/tmp/mysql.sock
@end example
Note that the given file must be an absolute pathname!

@item
If you want to compile statically-linked programs (e.g., to make a binary
distribution, to get more speed or to work around problems with some RedHat
distributions), run @code{configure} like this:

@example
shell> ./configure --with-client-ldflags=-all-static \
           --with-mysqld-ldflags=-all-static
@end example

@item
If you are using @code{gcc} and don't have @code{libg++} or @code{libstdc++}
installed, you can tell @code{configure} to use @code{gcc} as your C++
compiler:

@tindex CC environment variable
@tindex Environment variable, CC
@tindex CXX environment variable
@tindex Environment variable, CXX
@example
shell> CC=gcc CXX=gcc ./configure
@end example

When you use @code{gcc} as your C++ compiler, it will not attempt to link in
@code{libg++} or @code{libstdc++}.

If the build fails and produces errors about your compiler or linker not
being able to create the shared library @file{libmysqlclient.so.#} (@samp{#}
is a version number), you can work around this problem by giving the
@code{--disable-shared} option to @code{configure}.  In this case,
@code{configure} will not build a shared @code{libmysqlclient.so.#} library.

@item
You can configure @strong{MySQL} not to use @code{DEFAULT} column values for
non-@code{NULL} columns (i.e., columns that are not allowed to be
@code{NULL}).  This causes @code{INSERT} statements to generate an error
unless you explicitly specify values for all columns that require a
non-@code{NULL} value.  To suppress use of default values, run
@code{configure} like this:

@tindex CXXFLAGS environment variable
@tindex Environment variable, CXXFLAGS
@example
shell> CXXFLAGS=-DDONT_USE_DEFAULT_FIELDS ./configure
@end example

@item
By default, @strong{MySQL} uses the ISO-8859-1 (Latin1) character set. To
change the default set, use the @code{--with-charset} option:
@example
shell> ./configure --with-charset=CHARSET
@end example
@code{CHARSET} may be one of @code{big5}, @code{cp1251}, @code{cp1257},
@code{czech}, @code{danish},@code{dec8}, @code{dos}, @code{euc_kr},
@code{german1}, @code{hebrew}, @code{hp8}, @code{hungarian},
@code{koi8_ru}, @code{koi8_ukr}, @code{latin1}, @code{latin2},
@code{sjis}, @code{swe7}, @code{tis620}, @code{ujis}, @code{usa7},
@code{win1251} or @code{win1251ukr}.
  @xref{Character sets}.

Note that if you want to change the character set, you must do a @code{make
distclean} between configurations!

If you want to convert characters between the server and the client,
you should take a look at the @code{SET OPTION CHARACTER SET} command.
@xref{SET OPTION, , @code{SET OPTION}}.

@cindex @code{isamchk}
@strong{Warning:} If you change character sets after having created any
tables, you will have to run @code{isamchk -r -q} on every
table. Your indexes may be sorted incorrectly otherwise.
(This can happen if you install @strong{MySQL}, create some tables,
then reconfigure @strong{MySQL} to use a different character set and
reinstall it.)

@item
To configure
@strong{MySQL} with debugging code, use the @code{--with-debug} option:
@example
shell> ./configure --with-debug
@end example
This causes a safe memory allocator to be included that can find some errors
and that provides output about what is happening.
@xref{Debugging server}.

@item
Options that pertain to particular systems can be found in the
system-specific sections later in this chapter.
@xref{Source install system issues}.
@end itemize

@node Compilation problems, MIT-pthreads, Installing source, Installing
@section Problems compiling?

All @strong{MySQL} programs compile cleanly for us with no warnings on
Solaris using @code{gcc}. On other systems, warnings may occur due to
differences in system include files. See @ref{MIT-pthreads}, for warnings
that may occur when using MIT-pthreads.  For other problems, check the list
below.

The solution to many problems involves reconfiguring.  If you do need to
reconfigure, take note of the following:

@cindex Running @code{configure} after prior invocation
@cindex @code{configure}, running after prior invocation
@itemize @bullet
@item
If @code{configure} is run after it already has been run, it may use
information that was gathered during its previous invocation.  This
information is stored in @file{config.cache}.  When @code{configure} starts
up, it looks for that file and reads its contents if it exists, on the
assumption that the information is still correct.  That assumption is invalid
when you reconfigure.
@item
Each time you run @code{configure}, you must run @code{make} again
to recompile.  However, you may want to remove old object files from previous
builds first, since they were compiled using different configuration options.
@end itemize

To prevent old configuration information or object files from being used,
run these commands before rerunning @code{configure}:

@example
shell> rm config.cache
shell> make clean
@end example

Alternatively, you can run @code{make distclean}.

The list below describes some of the problems compiling @strong{MySQL}
that have been found to occur most often:

@itemize @bullet
@item
@cindex @code{cc1plus} problems
@cindex @code{fatal signal 11}
@cindex @code{sql_yacc.cc} problems
@cindex Internal compiler errors
@cindex Virtual memory problems while compiling
If you get errors when compiling @file{sql_yacc.cc} such as the ones shown
below, you have probably run out of memory or swap space:

@example
Internal compiler error: program cc1plus got fatal signal 11
  or
Out of virtual memory
  or
Virtual memory exhausted
@end example

The problem is that @code{gcc} requires huge amounts of memory to compile
@file{sql_yacc.cc} with inline functions.  Try running @code{configure} with
the @code{--with-low-memory} option:

@example
shell> ./configure --with-low-memory
@end example

This option causes @code{-fno-inline} to be added to the compile line if you
are using @code{gcc} and @code{-O0} if you are using something else.  You
should try the @code{--with-low-memory} option even if you have so much
memory and swap space that you think you can't possibly have run out.  This
problem has been observed to occur even on systems with generous hardware
configurations, and the @code{--with-low-memory} option usually fixes it.

@item
By default, @code{configure} picks @code{c++} as the compiler name and
GNU @code{c++} links with @code{-lg++}.  If you are using @code{gcc},
that behavior can cause problems during configuration such as this:

@cindex C++ compiler cannot create executables
@example
configure: error: installation or configuration problem:
C++ compiler cannot create executables.
@end example

@tindex CXX environment variable
@tindex Environment variable, CXX
You might also observe problems during compilation related to
@code{g++}, @code{libg++} or @code{libstdc++}.

One cause of these problems is that you may not have @code{g++}, or you may
have @code{g++} but not @code{libg++} or @code{libstdc++}.  Take a look at
the @file{config.log} file.  It should contain the exact reason why your c++
compiler didn't work!  To work around these problems, you can use @code{gcc}
as your C++ compiler.  Try setting the environment variable @code{CXX} to
@code{"gcc -O3"}.  For example:

@tindex CXX environment variable
@tindex Environment variables, CXX
@example
shell> CXX="gcc -O3" ./configure
@end example

This works because @code{gcc} compiles C++ sources as well as @code{g++}
does, but does not link in @code{libg++} or @code{libstdc++} by default.

Another way to fix these problems, of course, is to install @code{g++},
@code{libg++} and @code{libstdc++}.

@item
If your compile fails with errors such as any of the following,
you must upgrade your version of @code{make} to GNU @code{make}:

@example
making all in mit-pthreads
make: Fatal error in reader: Makefile, line 18:
Badly formed macro assignment
  or
make: file `Makefile' line 18: Must be a separator (:
  or
pthread.h: No such file or directory
@end example

@cindex Solaris troubleshooting
@cindex FreeBSD troubleshooting
@cindex Troubleshooting, Solaris
@cindex Troubleshooting, FreeBSD
Solaris and FreeBSD are known to have troublesome @code{make} programs.

GNU @code{make} version 3.75 is known to work.

@tindex CC environment variable
@tindex Environment variable, CC
@tindex CXX environment variable
@tindex Environment variable, CXX
@tindex CFLAGS environment variable
@tindex Environment variable, CFLAGS
@tindex CXXFLAGS environment variable
@tindex Environment variable, CXXFLAGS
@item
If you want to define flags to be used by your C or C++ compilers, do so by
adding the flags to the @code{CFLAGS} and @code{CXXFLAGS} environment
variables.  You can also specify the compiler names this way using @code{CC}
and @code{CXX}.  For example:

@example
shell> CC=gcc
shell> CFLAGS=-O6
shell> CXX=gcc
shell> CXXFLAGS=-O6
shell> export CC CFLAGS CXX CXXFLAGS
@end example

See @ref{TcX binaries}, for a list of flag definitions that have been found
to be useful on various systems.

@item
If you get an error message like this,
you need to upgrade your @code{gcc} compiler:

@example
client/libmysql.c:273: parse error before `__attribute__'
@end example

@code{gcc} 2.8.1 is known to work, but we recommend using @code{egcs}
1.0.3a or newer instead.

@item
If you get errors such as those shown below when compiling @code{mysqld},
@code{configure} didn't correctly detect the type of the last argument to
@code{accept()}, @code{getsockname()} or @code{getpeername()}:

@example
cxx: Error: mysqld.cc, line 645: In this statement, the referenced
     type of the pointer value "&length" is "unsigned long", which
     is not compatible with "int".
new_sock = accept(sock, (struct sockaddr *)&cAddr, &length);
@end example

To fix this, edit the @file{config.h} file (which is generated by
@code{configure}).  Look for these lines:

@example
/* Define as the base type of the last arg to accept */
#define SOCKET_SIZE_TYPE XXX
@end example

Change @code{XXX} to @code{size_t} or @code{int}, depending on your
operating system.  (Note that you will have to do this each time you run
@code{configure}, since @code{configure} regenerates @file{config.h}.)

@item
The @file{sql_yacc.cc} file is generated from @file{sql_yacc.yy}.  Normally
the build process doesn't need to create @file{sql_yacc.cc}, because
@strong{MySQL} comes with an already-generated copy.  However, if you do need
to recreate it, you might encounter this error:

@example
"sql_yacc.yy", line xxx fatal: default action causes potential...
@end example

This is a sign that your version of @code{yacc} is deficient.
You probably need to install @code{bison} (the GNU version of @code{yacc})
and use that instead.

@item
If you need to debug @code{mysqld} or a @strong{MySQL} client, run
@code{configure} with the @code{--with-debug} option, then recompile and
link your clients with the new client library.
@xref{Debugging client}.
@end itemize

@node MIT-pthreads, Perl support, Compilation problems, Installing
@section MIT-pthreads notes

This section describes some of the issues involved in using MIT-pthreads.

Note that on Linux you should NOT use MIT-pthreads but install LinuxThreads!
@xref{Linux}.

If your system does not provide native thread support, you will need to
build @strong{MySQL} using the MIT-pthreads package.  This includes
most FreeBSD systems, SunOS 4.x, Solaris 2.4 and earlier, and some others.
@xref{Which OS}.

@itemize @bullet
@item
On most systems, you can force MIT-pthreads to be used by running
@code{configure} with the @code{--with-mit-threads} option:

@example
shell> ./configure --with-mit-threads
@end example

Building in a non-source directory is not supported when using
MIT-pthreads, because we want to minimize our changes to this code.

@item
MIT-pthreads doesn't support the @code{AF_UNIX} protocol used to implement
Unix sockets.  This means that if you compile using MIT-pthreads, all
connections must be made using TCP/IP (which is a little slower).  If you
find after building @strong{MySQL} that you cannot connect to the local
server, it may be that your client is attempting to connect to
@code{localhost} using a Unix socket as the default. Try making a TCP/IP
connection with @code{mysql} by using a host option (@code{-h} or
@code{--host}) to specify the local host name explicitly.

@item
The checks that determine whether or not to use MIT-pthreads occur only
during the part of the configuration process that deals with the server
code.  If you have configured the distribution using @code{--without-server}
to build only the client code, clients will not know whether or not
MIT-pthreads is being used and will use Unix socket connections by default.
Since Unix sockets do not work under MIT-pthreads, this means you will need
to use @code{-h} or @code{--host} when you run client programs.

@item
When @strong{MySQL} is compiled using MIT-pthreads, system locking is
disabled by default for performance reasons. You can tell the server to use
system locking with the @code{--use-locking} option.

@item
Sometimes the pthread @code{bind()} command fails to bind to a socket without
any error message (at least on Solaris). The result is that all connections
to the server fail.  For example:

@example
shell> mysqladmin version
mysqladmin: connect to server at '' failed;
error: 'Can't connect to mysql server on localhost (146)'
@end example

The solution to this is to kill the @code{mysqld} server and restart it.
This has only happened to us when we have forced the server down and done
a restart immediately.

@item
With MIT-pthreads, the @code{sleep()} system call isn't interruptible with
@code{SIGINT} (break). This is only noticeable when you run @code{mysqladmin
--sleep}.  You must wait for the @code{sleep()} call to terminate before the
interrupt is served and the process stops.

@item
When linking you may receive warning messages like these (at least on
Solaris); they can be ignored:

@example
ld: warning: symbol `_iob' has differing sizes:
    (file /my/local/pthreads/lib/libpthread.a(findfp.o) value=0x4;
file /usr/lib/libc.so value=0x140);
    /my/local/pthreads/lib/libpthread.a(findfp.o) definition taken
ld: warning: symbol `__iob' has differing sizes:
    (file /my/local/pthreads/lib/libpthread.a(findfp.o) value=0x4;
file /usr/lib/libc.so value=0x140);
    /my/local/pthreads/lib/libpthread.a(findfp.o) definition taken
@end example

@item
Some other warnings also can be ignored:

@example
implicit declaration of function `int strtoll(...)'
implicit declaration of function `int strtoul(...)'
@end example

@item
We haven't gotten @code{readline} to work with MIT-pthreads. (This isn't
needed, but may be interesting for someone.)
@end itemize

@node Perl support, Source install system issues, MIT-pthreads, Installing
@section Perl installation comments

@menu
* Perl installation::           Installing Perl on Unix
* ActiveState Perl::            Installing ActiveState Perl on Win32
* Win32 Perl::                  Installing the @strong{MySQL} Perl distribution on Win32
* Perl support problems::       Problems using the Perl @code{DBI}/@code{DBD} interface
@end menu

@node Perl installation, ActiveState Perl, Perl support, Perl support
@subsection Installing Perl on Unix

Perl support for @strong{MySQL} is provided by means of the
@code{DBI}/@code{DBD} client interface.  @xref{Perl}.  The Perl
@code{DBD}/@code{DBI} client code requires Perl 5.004 or later.  The
interface @emph{will not work} if you have an older version of Perl.

As of release 3.22.8, Perl support is distributed separately from the main
@strong{MySQL} distribution.  If you want to install Perl support, the files
you will need can be obtained from @uref{http://www.mysql.com/Contrib}.

The Perl distributions are provided as compressed @code{tar} archives and
have names like @file{MODULE-VERSION.tar.gz}, where @code{MODULE} is the
module name and @code{VERSION} is the version number.  You should get the
@code{Data-Dumper}, @code{DBI}, and @code{Msql-Mysql-modules} distributions
and install them in that order.  The installation procedure is shown below.
The example shown is for the @code{Data-Dumper} module, but the procedure is
the same for all three distributions.

@enumerate
@item
Unpack the distribution into the current directory:
@example
shell> gunzip < Data-Dumper-VERSION.tar.gz | tar xvf -
@end example
This command creates a directory named @file{Data-Dumper-VERSION}.

@item
Change into the top-level directory of the unpacked distribution:
@example
shell> cd Data-Dumper-VERSION
@end example

@item
Build the distribution and compile everything:
@example
shell> perl Makefile.PL
shell> make
shell> make test
shell> make install
@end example
@end enumerate

The @code{make test} command is important, because it verifies that the
module is working.  Note that when you run that command during the
@code{Msql-Mysql-modules} installation to exercise the interface code, the
@strong{MySQL} server must be running or the test will fail.

It is a good idea to rebuild and reinstall the @code{Msql-Mysql-modules}
distribution whenever you install a new release of @strong{MySQL},
particularly if you notice symptoms such as all your @code{DBI} scripts
dumping core after you upgrade @strong{MySQL}.

If you don't have the right to install Perl modules in the system directory
or if you to install local Perl modules, the following reference may help
you:

@example
@uref{http://www.iserver.com/support/contrib/perl5/modules.html}
@end example

Look under the heading
@code{Installing New Modules that Require Locally Installed Modules}.

@node ActiveState Perl, Win32 Perl, Perl installation, Perl support
@subsection Installing ActiveState Perl on Win32

To install the @strong{MySQL} @code{DBD} module with ActiveState Perl on
Win32, you should do the following:

@itemize @bullet
@item Open a DOS shell.
@item If required, set the HTTP_proxy variable. For example, you might try:
@code{set HTTP_proxy=my.proxy.com:3128}
@item Start the PPM program: @code{C:\perl\bin\ppm.pl}
@item If you have not already done so, install @code{DBI}: @code{install DBI}
@item If this succeeds, install @code{DBD::mysql:}
@code{http://www.mysql.com/Contrib/ppd/DBD-mysql.ppd}
@end itemize

If you can't get the above to work, you should instead install the @strong{MyODBC}
driver and connect to @strong{MySQL} server through ODBC.

@example
use DBI;
$dbh= DBI->connect("DBI:ODBC:$dsn","$user","$password") || 
  die "Got error $DBI::errstr when connecting to $dsn\n";
@end example

@node Win32 Perl, Perl support problems, ActiveState Perl, Perl support
@subsection Installing the @strong{MySQL} Perl distribution on Win32

The @strong{MySQL} Perl distribution contains @code{DBI},
@code{DBD:MySQL} and @code{DBD:ODBC}.

@itemize @bullet
@item Get the Perl distribution for Win32 from
@uref{http://www.mysql.com/download.html}.
@item Unzip the distribution in @code{C:} so that you get a @file{C:\PERL} directory.
@item Add the directory @file{C:\PERL\BIN} to your path.
@item Add the directory @file{C:\PERL\BIN\MSWin32-x86-thread} or
@file{C:\PERL\BIN\MSWin32-x86} to your path.
@item Test that @code{perl} works by executing @code{perl -v} in a DOS shell.
@end itemize

@node Perl support problems,  , Win32 Perl, Perl support
@subsection Problems using the Perl @code{DBI}/@code{DBD} interface

If Perl reports that it can't find the @code{../mysql/mysql.so} module,
then the problem is probably that Perl can't locate the shared library
@file{libmysqlclient.so}.

You can fix this by any of the following methods:

@itemize @bullet
@item
Compile the @code{Msql-Mysql-modules} distribution with @code{perl
Makefile.PL -static} rather than @code{perl Makefile.PL}

@item
Copy @code{libmysqlclient.so} to the directory where your other shared
libraries are located (probably @file{/usr/lib} or @file{/lib}).

@item
On @code{Linux} you can add the pathname of the directory where
@code{libmysqlclient.so} is located to the @file{/etc/ld.so.conf} file.

@item
@tindex LD_RUN_PATH environment variable
@tindex Environment variable, LD_RUN_PATH
Add the pathname of the directory where @code{libmysqlclient.so} is located
to the @code{LD_RUN_PATH} environment variable.
@end itemize

If you get the following errors from @code{DBD-mysql},
you are probably using @code{gcc} (or using an old binary compiled with
@code{gcc}):

@example
/usr/bin/perl: can't resolve symbol '__moddi3'
/usr/bin/perl: can't resolve symbol '__divdi3'
@end example

Add @code{-L/usr/lib/gcc-lib/... -lgcc} to the link command when the
@file{mysql.so} library gets built (check the output from @code{make} for
@file{mysql.so} when you compile the Perl client).  The @code{-L} option
should specify the pathname of the directory where @file{libgcc.a} is located
on your system.

Another cause of this problem may be that Perl and @strong{MySQL} aren't both
compiled with @code{gcc}.  In this case, you can solve the mismatch by
compiling both with @code{gcc}.

If you want to use the Perl module on a system that doesn't support dynamic
linking (like SCO) you can generate a static version of Perl that includes
@code{DBI} and @code{DBD-mysql}.  The way this works is that you generate a
version of Perl with the @code{DBI} code linked in and install it on top of
your current Perl.  Then you use that to build a version of Perl that
additionally has the @code{DBD} code linked in, and install that.

On SCO, you must have the following environment variables set:

@example
shell> LD_LIBRARY_PATH=/lib:/usr/lib:/usr/local/lib:/usr/progressive/lib
or
shell> LD_LIBRARY_PATH=/usr/lib:/lib:/usr/local/lib:/usr/ccs/lib:/usr/progressive/lib:/usr/skunk/lib
shell> LIBPATH=/usr/lib:/lib:/usr/local/lib:/usr/ccs/lib:/usr/progressive/lib:/usr/skunk/lib
shell> MANPATH=scohelp:/usr/man:/usr/local1/man:/usr/local/man:/usr/skunk/man:
@end example

First, create a Perl that includes a statically-linked @code{DBI} by running
these commands in the directory where your @code{DBI} distribution is
located:

@example
shell> perl Makefile.PL LINKTYPE=static
shell> make
shell> make install
shell> make perl
@end example

Then you must install the new Perl. The output of @code{make perl} will
indicate the exact @code{make} command you will need to execute to perform
the installation.  On SCO, this is @code{make -f Makefile.aperl inst_perl
MAP_TARGET=perl}.

Next, use the just-created Perl to create another Perl that also includes a
statically-linked @code{DBD::mysql} by running these commands in the
directory where your @code{Msql-Mysql-modules} distribution is located:

@example
shell> perl Makefile.PL LINKTYPE=static
shell> make
shell> make install
shell> make perl
@end example

Finally, you should install this new Perl.  Again, the output of @code{make
perl} indicates the command to use.

@node Source install system issues, Win32, Perl support, Installing
@section System-specific issues

The following sections indicate some of the issues that have been observed to
occur on particular systems when installing @strong{MySQL} from a source
distribution.

@menu
* Solaris::                     Solaris notes
* Solaris 2.7::                 Solaris 2.7 notes
* Solaris x86::                 Solaris x86 notes
* SunOS::                       SunOS 4 notes
* Linux::                       Linux notes (all Linux versions)
* Alpha-DEC-Unix::              Alpha-DEC-Unix notes
* Alpha-DEC-OSF1::              Alpha-DEC-OSF1 notes
* SGI-Irix::                    SGI-Irix notes
* FreeBSD::                     FreeBSD notes
* BSDI::                        BSD/OS notes
* SCO::                         SCO notes
* SCO Unixware::                SCO Unixware 7.0 notes
* IBM-AIX::                     IBM-AIX notes
* HP-UX::                       HP-UX notes
@end menu

@node Solaris, Solaris 2.7, Source install system issues, Source install system issues
@subsection Solaris notes

On Solaris, you may run into trouble even before you get the @strong{MySQL}
distribution unpacked!  Solaris @code{tar} can't handle long file names, so
you may see an error like this when you unpack @strong{MySQL}:

@example
x mysql-3.22.12-beta/bench/Results/ATIS-mysql_odbc-NT_4.0-cmp-db2,informix,ms-sql,mysql,oracle,solid,sybase, 0 bytes, 0 tape blocks
tar: directory checksum error
@end example

In this case, you must use GNU @code{tar} (@code{gtar}) to unpack the
distribution.  You can find a precompiled copy for Solaris at
@uref{http://www.mysql.com/Downloads/}.

Sun native threads work only on Solaris 2.5 and higher. For 2.4 and
earlier versions, @strong{MySQL} will automatically use
MIT-pthreads. @xref{MIT-pthreads}.

If you are using Solaris on a SPARC, the recommended compiler is @code{egcs}
1.1.2 or newer.  You can find this at @uref{http://egcs.cygnus.com/}.
Note that @code{egs} 1.1.1 and @code{gcc} 2.8.1 don't work reliably on SPARC!

The recommended @code{configure} line when using @code{egcs} 1.1.2 is:

@example
shell> CC=gcc CFLAGS="-O6" \
       CXX=gcc CXXFLAGS="-O6 -felide-constructors -fno-exceptions -fno-rtti" \
       ./configure --prefix=/usr/local/mysql --with-low-memory
@end example

If you have the Sun Workshop 4.2 compiler, you can run @code{configure} like
this:

@example
shell> CC=cc CFLAGS="-Xa -fast -xstrconst -mt" \
       CXX=CC CXXFLAGS="-xsb -noex -fast -mt" \
       ./configure
@end example

You may also have to edit the @code{configure} script to change this line:

@example
#if !defined(__STDC__) || __STDC__ != 1
@end example

to this:

@example
#if !defined(__STDC__)
@end example

If you turn on @code{__STDC__} with the @code{-Xc} option, the Sun compiler
can't compile with the Solaris @file{pthread.h} header file. This is a Sun
bug (broken compiler or broken include file).

If @code{mysqld} issues the error message shown below when you run it, you have
tried to compile @strong{MySQL} with the Sun compiler without enabling the
multi-thread option (@code{-mt}):

@example
libc internal error: _rmutex_unlock: rmutex not held
@end example

Add @code{-mt} to @code{CFLAGS} and @code{CXXFLAGS} and try again.

If you get the following error when compiling @strong{MySQL} with @code{gcc},
it means that your @code{gcc} is not configured for your version of Solaris!

@example
shell> gcc -O3 -g -O2 -DDBUG_OFF  -o thr_alarm ...
./thr_alarm.c: In function `signal_hand':
./thr_alarm.c:556: too many arguments to function `sigwait'
@end example

The proper thing to do in this case is to get the newest version of
@code{egcs} and compile it with your current @code{gcc} compiler!  At
least for Solaris 2.5, almost all binary versions of @code{gcc} have
old, unusable include files that will break all programs that use
threads (and possibly other programs)!

Solaris doesn't provide static versions of all system libraries
(@code{libpthreads} and @code{libdl}), so you can't compile @strong{MySQL}
with @code{--static}.  If you try to do so, you will get the error:

@example
ld: fatal: library -ldl: not found
@end example

If too many processes try to connect very rapidly to @code{mysqld}, you will
see this error in the @strong{MySQL} log:

@example
Error in accept: Protocol error
@end example

You might try starting the server with the @code{--set-variable back_log=50}
option as a workaround for this.

If you are linking your own @strong{MySQL} client, you might get the
following error when you try to execute it:

@example
ld.so.1: ./my: fatal: libmysqlclient.so.#: open failed: No such file or directory
@end example

The problem can be avoided by one of the following methods:

@itemize @bullet
@item
Link the client with the following flag (instead of @code{-Lpath}):
@code{-Wl,r/full-path-to-libmysqlclient.so}.
@item
Copy @code{libmysqclient.so} to @file{/usr/lib}.
@item
@tindex LD_RUN_PATH environment variable
@tindex Environment variable, LD_RUN_PATH
Add the pathname of the directory where @code{libmysqlclient.so} is located
to the @code{LD_RUN_PATH} environment variable before running your client.
@end itemize

@node Solaris 2.7, Solaris x86, Solaris, Source install system issues
@subsection Solaris 2.7 notes

You can normally use a Solaris 2.6 binary on Solaris 2.7.  Most of the
Solaris 2.6 issues also apply for Solaris 2.7.

Solaris 2.7 has some bugs in the include files. You may see the following
error when you use @code{gcc}:

@example
/usr/include/widec.h:42: warning: `getwc' redefined
/usr/include/wchar.h:326: warning: this is the location of the previous
definition
@end example

If this occurs, you can do the following to fix the problem:

Copy @code{/usr/include/widec.h} to
@code{.../lib/gcc-lib/os/gcc-version/include} and change line 41 from:

@example
#if     !defined(lint) && !defined(__lint)

to

#if     !defined(lint) && !defined(__lint) && !defined(getwc)
@end example

Alternatively, you can edit @file{/usr/include/widec.h} directly.  Either
way, after you make the fix, you should remove @file{config.cache} and run
@code{configure} again!

If you get errors like this when you run @code{make}, it's because @code{configure}
didn't detect the @file{curses.h} file (probably because of the error in
@code{/usr/include/widec.h}:

@example
In file included from mysql.cc:50:
/usr/include/term.h:1060: syntax error before `,'
/usr/include/term.h:1081: syntax error before `;'
@end example

The solution to this is to do one of the following steps:

@itemize @bullet
@item
Edit @file{/usr/include/widec.h} as indicted above and rerun configure
@item
Remove the @code{#define HAVE_TERM} line from @file{config.h} file and
run @code{make} again.
@item
Configure with @code{CFLAGS=-DHAVE_CURSES CXXFLAGS=-DCURSES ./configure}
@end itemize

@node Solaris x86, SunOS, Solaris 2.7, Source install system issues
@subsection Solaris x86 notes

If you are using @code{gcc} or @code{egcs} on Solaris x86 and you
experience problems with core dumps under load, you should use the
following @code{configure} command:

@example
shell> CC=gcc CFLAGS="-O6 -fomit-frame-pointer" \
       CXX=gcc \
       CXXFLAGS="-O6 -fomit-frame-pointer -felide-constructors -fno-exceptions -fno-rtti" \
       ./configure --prefix=/usr/local/mysql
@end example

This will avoid problems with the @code{libstdc++} library and with C++
exceptions.

If this doesn't help, you should compile a debug version and run
it with a trace file or under @code{gdb}.  @xref{Debugging server}.

@node SunOS, Linux, Solaris x86, Source install system issues
@subsection SunOS 4 notes

On SunOS 4, MIT-pthreads is needed to compile @strong{MySQL}, which in turn
means you will need GNU @code{make}.

Some SunOS 4 systems have problems with dynamic libraries and
@code{libtool}. You can use the following @code{configure} line to avoid
this problem:

@example
shell> ./configure --disable-shared --with-mysqld-ldflags=-all-static
@end example

When compiling @code{readline}, you may get warnings about duplicate defines.
These may be ignored.

When compiling @code{mysqld}, there will be some @code{implicit declaration
of function} warnings. These may be ignored.

@node Linux, Alpha-DEC-Unix, SunOS, Source install system issues
@subsection Linux notes (all Linux versions)

@strong{MySQL} uses LinuxThreads on Linux.  If you are using an old Linux
version that doesn't have @code{glibc2}, you must install LinuxThreads before
trying to compile
@strong{MySQL}. @uref{http://www.mysql.com/Downloads/Linux}

If you can't start @code{mysqld} or if @code{mysql_install_db} doesn't work,
please continue reading!  This only happens on Linux system with problems in
the LinuxThreads or @code{libc}/@code{glibc} libraries. There are a lot of
simple workarounds to get @strong{MySQL} to work!  The simplest is to use the
binary version of @strong{MySQL} (not the RPM) for Linux x86.  One nice
aspect of this version is that it's probably 10% faster than any version you
would compile yourself!  @xref{Compile and link options}.

One known problem with the binary distribution is that with older Linux
systems that use @code{libc} (like RedHat 4.x or Slackware), you will get
some non-fatal problems with hostname resolution
@xref{Binary notes-Linux}.

@code{isamchk} hangs with @code{libc.so.5.3.12}. Upgrading to the newest
@code{libc} fixes this problem.

When using LinuxThreads you will see a minimum of three processes
running. These are in fact threads. There will be one thread for the
LinuxThreads manager, one thread to handle connections, and one thread
to handle alarms and signals.

If you see a dead @code{mysqld} daemon process with @code{ps}, this usually
means that you have found a bug in @strong{MySQL} or you have got a corrupted
table. @xref{Crashing}.

If you are using LinuxThreads and @code{mysqladmin shutdown} doesn't work,
you must upgrade to LinuxThreads 0.7.1 or newer.

If you are using RedHat, you might get errors like this:

@example
/usr/bin/perl is needed...
/usr/sh is needed...
/usr/sh is needed...
@end example

If so, you should upgrade your version of @code{rpm} to
@file{rpm-2.4.11-1.i386.rpm} and @file{rpm-devel-2.4.11-1.i386.rpm} (or later).

You can get the upgrades of libraries to RedHat 4.2 from
@uref{ftp://ftp.redhat.com/updates/4.2/i386}. Or
@uref{http://www.sunsite.unc.edu/pub/Linux/distributions/redhat/code/rpm/}
for other distributions.

If you are linking your own @strong{MySQL} client and get the error:

@example
ld.so.1: ./my: fatal: libmysqlclient.so.4: open failed: No such file or directory
@end example

when executing them, the problem can be avoided by one of the following
methods:

@itemize @bullet
@item
Link the client with the following flag (instead of @code{-Lpath}):
@code{-Wl,r/path-libmysqlclient.so}.
@item
Copy @code{libmysqclient.so} to @file{/usr/lib}.
@item
@tindex LD_RUN_PATH environment variable
@tindex Environment variable, LD_RUN_PATH
Add the pathname of the directory where @code{libmysqlclient.so} is located
to the @code{LD_RUN_PATH} environment variable before running your client.
@end itemize

@menu
* Linux-x86::                   Linux-x86 notes
* Linux-RedHat50::              RedHat 5.0 notes
* Linux-RedHat51::              RedHat 5.1 notes
* Linux-SPARC::                 Linux-SPARC notes
* Linux-Alpha::                 Linux-Alpha notes
* MKLinux::                     MkLinux notes
@end menu

@node Linux-x86, Linux-RedHat50, Linux, Linux
@subsubsection Linux-x86 notes

@strong{MySQL} requires @code{libc} version 5.4.12 or newer. It's known to
work with @code{libc} 5.4.46. @code{glibc} version 2.0.6 and later should
also work. There have been some problems with the @code{glibc} RPMs from
RedHat so if you have problems, check whether or not there are any updates!
The @code{glibc} 2.0.7-19 and 2.0.7-29 RPMs are known to work.

On some older Linux distributions, @code{configure} may produce an error
like this:

@example
Syntax error in sched.h. Change _P to __P in the /usr/include/sched.h file.
See the Installation chapter in the Reference Manual.
@end example

Just do what the error message says and add an extra underscore to the
@code{_P} macro that has only one underscore, then try again.

You may get some warnings when compiling; those shown below can be ignored:

@example
mysqld.cc -o objs-thread/mysqld.o
mysqld.cc: In function `void init_signals()':
mysqld.cc:315: warning: assignment of negative value `-1' to `long unsigned int'
mysqld.cc: In function `void * signal_hand(void *)':
mysqld.cc:346: warning: assignment of negative value `-1' to `long unsigned int'
@end example

In Debian GNU/Linux, if you want @strong{MySQL} to start automatically when
the system boots, do the following:

@example
shell> cp support-files/mysql.server /etc/init.d/mysql.server
shell> /usr/sbin/update-rc.d mysql.server defaults 99
@end example

@code{mysql.server} can be found in the @file{share/mysql} directory
under the @strong{MySQL} installation directory, or in the
@file{support-files} directory of the @strong{MySQL} source tree.

If @code{mysqld} always core dumps when it starts up, the problem may be that
you have an old @file{/lib/libc.a}.  Try renaming it, then remove
@file{sql/mysqld} and do a new @code{make install} and try again.  This
problem has been reported on some Slackware installations. RedHat 5.0 has
also a similar problem with some new @code{glibc} versions.
@xref{Linux-RedHat50}.

If you get the following error when linking @code{mysqld},
it means that your @file{libg++.a} is not installed correctly:

@example
/usr/lib/libc.a(putc.o): In function `_IO_putc':
putc.o(.text+0x0): multiple definition of `_IO_putc'
@end example

You can avoid using @file{libg++.a} by running @code{configure} like this:

@example
shell> CXX=gcc ./configure
@end example

@node Linux-RedHat50, Linux-RedHat51, Linux-x86, Linux
@subsubsection RedHat 5.0 notes

If you have any problems with @strong{MySQL} on RedHat, you should start by
upgrading @code{glibc} to the newest possible version!

If you install all the official RedHat patches (including
@code{glibc-2.0.7-19} and @code{glibc-devel-2.0.7-19}), both the
binary and source distributions of @strong{MySQL} should work without
any trouble!

The updates are needed since there is a bug in @code{glibc} 2.0.5 in how
@code{pthread_key_create} variables are freed. With @code{glibc} 2.0.5, you
must use a statically-linked @strong{MySQL} binary distribution. If you
want to compile from source, you must install the corrected version of
LinuxThreads from @uref{http://www.mysql.com/Downloads/Linux} or upgrade your
@code{glibc}.

If you have an incorrect version of @code{glibc} or LinuxThreads, the symptom
is that @code{mysqld} crashes after each connection. For example,
@code{mysqladmin version} will crash @code{mysqld} when it finishes!

Another symptom of incorrect libraries is that @code{mysqld} crashes at
once when it starts. On some Linux systems, this can be fixed by configuring
like this:

@example
shell> ./configure --with-mysqld-ldflags=-all-static
@end example

On Redhat 5.0, the easy way out is to install the @code{glibc} 2.0.7-19 RPM
and run @code{configure} @strong{without} the
@code{--with-mysqld-ldflags=-all-static} option.

For the source distribution of @code{glibc} 2.0.7, a patch that is easy to
apply and is tested with @strong{MySQL} may be found at:
@example
@uref{http://www.mysql.com/Download/Linux/glibc-2.0.7-total-patch.tar.gz}
@end example

If you experience crashes like these when you build @strong{MySQL}, you can
always download the newest binary version of @strong{MySQL}.  This is
statically-linked to avoid library conflicts and should work on all Linux
systems!

@strong{MySQL} comes with an internal debugger that can generate
trace files with a lot of information that can be used to find and solve a
wide range of different problems.
@xref{Debugging server}.

@node Linux-RedHat51, Linux-SPARC, Linux-RedHat50, Linux
@subsubsection RedHat 5.1 notes

The @code{glibc} of RedHat 5.1 (@code{glibc} 2.0.7-13) has a memory leak, so
to get a stable @strong{MySQL} version, you must upgrade @code{glibc} to
2.0.7-19, downgrade @code{glibc} or use a binary version of @code{mysqld}. If
you don't do this, you will encounter memory problems (out of memory, etc.,
etc.).  The most common error in this case is:

@example
Can't create a new thread (errno 11). If you are not out of available
memory, you can consult the manual for any possible OS dependent bug
@end example

After you have upgraded to @code{glibc} 2.0.7-19, you can configure
@strong{MySQL} with dynamic linking (the default), but you @strong{cannot}
run @code{configure} with the @code{--with-mysqld-ldflags=-all-static} option
until you have installed @code{glibc} 2.0.7-19 from source!

You can check which version of @code{glibc} you have with @code{rpm -q glibc}.

@node Linux-SPARC, Linux-Alpha, Linux-RedHat51, Linux
@subsubsection Linux-SPARC notes

In some implementations, @code{readdir_r()} is broken.  The symptom is that
@code{SHOW DATABASES} always returns an empty set.  This
can be fixed by removing @code{HAVE_READDIR_R} from @file{config.h} after
configuring and before compiling.

Some problems will require patching your Linux installation.  The patch can
be found at
@uref{http://www.mysql.com/patches/Linux-sparc-2.0.30.diff}. This patch is
against the Linux distribution @file{sparclinux-2.0.30.tar.gz} that is
available at @code{vger.rutgers.edu} (a version of Linux that was
never merged with the official 2.0.30).  You must also install
LinuxThreads 0.6 or newer.

Thanks to @email{jacques@@solucorp.qc.ca} for this information.

@node Linux-Alpha, MKLinux, Linux-SPARC, Linux
@subsubsection Linux-Alpha notes

The big problem on Linux-Alpha is that there is still some problems with
threads in glibc on this platform.  You should start by getting the
newest glibc version you can find.

Note that before you run any programs that uses thread (like mysqld,
thr_alarm or thr_lock), you should raise the shared memory limit (with
ulimit). The @strong{MySQL} benchmarks are known to fail if you forget
to do this!


Configure @strong{MySQL} with the following command:

@example
shell> CC=gcc CCFLAGS="-Dalpha_linux_port" \
       CXX=gcc CXXFLAGS="-O3 -Dalpha_linux_port -felide-constructors -fno-exceptions -fno-rtti" \
       ./configure --prefix=/usr/local/mysql
@end example

Try to compile @code{mysys/thr_lock} and @code{mysys/thr_alarm}.
Test that these programs work!  (Invoke each one with no arguments.
Each should end with @code{test_succeeded} if everything
was okay.)

After installing @strong{MySQL}, uncomment the @code{ulimit} command in
@code{safe_mysqld} and add options to increase share memory.

Note that Linux-Alpha is still an alpha-quality platform for @strong{MySQL}.
With the newest glibc, you have a very good chance of it working.

If you have problems with signals (@strong{MySQL} dies unexpectedly
under high load) you may have found an OS bug with threads and
signals. In this case you can tell @strong{MySQL} not to use signals by
configuring with:

@example
shell> CFLAGS=-DDONT_USE_THR_ALARM \
       CXXFLAGS=-DDONT_USE_THR_ALARM \
       ./configure ...
@end example

This doesn't affect the performance of @strong{MySQL}, but has the side
effect that you can't kill clients that are ``sleeping'' on a connection with
@code{mysqladmin kill} or @code{mysqladmin shutdown}.  Instead, the client
will die when it issues its next command.

@node MKLinux,  , Linux-Alpha, Linux
@subsubsection MkLinux notes

@strong{MySQL} should work on MkLinux with the newest @code{glibc} package
(tested with @code{glibc} 2.0.7).

@node Alpha-DEC-Unix, Alpha-DEC-OSF1, Linux, Source install system issues
@subsection Alpha-DEC-Unix notes

When compiling threaded programs under Digital UNIX, the documentation
recommends using the @code{-pthread} option for @code{cc} and @code{cxx} and
the libraries @code{-lmach -lexc} (in addition to @code{-lpthread}).  You
should run @code{configure} something like this:

@example
shell> CC="cc -pthread" CXX="cxx -pthread -O" \
       ./configure --with-named-thread-libs="-lpthread -lmach -lexc -lc"
@end example

When compiling @code{mysqld}, you may see a couple of warnings like this:

@example
mysqld.cc: In function void handle_connections()':
mysqld.cc:626: passing long unsigned int *' as argument 3 of
accept(int,sockadddr *, int *)'
@end example

You can safely ignore these warnings. They occur because @code{configure}
can detect only errors, not warnings.

If you start the server directly from the command line, you may have problems
with it dying when you log out.  (When you log out, your outstanding processes
receive a @code{SIGHUP} signal.)  If so, try starting the server like this:

@example
shell> nohup mysqld [options] &
@end example

@code{nohup} causes the command following it to ignore any @code{SIGHUP}
signal sent from the terminal.  Alternatively, start the server by running
@code{safe_mysqld}, which invokes @code{mysqld} using @code{nohup} for you.

@node Alpha-DEC-OSF1, SGI-Irix, Alpha-DEC-Unix, Source install system issues
@subsection Alpha-DEC-OSF1 notes

If you have problems compiling and have DEC @code{CC} and @code{gcc}
installed, try running @code{configure} like this:

@example
shell> CC=cc CFLAGS=-O CXX=gcc CXXFLAGS=-O3 \
       ./configure --prefix=/usr/local/mysql
@end example

If you get problems with the @file{c_asm.h} file, you can create and use a 'dummy'
@file{c_asm.h} file with:

@example
shell> touch include/c_asm.h
shell> CC=gcc CFLAGS=-I./include \
       CXX=gcc CXXFLAGS=-O3 \
       ./configure --prefix=/usr/local/mysql
@end example

On OSF1 V4.0D and compiler "DEC C V5.6-071 on Digital UNIX V4.0 (Rev. 878)"
the compiler had some strange behavior (undefined @code{asm} symbols).
@code{/bin/ld} also appears to be broken (problems with @code{_exit
undefined} errors occuring while linking @code{mysqld}).  On this system, we
have managed to compile @strong{MySQL} with the following @code{configure}
line, after replacing @code{/bin/ld} with the version from OSF 4.0C:

@example
shell> CC=gcc CXX=gcc CXXFLAGS=-O3 ./configure --prefix=/usr/local/mysql
@end example

In some versions of OSF1, the @code{alloca()} function is broken. Fix
this by removing the line in @file{config.h} that defines @code{'HAVE_ALLOCA'}.

The @code{alloca()} function also may have an incorrect prototype in
@code{/usr/include/alloca.h}.  This warning resulting from this can be ignored.

@code{configure} will use the following thread libraries automatically:
@code{--with-named-thread-libs="-lpthread -lmach -lexc -lc"}.

When using @code{gcc}, you can also try running @code{configure} like this:

@example
shell> CFLAGS=-D_PTHREAD_USE_D4 CXX=gcc CXXFLAGS=-O3 ./configure ....
@end example

If you have problems with signals (@strong{MySQL} dies unexpectedly
under high load) you may have found an OS bug with threads and
signals. In this case you can tell @strong{MySQL} not to use signals by
configuring with:

@example
shell> CFLAGS=-DDONT_USE_THR_ALARM \
       CXXFLAGS=-DDONT_USE_THR_ALARM \
       ./configure ...
@end example

This doesn't affect the performance of @strong{MySQL}, but has the side
effect that you can't kill clients that are ``sleeping'' on a connection with
@code{mysqladmin kill} or @code{mysqladmin shutdown}.  Instead, the client
will die when it issues its next command.

@node SGI-Irix, FreeBSD, Alpha-DEC-OSF1, Source install system issues
@subsection SGI-Irix notes

You may have to undefine some things in @file{config.h} after running
@code{configure} and before compiling.

In some Irix implementations, the @code{alloca()} function is broken. If the
@code{mysqld} server dies on some @code{SELECT} statements, remove the lines
from @file{config.h} that define @code{HAVE_ALLOC} and @code{HAVE_ALLOCA_H}.
If @code{mysqladmin create} doesn't work, remove the line from
@file{config.h} that defines @code{HAVE_READDIR_R}. You may have to remove
the @code{HAVE_TERM_H} line as well.

SGI recommends that you install all of the patches on this page as a set:
http://support.sgi.com/surfzone/patches/patchset/6.2_indigo.rps.html

At the very minimum, you should install the latest kernel rollup, the
latest @code{rld} rollup, and the latest @code{libc} rollup.

You definately need all the POSIX patches on this page, for pthreads support:

http://support.sgi.com/surfzone/patches/patchset/6.2_posix.rps.html

If you get the something like the following error when compiling
@file{mysql.cc}:

@example
"/usr/include/curses.h", line 82: error(1084): invalid combination of type
@end example

Then type the following in the top-level directory of your @strong{MySQL}
source tree:

@example
shell> extra/replace bool curses_bool < /usr/include/curses.h > include/curses.h
shell> make
@end example

There have also been reports of scheduling problems.  If only one thread is
running, things go slow. Avoid this by starting another client. This may lead
to a 2-to-10-fold increase in execution speed thereafter for the other
thread.  This is a poorly-understood problem with Irix threads; you may have
to improvise to find solutions until this can be fixed.

If you are compiling with @code{gcc}, you can use the following
@code{configure} command:

@example
shell> CC=gcc CXX=gcc CXXFLAGS=-O3 \
       ./configure --prefix=/usr/local/mysql --with-thread-safe-client --with-named-thread-libs=-lpthread
@end example

@node FreeBSD, BSDI, SGI-Irix, Source install system issues
@subsection FreeBSD notes

If you notice that @code{configure} will use MIT-pthreads, you should read
the MIT-pthreads notes. @xref{MIT-pthreads}.

If you get an error from @code{make install} that it can't find
@file{/usr/include/pthreads}, @code{configure} didn't detect that you need
MIT-pthreads. This is fixed by executing these commands:

@example
shell> rm config.cache
shell> ./configure --with-mit-threads
@end example

The behavior of FreeBSD @code{make} is slightly different from that of GNU
@code{make}. If you have @code{make}-related problems, you should install GNU
@code{make}.

If @code{mysql} or @code{mysqladmin} takes a long time to respond, a user
said the following:

Are you running the @code{ppp} user process? On one FreeBSD box (2.2.5)
@strong{MySQL}
clients takes a couple of seconds to connect to @code{mysqld} if the @code{ppp}
process is running.

FreeBSD is also known to have a very low default file handle limit.
@xref{Not enough file handles}.

@cindex Timezone problems
@tindex TZ environment variable
@tindex Environment variable, TZ
If you have a problem with @code{SELECT NOW()} returning values in GMT and
not your local time, you have to set the @code{TZ} environment variable to
your current timezone.  This should be done for the environment in which
the server runs, for example, in @code{safe_mysqld} or @code{mysql.server}.

Make sure that the @code{localhost} entry in the @file{/etc/hosts} file is
correct (otherwise you will have problems connecting to the database).  The
@file{/etc/hosts} file should start with a line:

@example
127.0.0.1       localhost localhost.your.domain
@end example

If you are using FreeBSD 2.2.6, don't forget to apply the ttcp and mmap-22
patches to the OS (for security reasons).  Please see
@uref{http://www.freebsd.org} for these CERT patches.

If you are using FreeBSD 2.2.7 and you have problems killing the @code{mysqld}
daemon, you should get new sources using @code{cvsup} and recompile
@code{libc_r}.

@menu
* FreeBSD-3.0::                 FreeBSD-3.0 notes
@end menu

@node FreeBSD-3.0,  , FreeBSD, FreeBSD
@subsubsection FreeBSD-3.0 notes

You have to run @code{configure} with the
@code{--with-named-thread-libs=-lc_r} option.

The pthreads library for FreeBSD doesn't contain the @code{sigwait()}
function and there are some bugs in it.  To fix this, get the
@file{FreeBSD-3.0-libc_r-1.0.diff} file from the
@uref{ftp://www.mysql.com/pub/mysql/Downloads/FreeBSD,FreeBSD area} of the
@strong{MySQL} FTP site and apply it in the
@file{/usr/src/lib/libc_r/uthread} directory. Then follow the instructions
that can be found with @code{man pthread} about how to recompile the
@code{libc_r} library.

You can test if you have a ``modern'' @code{libpthread.a} with this command:

@example
shell> nm /usr/lib/libc_r.a | grep sigwait
@end example

If the above doesn't find @code{sigwait}, you must use the patch above
and recompile @code{libc_r}.

@node BSDI, SCO, FreeBSD, Source install system issues
@subsection BSD/OS notes

@menu
* BSDI2::                       BSD/OS 2.x notes
* BSDI3::                       BSD/OS 3.x notes
* BSDI4::                       BSD/OS 4.x notes
@end menu

@node BSDI2, BSDI3, BSDI, BSDI
@subsubsection BSD/OS 2.x notes

If you get the following error when compiling @strong{MySQL}, your
@code{ulimit} value for virtual memory is too low:

@example
item_func.h: In method `Item_func_ge::Item_func_ge(const Item_func_ge &)':
item_func.h:28: virtual memory exhausted
make[2]: *** [item_func.o] Error 1
@end example

Try using @code{ulimit -v 80000} and run @code{make} again.  If this
doesn't work and you are using @code{bash}, try switching to @code{csh}
or @code{sh}; some BSDI users have reported problems with @code{bash}
and @code{ulimit}.

If you are using @code{gcc}, you may also use have to use the
@code{--with-low-memory} flag for @code{configure} to be able to compile
@file{sql_yacc.cc}.

@cindex Timezone problems
@tindex TZ environment variable
@tindex Environment variable, TZ
If you have a problem with @code{SELECT NOW()} returning values in GMT and
not your local time, you have to set the @code{TZ} environment variable to
your current timezone.  This should be done for the environment in which
the server runs, for example in @code{safe_mysqld} or @code{mysql.server}.

@node BSDI3, BSDI4, BSDI2, BSDI
@subsubsection BSD/OS 3.x notes

Upgrade to BSD/OS 3.1. If that is not possible, install BSDIpatch M300-038.

Use the following command when configuring @strong{MySQL}:

@example
shell> env CXX=shlicc++ CC=shlicc2 \
       ./configure \
           --prefix=/usr/local/mysql \
           --localstatedir=/var/mysql \
           --without-perl \
           --with-unix-socket-path=/var/mysql/mysql.sock
@end example

The following is also known to work:

@example
shell> env CC=gcc CXX=gcc CXXFLAGS=-O3 \
       ./configure \
           --prefix=/usr/local/mysql \
           --with-unix-socket-path=/var/mysql/mysql.sock
@end example

You can change the directory locations if you wish, or just use the
defaults by not specifying any locations.

If you have problems with performance under heavy load, try using the
@code{--skip-thread-priority} option to @code{safe_mysqld}!  This will run
all threads with the same priority; on BSDI 3.1, this gives better
performance (at least until BSDI fixes their thread scheduler).

If you get the error @code{virtual memory exhausted} while compiling,
you should try using @code{ulimit -v 80000} and run @code{make} again.
If this doesn't work and you are using @code{bash}, try switching to
@code{csh} or @code{sh}; some BSDI users have reported problems with
@code{bash} and @code{ulimit}.

@node BSDI4,  , BSDI3, BSDI
@subsubsection BSD/OS 4.x notes

BSDI 4.x has some thread related bugs.  If you want to use @strong{MySQL}
on this, you should install all thread related patches. At least
M400-023 should be installed.

@node SCO, SCO Unixware, BSDI, Source install system issues
@subsection SCO notes

The current port is tested only on a ``sco3.2v5.0.4'' and
``sco3.2v5.0.5'' system.  There has also been a lot of progress on a
port to ``sco 3.2v4.2''.

@enumerate
@item
For OpenServer 5.0.X you need to use GDS in Skunkware 95 (95q4c).  This
is necessary because GNU @code{gcc} 2.7.2 in Skunkware 97 does not have
GNU @code{as}.  You can also use @code{egcs} 1.1.2 or newer
@uref{http://www.egcs.com}.  If you are using @code{egcs} 1.1.2 you have
to execute the following command:

@example
cp -p /usr/include/pthread/stdtypes.h /usr/local/lib/gcc-lib/i386-pc-sco3.2v5.0.5/egcs-2.91.66/include/pthread/
@end example
@item
You need the port of GCC 2.5.? for this product and the Development
system.  They are required on this version of SCO UNIX.  You cannot
just use the GCC Dev system.
@item
You should get the FSU Pthreads package and install it first.  This can be
found at
@uref{http://www.cs.wustl.edu/~schmidt/ACE_wrappers/FSU-threads.tar.gz}.
You can also get a precompiled package from
@uref{ftp://www.mysql.com/pub/mysql/Downloads/SCO/FSU-threads-3.5c.tar.gz}.
@item
FSU Pthreads can be compiled with SCO UNIX 4.2 with tcpip.  Or
OpenServer 3.0 or Open Desktop 3.0 (OS 3.0 ODT 3.0), with the SCO
Development System installed using a good port of GCC 2.5.X ODT or OS
3.0 you will need a good port of GCC 2.5.? There are a lot of problems
without a good port.  The port for this product requires the SCO UNIX
Development system.  Without it, you are missing the libraries and the
linker that is needed.
@item
To build FSU Pthreads on your system, do the following:
@enumerate
@item
Run @code{./configure} in the @file{threads/src} directory and select
the SCO OpenServer option. This command copies @file{Makefile.SCO5} to
@file{Makefile}.
@item
Run @code{make}.
@item
To install in the default @file{/usr/include} directory, login as root,
then @code{cd} to the @file{thread/src} directory, and run @code{make
install}.
@end enumerate
@item
Remember to use GNU @code{make} when making @strong{MySQL}.
@item
On OSR 5.0.5, you should use the following configure line:
@example
shell> CC="gcc -DSCO" CXX="gcc -DSCO" ./configure
@end example
The @code{-DSCO} is needed to help configure detect some thread
functions properly.  If you forget @code{-DSCO}, you will get the following
error message while compiling:
@example
my_pthread.c: In function `my_pthread_mutex_init':
my_pthread.c:374: `pthread_mutexattr_default' undeclared (first use this function)
@end example
@item
If you don't start @code{safe_mysqld} as root, you probably will get only the
default 110 open files per process.  @code{mysqld} will write a note about this
in the log file.
@item
With SCO 3.2V5.0.5, you should use a FSU Pthreads version 3.5c or newer.
The following @code{configure} command should work:
@example
shell> CC="gcc -belf" ./configure --prefix=/usr/local/mysql --disable-shared
@end example
@item
With SCO 3.2V4.2, you should use a FSU Pthreads version 3.5c or newer.
The following @code{configure} command should work:
@example
shell> CFLAGS="-D_XOPEN_XPG4" CXX=gcc CXXFLAGS="-D_XOPEN_XPG4" \
       ./configure \
           --with-debug --prefix=/usr/local/mysql \
           --with-named-thread-libs="-lgthreads -lsocket -lgen -lgthreads" \
           --with-named-curses-libs="-lcurses"
@end example
You may get some problems with some include files. In this case, you can
find new SCO-specific include files at
@uref{ftp://www.mysql.com/pub/mysql/Downloads/SCO/SCO-3.2v4.2-includes.tar.gz}.
You should unpack this file in the @file{include}
directory of your @strong{MySQL} source tree.
@end enumerate

SCO development notes:

@itemize @bullet
@item
@strong{MySQL} should automatically detect FSU Pthreads and link @code{mysqld}
with @code{-lgthreads -lsocket -lgthreads}.
@item
The SCO development libraries are reentrant in FSU Pthreads. SCO claims
that its libraries' functions are reentrant, so they must be reentrant with
FSU Pthreads. FSU Pthreads on OpenServer tries to use the SCO scheme to
make reentrant library.
@item
FSU Pthreads (at least the version at @code{www.mysql.com}) comes linked with
GNU @code{malloc}.  If you encounter problems with memory usage, make sure that
@file{gmalloc.o}
is included in @file{libgthreads.a} and @file{libgthreads.so}.
@item
In FSU Pthreads, the following system calls are pthreads-aware: @code{read()},
@code{write()}, @code{getmsg()}, @code{connect()}, @code{accept()},
@code{select()} and @code{wait()}.
@end itemize

If you want to install DBI on SCO, you have to edit the @file{Makefiles} in
DBI-xxx and each subdirectory:

@example
OLD:                                  NEW:
CC = cc                               CC = gcc -belf
CCCDLFLAGS = -KPIC -W1,-Bexport       CCCDLFLAGS = -fpic
CCDLFLAGS = -wl,-Bexport              CCDLFLAGS =

LD = ld                               LD = gcc -belf -G -fpic
LDDLFLAGS = -G -L/usr/local/lib       LDDLFLAGS = -L/usr/local/lib
LDFLAGS = -belf -L/usr/local/lib      LDFLAGS = -L/usr/local/lib

LD = ld                               LD = gcc -belf -G -fpic
OPTIMISE = -Od         		      OPTIMISE = -O1

OLD:
CCCFLAGS = -belf -dy -w0 -U M_XENIX -DPERL_SCO5 -I/usr/local/include

NEW:
CCFLAGS = -U M_XENIX -DPERL_SCO5 -I/usr/local/include
@end example

This is because the Perl dynaloader will not load the @code{DBI} modules
if they were compiled with @code{icc} or @code{cc}.

Perl works best when compiled with @code{cc}.

@node SCO Unixware, IBM-AIX, SCO, Source install system issues
@subsection SCO Unixware 7.0 notes

You must use a version of @strong{MySQL} at least as recent as 3.22.13, since
that version fixes some portability problems under Unixware.

We have been able to compile @strong{MySQL} with the following @code{configure}
command on UnixWare 7.0.1:

@example
shell> CC=cc CXX=CC ./configure --prefix=/usr/local/mysql
@end example

@node IBM-AIX, HP-UX, SCO Unixware, Source install system issues
@subsection IBM-AIX notes

Automatic detection of @code{xlC} is missing from Autoconf, so a
@code{configure} command something like this is needed when using the IBM
compiler:

@example
shell> CC="xlc_r -ma -O3 -qstrict" \
       CXX="xlC_r -ma -O3 -qstrict" \
       ./configure
@end example

If you are using @code{egcs} to compile @strong{MySQL}, you
@strong{MUST} use the @code{-fno-exceptions} flag, as the exception
handling in @code{egcs} is not thread-safe!  (This is tested with
@code{egcs} 1.1.)  We recommend the following @code{configure} line with
@code{egcs} and @code{gcc} on AIX:

@example
shell> CXX=gcc \
       CXXFLAGS="-felide-constructors -fno-exceptions -fno-rtti" \
       ./configure --prefix=/home/monty --with-debug --with-low-memory
@end example

If you have problems with signals (@strong{MySQL} dies unexpectedly
under high load) you may have found an OS bug with threads and
signals. In this case you can tell @strong{MySQL} not to use signals by
configuring with:

@example
shell> CFLAGS=-DDONT_USE_THR_ALARM CXX=gcc \
       CXXFLAGS="-felide-constructors -fno-exceptions -fno-rtti -DDONT_USE_THR_ALARM" \
       ./configure --prefix=/home/monty --with-debug --with-low-memory
@end example

This doesn't affect the performance of @strong{MySQL}, but has the side
effect that you can't kill clients that are ``sleeping'' on a connection with
@code{mysqladmin kill} or @code{mysqladmin shutdown}.  Instead, the client
will die when it issues its next command.

@node HP-UX,  , IBM-AIX, Source install system issues
@subsection HP-UX notes

There are a couple of ``small'' problems when compiling @strong{MySQL} on
HP-UX.  We recommend that you use @code{gcc} instead of the HP-UX native
compiler, because @code{gcc} produces better code!

@code{gcc} 2.8.0 can't compile @code{readline} on HP-UX (an internal
compiler error occurs) if you are compiling with @code{-O6}.  On the
other hand, MIT-pthreads can't be compiled with the HP-UX compiler,
because it can't compile @code{.S} (assembler) files.  We got
@strong{MySQL} to compile on HP-UX 10.20 by doing the following:

@example
shell> CC=gcc CXX=gcc \
       ./configure --prefix=/usr/local/mysql --with-low-memory
shell> cd readline
shell> edit Makefile and change -O6 to something lower
shell> cd ..
shell> make
shell> make install
shell> scripts/mysql_install_db
shell> /usr/local/mysql/bin/safe_mysqld &
@end example

@node Win32, OS/2, Source install system issues, Installing
@section Win32 notes

This section describes installation and use of @strong{MySQL} on Win32.  This
is also described in the @file{README} file that comes with the
@strong{MySQL} Win32 distribution.

@menu
* Win32 installation::          Installing @strong{MySQL} on Win32
* Win95 start::                 Starting @strong{MySQL} on Win95 / Win98
* NT start::                    Starting @strong{MySQL} on NT
* Win32 running::               Running @strong{MySQL} on Win32
* Win32 and SSH::               Connecting to a remote @strong{MySQL} from Win32 with SSH
* Win32 vs. Unix::              @strong{MySQL}-Win32 compared to Unix @strong{MySQL}
@end menu

@node Win32 installation, Win95 start, Win32, Win32
@subsection Installing @strong{MySQL} on Win32

If you don't have a registered version of @strong{MySQL}, you should first
download the shareware version from:

@uref{http://www.mysql.com/mysql_w32.htmy,@strong{MySQL} 3.21.29}

If you plan to connect to @strong{MySQL} from some other program, you will
probably also need the @strong{MyODBC} driver. You can find this at:

@uref{http://www.mysql.com/download.htmy,@strong{MySQL} download page}

To install either distribution, unzip it in some empty directory and run the
@code{Setup.exe} program.

Installation takes place in @file{C:\mysql}.

@node Win95 start, NT start, Win32 installation, Win32
@subsection Starting @strong{MySQL} on Win95 / Win98

@strong{MySQL} uses TCP/IP to connect a client to a server. (This will
allow any machine on your network to connect to your @strong{MySQL}
server). Because of this, you must install TCP/IP on your machine before
starting @strong{MySQL}.  You can find TCP/IP on your Windows CD-ROM.

Note that if you are using an old Win95 release (for example OSR2), it's
likely that you have an old Winsock package!  @strong{MySQL} requires Winsock
2!  You can get the newest Winsock from @uref{http://www.microsoft.com,Microsoft}.
Win98 has as default the new Winsock 2 library, so the above doesn't apply
for Win98.

There are 2 different @strong{MySQL} servers you can use:

@multitable @columnfractions .15 .85
@item @code{mysqld} @tab Compiled with full debugging and automatic memory allocation checking
@item @code{mysqld-opt} @tab Optimized for a Pentium processor.
@end multitable

Both of the above should work on any Intel processor >= i386.

To start the @code{mysqld} server, you should start a MS-DOS window and type:

@example
C:\mysql\bin\mysqld
@end example

This will start @code{mysqld} in the background without a window.

You can kill the @strong{MySQL} server by executing:

@example
C:\mysql\bin\mysqladmin -u root shutdown
@end example

Note that Win95/Win98 don't support creation of named pipes.  On
Win95/Win98, you can only use named pipes to connect to a remote
@strong{MySQL} running on an NT server.

@node NT start, Win32 running, Win95 start, Win32
@subsection Starting @strong{MySQL} on NT

The Win95/Win98 section also applies to @strong{MySQL} on NT, with the
following differences:

To get @strong{MySQL} to work with TCP/IP, you must install service pack 3
(or newer)! 

For NT, the server name is @code{mysqld-nt}.  Normally you should install
@strong{MySQL} as a service on NT:

@example
C:\mysql\bin\mysqld-nt --install
@end example

(You could use the @code{mysqld} or @code{mysqld-opt} servers on NT,
but those cannot be started as a service or use named pipes.)

You can start and stop the @strong{MySQL} service with:

@example
NET START mysql
NET STOP mysql
@end example

Note that in this case you can't use any other options for @code{mysqld-nt}!

You can also run @code{mysqld-nt} as a standalone program on NT if you need
to start @code{mysqld-nt} with any options!  If you start @code{mysqld-nt}
without options on NT, @code{mysqld-nt} tries to starts itself as a service
with the default service options.  If you have stopped @code{mysqld-nt}, you
have to start it with @code{NET START mysql}.

The service is installed with the name @code{MySql}. Once installed, it must
be started using Services Control Manager (SCM) Utility (found in Control
Panel) or by using the @code{NET START MySQL} command. If any options are
desired, they must be specified as "Startup parameters" in the SCM utility
before you start the @strong{MySQL} service.  Once running, @code{mysqld-nt}
can be stopped using @code{mysqladmin} or from the SCM utility or by using
the command @code{NET STOP MySQL}. If you use SCM to stop @code{mysqld-nt},
there is a strange message from SCM about @code{mysqld shutdown normally}.
When run as a service, @code{mysqld-nt} has no access to a console and so no
messages can be seen.

On NT you can get the following service error messages:

@multitable @columnfractions .3 .7
@item Permission Denied @tab Means that it cannot find @code{mysqld-nt.exe}
@item Cannot Register   @tab Means that the path is incorrect
@end multitable

If you have problems installing @code{mysqld-nt} as a service, try starting
it with the full path:

@example
C:\mysql\bin\mysqld --install
@end example

If this doesn't work, you can get @code{mysqld-nt} to start properly by fixing
the path in the registry!

If you don't want to start @code{mysqld-nt} as a service, you can start it as
follows:

@example
C:\mysql\bin\mysqld-nt --standalone
@end example

or

@example
C:\mysql\bin\mysqld-nt --standalone --debug
@end example

The last version gives you a debug trace in @file{C:\mysqld.trace}.

@node Win32 running, Win32 and SSH, NT start, Win32
@subsection Running @strong{MySQL} on Win32

@strong{MySQL} supports TCP/IP on all Win32 platforms and named pipes on NT.
The default is to use named pipes for local connections on NT and TCP/IP for
all other cases if the client has TCP/IP installed.  The host name specifies
which protocol is used:

@multitable @columnfractions .3 .7
@strong{Host name} @tab @strong{protocol}
@item NULL (none) @tab  On NT, try named pipes first; if that doesn't work, use TCP/IP. On Win95/Win98, TCP/IP is used.
@item . @tab Named pipes
@item localhost @tab TCP/IP to current host
@item hostname  @tab TCP/IP
@end multitable

You can force a @strong{MySQL} client to use named pipes by specifying the
@code{--pipe} option.  Use the @code{--socket} option to specify the name of
the pipe.

You can test whether or not @strong{MySQL} is working by executing the
following commands:

@example
C:\mysql\bin\mysqlshow
C:\mysql\bin\mysqlshow -u root mysql
C:\mysql\bin\mysqladmin version status proc
C:\mysql\bin\mysql test
@end example

By default, @strong{MySQL}-Win32 is configured to be installed in
@file{C:\mysql}.  If you want to install @strong{MySQL} elsewhere, install it
in @file{C:\mysql}, then move the installation to where you want it.  If you
do move @strong{MySQL}, you must tell @code{mysqld} where everything is by
supplying options to @code{mysqld}. Use @code{C:\mysql\bin\mysqld --help} to
display all options!  If, for example, you have moved the @strong{MySQL}
distribution to @file{D:\programs\mysql}, you must start @code{mysqld} with:
@code{D:\programs\mysql\bin\mysqld --basedir D:\programs\mysql}

With the registered version of @strong{MySQL}, you can also create a
@file{C:\my.cnf} file that holds any default options for the
@strong{MySQL} server.  Copy the file @file{\mysql\my-example.cnf} to
@file{C:\my.cnf} and edit this to suit your setup.
@xref{Option files}.

If @code{mysqld} is slow to answer to connections on Win95/Win98, there is
probably a problem with your DNS. In this case, start @code{mysqld} with
@code{--skip-name-resolve} and use only @code{localhost} and IP numbers in
the @strong{MySQL} grant tables.  You can also avoid DNS when connecting to a
@code{mysqld-nt} @strong{MySQL} server running on NT by using the
@code{--pipe} argument to specify use of named pipes.  This works for most
@strong{MySQL} clients.

There are two versions of the @strong{MySQL} command line tool:
@multitable @columnfractions .15 .85
@item @code{mysql} @tab Compiled on native Win32, which offers very limited text
editing capabilities.
@item @code{mysqlc} @tab Compiled with the Cygnus GNU compiler and libraries, which offers @code{readline} editing.
@end multitable

If you want to use @code{mysqlc.exe}, you must copy
@file{C:\mysql\lib\cygwinb19.dll} to @file{\windows\system} (or similar
place).

The default privileges on Win32 give all local users full privileges
to all databases.  To make @strong{MySQL} more secure, you
should set a password for all users and remove the row in the
@code{mysql.user} table that has @code{Host='localhost'} and
@code{User=''}.

You should also add a password for the @code{root} user:

@example
C:\mysql\bin\mysql mysql
mysql> DELETE FROM user WHERE Host='localhost' AND User='';
mysql> QUIT
C:\mysql\bin\mysqladmin reload
C:\mysql\bin\mysqladmin -u root password your_password
@end example

After you've set the password, if you want to take down the @code{mysqld}
server, you can do so using this command:

@example
mysqladmin --user=root --password=your_password shutdown
@end example 

@node Win32 and SSH, Win32 vs. Unix, Win32 running, Win32
@subsection Connecting to a remote @strong{MySQL} from Win32 with SSH

Here is a note about how to connect to get a secure connection to remote MySQL
server with SSH (by David Carlson).

@itemize @bullet
@item
Install SSH client on your windows machine - I used a free SSH client
from @uref{http://www.doc.ic.ac.uk/~ci2/ssh/}.
Other useful links:
@uref{http://www.npaci.edu/Security/npaci_security_software.html} and
@uref{http://www.npaci.edu/Security/samples/ssh32_windows/index.html}.
@item
Start SSH. Set Host Name = yourmysqlserver name or IP address. Set
userid=your userid to log in to your server
@item
Click on "local forwards". Set @code{local port: 3306},
@code{host: localhost}, @code{remote port: 3306}
@item
Save everything otherwise you'll have to redo it the next time.
@item
Log in to your server with SSH.
@item
Start some ODBC application (for example Access)
@item
Create a new file and link to mySQL using the ODBC driver the same way
you normally do except for server, user "localhost".
@end itemize

That's it. It works very well with a direct Internet connection. I'm
having problems with SSH conflicting with my Win95 network and Wingate -
but that'll be the topic of a posting on another software company's
usegroup!

@node Win32 vs. Unix,  , Win32 and SSH, Win32
@subsection @strong{MySQL}-Win32 compared to Unix @strong{MySQL}

@strong{MySQL}-Win32 has by now proven itself to be very stable. This version
of @strong{MySQL} has the same features as the corresponding Unix version
with the following exceptions:

@table @strong
@item Win95 and threads
Win95 leaks about 200 bytes of main memory for each thread creation.  Because
of this, you shouldn't run @code{mysqld} for an extended time on Win95 if
you do many connections, since each connection in @strong{MySQL} creates
a new thread!  NT and Win98 don't suffer from this bug.

@item Blocking read
@strong{MySQL} uses a blocking read for each connection.
This means that:

@itemize @bullet
@item
A connection will not be disconnected automatically after 8 hours, as happens
with the Unix version of @strong{MySQL}.

@item
If a connection ``hangs,'' it's impossible to break it without killing
@strong{MySQL}.

@item
@code{mysqladmin kill} will not work on a sleeping connection.

@item
@code{mysqladmin shutdown} can't abort as long as there are sleeping
connections.
@end itemize

We plan to fix this in the near future.

@item UDF functions
For the moment, @strong{MySQL}-Win32 does not support user definable functions.

@item @code{DROP DATABASE}
You can't drop a database that is in use by some thread.

@item Killing @strong{MySQL} from the task manager
You can't kill @strong{MySQL} from the task manager or with the shutdown
utility in Windows95. You must take it down with @code{mysqladmin shutdown}.

@item Case-insensitive names
Filenames are case insensitive on Win32, so database and table names
are also case insensitive in @strong{MySQL} for Win32.  The only restriction is
that database and table names must be given in the same case throughout a
given statement.  The following query would not work because it refers to
a table both as @code{my_table} and as @code{MY_TABLE}:
@example
SELECT * FROM my_table WHERE MY_TABLE.col=1;
@end example

@item The @samp{\} directory character
Pathname components in Win95 are separated by @samp{\} characters, which is
also the escape character in @strong{MySQL}.  If you are using @code{LOAD
DATA INFILE} or @code{SELECT ... INTO OUTFILE}, you must double the @samp{\}
character or use Unix style filenames @samp{/} characters:
@example
LOAD DATA INFILE "C:\\tmp\\skr.txt" INTO TABLE skr;
SELECT * FROM skr INTO OUTFILE 'C:/tmp/skr.txt';
@end example

@item @code{Can't open named pipe} error
If you use the shareware version of @strong{MySQL}-Win32 on NT with the
newest mysql-clients you will get the following error:

@example
error 2017: can't open named pipe to host: . pipe...
@end example

@tindex .my.cnf file
This is because the release version of @strong{MySQL} uses
named pipes on NT by default.  You can avoid this error by using the
@code{--host=localhost} option to the new @strong{MySQL} clients
or create a file @file{C:\my.cnf} that contains the following information:

@example
[client]
host = localhost
@end example

@item @code{Access denied for user} error
If you get the error @code{Access denied for user: 'some-user@@unknown'
to database 'mysql'} when accessing a @strong{MySQL} server on the same
machine, this means that @strong{MySQL} can't resolve your host name
properly.

To fix this, you should create a file @file{\windows\hosts} with the
following information:

@example
127.0.0.1       localhost
@end example
@end table

Here are some open issues for anyone who might want to help us with the Win32
release:

@itemize @bullet
@item
Make a single user @code{MYSQL.DLL} server.  This should include everything in
a standard @strong{MySQL} server, except thread creation.  This will make
@strong{MySQL} much easier to use in applications that don't need a true
client/server and don't need to access the server from other hosts.

@item
Add some nice ``start'' and ``shutdown'' icons to the @strong{MySQL} installation.

@item
Create a tool to manage registry entries for the @strong{MySQL} startup
options.  The registry entry reading is already coded into @code{mysqld.cc},
but it should be recoded to be more ``parameter'' oriented.
The tool should also be able to update the @file{\my.cnf} file if the user
would prefer to use this instead of the registry.

@item
When registering @code{mysqld} as a service with @code{--install} (on NT)
it would be nice if you could also add default options on the command line.
For the moment, the workaround is to update the @file{C:\my.cnf} file
instead.

@item
When you suspend a laptop running Win95, the @code{mysqld}
daemon doesn't accept new connections when the laptop is resumed.
We don't know if this is a problem with Win95, TCP/IP or @strong{MySQL}.

@item
It would be real nice to be able to kill @code{mysqld} from the
task manager.  For the moment, you must use @code{mysqladmin shutdown}.

@item
Port @code{readline} to Win32 for use in the @code{mysql} command line tool.

@item
GUI versions of the standard @strong{MySQL} clients (@code{mysql},
@code{mysqlshow}, @code{mysqladmin}, and @code{mysqldump}) would be nice.

@item
It would be nice if the socket ``read'' and ``write'' functions in
@file{net.c} were interruptible. This would make it possible to kill open
threads with @code{mysqladmin kill} on Win32.

@item
Documentation of which Windows programs work with
@strong{MySQL}-Win32/@strong{MyODBC} and what must be done to get them working.

@item
@code{mysqld} always starts in the "C" locale and not in the default locale.
We would like to have @code{mysqld} use the current locale for the sort order.

@item
Port @code{sqlclient} to Win32 (almost done) and add more features to it!

@item
Add more options to MysqlManager.

@item
Change the communication protocol between the server and client to use Windows
internal communication instead of sockets and TCP/IP.

@item
Implement UDF functions with @code{.DLL}s.

@item
Add macros to use the faster thread-safe increment/decrement methods
provided by Win32.

@end itemize

Other Win32-specific issues are described in the @file{README} file that comes
with the @strong{MySQL}-Win32 distribution.

@node OS/2, TcX binaries, Win32, Installing
@section OS/2 notes

@strong{MySQL} uses quite a few open files. Because of this, you
should add something like the following to your @file{CONFIG.SYS} file:

@example
SET EMXOPT=-c -n -h1024
@end example

If you don't do this, you will probably run into the following error:

@example
File 'xxxx' not found (Errcode: 24)
@end example

When using @strong{MySQL} with OS/2 Warp 3, FixPack 29 or above is
required.  With OS/2 Warp 4, FixPack 4 or above is required. This is a
requirement of the Pthreads library.  @strong{MySQL} must be installed
in a partition that supports long file names such as HPFS, FAT32, etc.

The @file{INSTALL.CMD} script must be run from OS/2's own @file{CMD.EXE}
and may not work with replacement shells such as @file{4OS2.EXE}.

The @file{scripts/mysql-install-db} script has been renamed: it is now called
@file{install.cmd} and is a REXX script which will set up the default
@strong{MySQL} security settings and create the WorkPlace Shell icons
for @strong{MySQL}.

Dynamic module support is compiled in but not fully tested. Dynamic
modules should be compiled using the Pthreads runtime library.

@example
gcc -Zdll -Zmt -Zcrtdll=pthrdrtl -I../include -I../regex -I.. \
    -o example udf_example.cc -L../lib -lmysqlclient udf_example.def
mv example.dll example.udf
@end example

@strong{Note:} Due to limitations in OS/2, UDF module name stems must not
exceed 8 characters. Modules are stored in the @file{/mysql2/udf}
directory; the @code{safe-mysqld.cmd} script will put this directory in
the @code{BEGINLIBPATH} environment variable. When using UDF modules,
specified extensions are ignored --- it is assumed to be @file{.udf}.
For example, in Unix, the shared module might be named @file{example.so}
and you would load a function from it like this:

@example
CREATE FUNCTION metaphon RETURNS STRING SONAME "example.so";
@end example

Is OS/2, the module would be named @file{example.udf}, but you would not
specify the module extension:

@example
CREATE FUNCTION metaphon RETURNS STRING SONAME "example";
@end example

@node TcX binaries, Post-installation, OS/2, Installing
@section TcX binaries

As a service, TcX provides a set of binary distributions of @strong{MySQL}
that are compiled at TcX or at sites where customers kindly have given us
access to their machines.

These distributions
are generated with @code{scripts/make_binary_distribution} and are
configured with the following compilers and options:

@table @asis
@item SunOS 4.1.4 2 sun4c with @code{gcc} 2.7.2.1
@code{CC=gcc CXX=gcc CXXFLAGS=-O3 ./configure --prefix=/usr/local/mysql --disable-shared}

@item SunOS 5.5.1 sun4u with @code{egcs} 1.0.3a
@code{CC=gcc CFLAGS="-O6 -fomit-frame-pointer" CXX=gcc CXXFLAGS="-O6 -fomit-frame-pointer -felide-constructors -fno-exceptions -fno-rtti" ./configure --prefix=/usr/local/mysql --with-low-memory}

@item SunOS 5.6 sun4u with @code{egcs} 2.90.27
@code{CC=gcc CFLAGS="-O6 -fomit-frame-pointer" CXX=gcc CXXFLAGS="-O6 -fomit-frame-pointer -felide-constructors -fno-exceptions -fno-rtti" ./configure --prefix=/usr/local/mysql --with-low-memory}

@item SunOS 5.6 i86pc with @code{gcc} 2.8.1
@code{CC=gcc CXX=gcc CXXFLAGS=-O3 ./configure --prefix=/usr/local/mysql --with-low-memory}

@item Linux 2.0.33 i386 with @code{pgcc} 2.90.29 (@code{egcs} 1.0.3a)
@code{CFLAGS="-O6 -mpentium -mstack-align-double -fomit-frame-pointer" CXX=gcc CXXFLAGS="-O6 -mpentium -mstack-align-double -fomit-frame-pointer -felide-constructors -fno-exceptions -fno-rtti" ./configure --prefix=/usr/local/mysql --enable-assembler --with-mysqld-ldflags=-all-static}

@item SCO 3.2v5.0.4 i386 with @code{gcc} 2.7-95q4
@code{CC=gcc CXX=gcc CXXFLAGS=-O3 ./configure --prefix=/usr/local/mysql}

@item AIX 2 4 with @code{gcc} 2.7.2.2
@code{CC=gcc CXX=gcc CXXFLAGS=-O3 ./configure --prefix=/usr/local/mysql}

@item OSF1 V4.0 564 alpha with @code{gcc} 2.8.1
@code{CC=gcc CFLAGS=-O CXX=gcc CXXFLAGS=-O3 ./configure --prefix=/usr/local/mysql --with-low-memory}

@item Irix 6.3 IP32 with @code{gcc} 2.8.0
@code{CC=gcc CXX=gcc CXXFLAGS=-O3 ./configure --prefix=/usr/local/mysql}

@item BSDI BSD/OS 3.1 i386 with @code{gcc} 2.7.2.1
@code{CC=gcc CXX=gcc CXXFLAGS=-O ./configure --prefix=/usr/local/mysql}

@item BSDI BSD/OS 2.1 i386 with @code{gcc} 2.7.2
@code{CC=gcc CXX=gcc CXXFLAGS=-O3 ./configure --prefix=/usr/local/mysql}
@end table

Anyone who has more optimal options for any of the configurations listed
above can always mail them to the developer's mailing list at
@email{developer@@lists.mysql.com}.

RPM distributions prior to @strong{MySQL} 3.22 are user-contributed.
Beginning with 3.22, some RPMs are TcX-generated.

@node Post-installation, Upgrade, TcX binaries, Installing
@section Post-installation setup and testing

@menu
* mysql_install_db::            Problems running @code{mysql_install_db}
* Starting server::             Problems starting the @strong{MySQL} server
* Automatic start::             Starting and stopping @strong{MySQL} automatically
* Option files::                Option files
@end menu

Once you've installed @strong{MySQL} (from either a binary or source
distribution), you need to initialize the grant tables, start the server
and make sure that the server works okay.  You may also wish to arrange
for the server to be started and stopped automatically when your system
starts up and shuts down.

Normally you install the grant tables and start the server like this:

@example
shell> ./scripts/mysql_install_db
shell> cd mysql_installation_directory
shell> ./bin/safe_mysqld &
@end example

Testing is most easily done from the top-level directory of the @strong{MySQL}
distribution.  For a binary distribution, this is your installation directory
(typically something like @file{/usr/local/mysql}).  For a source
distribution, this is the main directory of your @strong{MySQL} source tree.

In the commands shown below in this section and in the following
subsections, @code{BINDIR} is the path to the location in which programs
like @code{mysqladmin} and @code{safe_mysqld} are installed.  For a
binary distribution, this is the @file{bin} directory within the
distribution.  For a source distribution, @code{BINDIR} is probably
@file{/usr/local/bin}, unless you specified an installation directory
other than @file{/usr/local} when you ran @code{configure}.
@code{EXECDIR} is the location in which the @code{mysqld} server is
installed.  For a binary distribution, this is the same as
@code{BINDIR}.  For a source distribution, @code{EXECDIR} is probably
@file{/usr/local/libexec}.

Testing is described in detail below:

@enumerate
@item
If necessary, start the @code{mysqld} server and set up the initial
@strong{MySQL} grant tables containing the privileges that determine how
users are allowed to connect to the server.  This is normally done with the
@code{mysql_install_db} script:

@example
shell> scripts/mysql_install_db
@end example

Normally, @code{mysql_install_db} needs to be run only the first time you
install @strong{MySQL}.  Therefore, if you are upgrading an existing
installation, you can skip this step. (However, @code{mysql_install_db} is
quite safe to use and will not update any tables that already exist, so if
you are unsure what to do, you can always run @code{mysql_install_db}.)

@code{mysql_install_db} creates six tables (@code{user}, @code{db},
@code{host}, @code{tables_priv}, @code{columns_priv} and @code{func}) in the
@code{mysql} database.  A description of the initial privileges is given in
@ref{Default privileges}.  Briefly, these privileges allow the @strong{MySQL}
@code{root} user to do anything, and allow anybody to create or use databases
with a name of @code{'test'} or starting with @code{'test_'}.

If you don't set up the grant tables, the following error will appear in the
log file when you start the server:

@tindex host.frm, problems finding
@example
mysqld: Can't find file: 'host.frm'
@end example

The above may also happens with a binary @strong{MySQL} distribution if you
don't start @strong{MySQL} by executing exactly @code{./bin/safe_mysqld}!

You might need to run @code{mysql_install_db} as @code{root}.  However,
if you prefer, you can run the @strong{MySQL} server as an unprivileged
(non-@code{root}) user, provided that user can read and write files in
the database directory.  Instructions for running @strong{MySQL} as an
unprivileged user are given in @ref{Changing MySQL user, , Changing
@strong{MySQL} user}.

If you have problems with @code{mysql_install_db}, see
@ref{mysql_install_db, , @code{mysql_install_db}}.

There are some alternatives to running the @code{mysql_install_db}
script as it is provided in the @strong{MySQL} distribution:

@itemize @bullet
@item
You may want to edit @code{mysql_install_db} before running it, to
change the initial privileges that are installed into the grant tables.
This is useful if you want to install @strong{MySQL} on a lot of machines
with the same privileges.  In this case you probably should need only to add
a few extra @code{INSERT} statements to the @code{mysql.user} and
@code{mysql.db} tables!

@item
If you want to change things in the grant tables after installing them, you
can run @code{mysql_install_db}, then use @code{mysql -u root mysql} to
connect to the grant tables as the @strong{MySQL} @code{root} user and issue
SQL statements to modify the grant tables directly.

@item
It is possible to recreate the grant tables completely after they have
already been created.  You might want to do this if you've already installed
the tables but then want to recreate them after editing
@code{mysql_install_db}.
@end itemize

For more information about these alternatives, see @ref{Default privileges}.

@item
Start the @strong{MySQL} server like this:
@example
shell> cd mysql_installation_directory
shell> bin/safe_mysqld &
@end example
If you have problems starting the server, see @ref{Starting server}.

@item
Use @code{mysqladmin} to verify that the server is running.  The following
commands provide a simple test to check that the server is up and responding
to connections:

@example
shell> BINDIR/mysqladmin version
shell> BINDIR/mysqladmin variables
@end example

The output from @code{mysqladmin version} varies slightly depending on your
platform and version of @strong{MySQL}, but should be similar to that shown
below:

@example
shell> BINDIR/mysqladmin version
mysqladmin  Ver 6.3 Distrib 3.22.9-beta, for pc-linux-gnu on i686
TCX Datakonsult AB, by Monty

Server version          3.22.9-beta
Protocol version        10
Connection              Localhost via UNIX socket
TCP port                3306
UNIX socket             /tmp/mysql.sock
Uptime:                 16 sec

Running threads: 1  Questions: 20  Reloads: 2  Open tables: 3
@end example

To get a feeling for what else you can do with @code{BINDIR/mysqladmin},
invoke it with the @code{--help} option.

@item
Verify that you can shut down the server:

@example
shell> BINDIR/mysqladmin -u root shutdown
@end example

@item
Verify that you can restart the server.  Do this using @code{safe_mysqld} or
by invoking @code{mysqld} directly.  For example:

@example
shell> BINDIR/safe_mysqld --log &
@end example

If @code{safe_mysqld} fails, try running it from the @strong{MySQL}
installation directory (if you are not already there).  If that doesn't work,
see @ref{Starting server}.

@item
Run some simple tests to verify that the server is working.
The output should be similar to what is shown below:

@example
shell> BINDIR/mysqlshow
+-----------+
| Databases |
+-----------+
| mysql     |
+-----------+

shell> BINDIR/mysqlshow mysql
Database: mysql
+--------------+
|    Tables    |
+--------------+
| columns_priv |
| db           |
| func         |
| host         |
| tables_priv  |
| user         |
+--------------+

shell> BINDIR/mysql -e "select host,db,user from db" mysql
+------+--------+------+
| host | db     | user |
+------+--------+------+
| %    | test   |      |
| %    | test_% |      |
+------+--------+------+
@end example

There is also a benchmark suite in the @file{sql-bench} directory (under the
@strong{MySQL} installation directory) that you can use to compare how
@strong{MySQL} performs on different platforms. The @file{sql-bench/Results}
directory contains the results from many runs against different databases and
platforms.  To run all tests, execute these commands:

@example
shell> cd sql-bench
shell> run-all-tests
@end example

If you don't have the @file{sql-bench} directory, you are probably using an
RPM for a binary distribution.  (Source distribution RPMs include the
benchmark directory.) In this case, you must first install the benchmark
suite before you can use it.  Beginning with @strong{MySQL} 3.22, there are
benchmark RPM files named @file{mysql-bench-VERSION-i386.rpm} that contain
benchmark code and data.

If you have a source distribution, you can also run the tests in the
@file{tests} subdirectory. For example, to run @file{auto_increment.tst}, do
this:

@example
shell> BINDIR/mysql -vvf test < ./tests/auto_increment.tst
@end example

The expected results are shown in the @file{./tests/auto_increment.res} file.
@end enumerate

@node mysql_install_db, Starting server, Post-installation, Post-installation
@subsection Problems running @code{mysql_install_db}

This section lists problems you might encounter when you run
@code{mysql_install_db}:

@table @strong
@item @code{mysql_install_db} doesn't install the grant tables

You may find that @code{mysql_install_db} fails to install the grant
tables and terminates after displaying the following messages:

@example
starting mysqld daemon with databases from XXXXXX
mysql daemon ended
@end example

In this case, you should examine the log file very carefully!  The log
should be located in the directory @file{XXXXXX} named by the error message,
and should indicate why @code{mysqld} didn't start.  If you don't understand
what happened, include the log when you post a bug report using
@code{mysqlbug}!
@xref{Bug reports}.

@item There is already a @code{mysqld} daemon running

In this case, you have probably don't have to run @code{mysql_install_db} at
all.  You have to run @code{mysql_install_db} only once, when you install
@strong{MySQL} the first time.

@item Installing a second @code{mysqld} daemon doesn't work when one daemon is running

This can happen when you already have an existing @strong{MySQL}
installation, but want to put a new installation in a different place (e.g.,
for testing, or perhaps you simply want to run two installations at the same
time).  Generally the problem that occurs when you try to run the second
server is that it tries to use the same socket and port as the old one.  In
this case you will get the error message: @code{Can't start server: Bind on
TCP/IP port: Address already in use} or @code{Can't start server : Bind on
unix socket...}  You can start the new server with a different socket and
port as follows:

@tindex MYSQL_UNIX_PORT environment variable
@tindex MYSQL_TCP_PORT environment variable
@tindex Environment variable, MYSQL_UNIX_PORT
@tindex Environment variable, MYSQL_TCP_PORT
@example
shell> MYSQL_UNIX_PORT=/tmp/mysqld-new.sock
shell> MYSQL_TCP_PORT=3307
shell> export MYSQL_UNIX_PORT MYSQL_TCP_PORT
shell> scripts/mysql_install_db
shell> bin/safe_mysqld &
@end example

After this, you should edit your server boot script to start both daemons
with different sockets and ports.  For example, it could invoke
@code{safe_mysqld} twice, but with different @code{--socket}, @code{--port}
and @code{--basedir} options for each invocation.

@item You don't have write access to @file{/tmp}

If you don't have write access to create a socket file at the default place
(in @file{/tmp}) or permission to create temporary files in @file{/tmp,}
you will get an error when running @code{mysql_install_db} or when
starting or using @code{mysqld}.

You can specify a different socket and temporary directory as follows:

@tindex TMPDIR environment variable
@tindex MYSQL_UNIX_PORT environment variable
@tindex Environment variable, TMPDIR
@tindex Environment variable, MYSQL_UNIX_PORT
@example
shell> TMPDIR=/some_tmp_dir/
shell> MYSQL_UNIX_PORT=/some_tmp_dir/mysqld.sock
shell> export TMPDIR MYSQL_UNIX_PORT
@end example

@file{some_tmp_dir} should be the path to some directory for which you
have write permission.

After this you should be able to run @code{mysql_install_db} and start
the server with these commands:

@example
shell> scripts/mysql_install_db
shell> BINDIR/safe_mysqld &
@end example

@item @code{mysqld} crashes immediately

If you are running RedHat 5.0 with a version of @code{glibc} older than
2.0.7-5, you should make sure you have installed all @code{glibc} patches!
There is a lot of information about this in the @strong{MySQL} mail
archives.  Links to the mail archives are available at the online
@uref{http://www.mysql.com/doc.html, @strong{MySQL} documentation page}.
Also, see @ref{Linux}.

You can also start @code{mysqld} manually using the @code{--skip-grant}
option and add the privilege information yourself using @code{mysql}:

@example
shell> BINDIR/safe_mysqld --skip-grant &
shell> BINDIR/mysql -u root mysql
@end example

From @code{mysql}, manually execute the SQL commands in @code{mysql_install_db}.
Make sure you run @code{mysqladmin reload} afterward to tell the
server to reload the grant tables.
@end table

@node Starting server, Automatic start, mysql_install_db, Post-installation
@subsection Problems starting the @strong{MySQL} server

Generally, you start the @code{mysqld} server in one of three ways:

@itemize @bullet
@item
By invoking @code{mysql.server}.  This script is used primarily at
system startup and shutdown, and is described more fully in
@ref{Automatic start}.
@item
By invoking @code{safe_mysqld}, which tries to determine the proper options
for @code{mysqld} and then runs it with those options.
@item
By invoking @code{mysqld} directly.
@end itemize

Whichever method you use to start the server, if it fails to start up
correctly, check the log file to see if you can find out why.  Log files
are located in the data directory (typically
@file{/usr/local/mysql/data} for a binary distribution,
@file{/usr/local/var} for a source distribution).  Look in the data
directory for files with names of the form @file{host_name.err} and
@file{host_name.log} where @code{host_name} is the name of your server
host.  Then check the last few lines of these files:

@example
shell> tail host_name.err
shell> tail host_name.log
@end example

When the @code{mysqld} daemon starts up, it changes directory to the
data directory.  This is where it expects to write log files and the pid
(process ID) file, and where it expects to find databases.

The data directory location is hardwired in when the distribution is
compiled.  However, if @code{mysqld} expects to find the data directory
somewhere other than where it really is on your system, it will not work
properly.  If you have problems with incorrect paths, you can find out
what options @code{mysqld} allows and what the default path settings are by
invoking @code{mysqld} with the @code{--help} option.  You can override the
defaults by specifying the correct pathnames as command-line arguments to
@code{mysqld}.  (These options can be used with @code{safe_mysqld} as well.)

Normally you should need to tell @code{mysqld} only the base directory under
which @strong{MySQL} is installed.  You can do this with the @code{--basedir}
option.  You can also use @code{--help} to check the effect of changing path
options (note that @code{--help} @emph{must} be the final option of the
@code{mysqld} command).  For example:

@example
shell> EXECDIR/mysqld --basedir=/usr/local --help
@end example

Once you determine the path settings you want, start the server without
the @code{--help} option.

If you get the following error, it means that some other program (or another
@code{mysqld} server) is already using the TCP/IP port or socket
@code{mysqld} is trying to use:

@example
Can't start server: Bind on TCP/IP port: Address already in use
  or
Can't start server : Bind on unix socket...
@end example

Use @code{ps} to make sure that you don't have another @code{mysqld} server
running.  If you can't find another server running, you can try to execute
the command @code{telnet your-host-name tcp-ip-port-number} and press
@code{RETURN} a couple of times.  If you don't get a error message like
@code{telnet: Unable to connect to remote host: Connection refused},
something is using the TCP/IP port @code{mysqld} is trying to use.
@xref{mysql_install_db, , @code{mysql_install_db}}, and @ref{Multiple
servers}.

The @code{safe_mysqld} script is written so that it normally is able to start
a server that was installed from either a source or a binary version of
@strong{MySQL}, even if these install the server in slightly different
locations.  @code{safe_mysqld} expects one of these conditions to be true:

@itemize @bullet
@item
The server and databases can be found relative to the directory from which
@code{safe_mysqld} is invoked.  @code{safe_mysqld} looks under its working
directory for @file{bin} and @file{data} directories (for binary
distributions) or for @file{libexec} and @file{var} directories (for source
distributions).  This condition should be met if you execute
@code{safe_mysqld} from your @strong{MySQL} installation directory (for
example, @file{/usr/local/mysql} for a binary distribution).

@item
If the server and databases cannot be found relative to its working directory,
@code{safe_mysqld} attempts to locate them by absolute pathnames.  Typical
locations are @file{/usr/local/libexec} and @file{/usr/local/var}.
The actual locations are determined when the distribution was built from which
@code{safe_mysqld} comes.  They should be correct if
@strong{MySQL} was installed in a standard location.
@end itemize

Since @code{safe_mysqld} will try to find the server and databases relative
to its own working directory, you can install a binary distribution of
@strong{MySQL} anywhere, as long as you start @code{safe_mysqld} from the
@strong{MySQL} installation directory:

@example
shell> cd mysql_installation_directory
shell> bin/safe_mysqld &
@end example

If @code{safe_mysqld} fails, even when invoked from the @strong{MySQL}
installation directory, you can modify it to use the path to @code{mysqld}
and the pathname options that are correct for your system.  Note that if you
upgrade @strong{MySQL} in the future, your modified version of
@code{safe_mysqld} will be overwritten, so you should make a copy of your
edited version that you can reinstall.

If @code{mysqld} is currently running, you can find out what path settings
it is using by executing this command:

@example
shell> mysqladmin variables
@end example

If @code{safe_mysqld} starts the server but you can't connect to it,
you should make sure you have an entry in @file{/etc/hosts} that looks like
this:

@example
127.0.0.1       localhost
@end example

This problem occurs only on systems that don't have a working thread
library and for which @strong{MySQL} must be configured to use MIT-pthreads.

@node Automatic start, Option files, Starting server, Post-installation
@subsection Starting and stopping @strong{MySQL} automatically

The @code{mysql.server} script can be used to start or stop the server,
by invoking it with @code{start} or @code{stop} arguments:

@example
shell> mysql.server start
shell> mysql.server stop
@end example

@code{mysql.server} can be found in the @file{share/mysql} directory
under the @strong{MySQL} installation directory, or in the @file{support-files}
directory of the @strong{MySQL} source tree.

Before @code{mysql.server} starts the server, it changes directory to
the @strong{MySQL} installation directory, then invokes
@code{safe_mysqld}.  You might need to edit @code{mysql.server} if you
have a binary distribution that you've installed in a non-standard
location.  Modify it to @code{cd} into the proper directory before it
runs @code{safe_mysqld}. If you want the server to run as some specific
user, you can change the @code{mysql_daemon_user=root} line to use
another user.  You can also modify @code{mysql.server} to pass other
options to @code{safe_mysqld}.

@code{mysql.server stop} brings down server by sending a signal to it.
You can take down the server manually by executing @code{mysqladmin shutdown}.

You might want to add these start and stop commands to the appropriate places
in your @file{/etc/rc*} files when you start using @strong{MySQL} for
production applications.  Note that if you modify @code{mysql.server}, then
if you upgrade @strong{MySQL} sometime, your modified version will be
overwritten, so you should make a copy of your edited version that you can
reinstall.

If your system uses @file{/etc/rc.local} to start external scripts, you
should append the following to it:
@example
/bin/sh -c 'cd /usr/local/mysql ; ./bin/safe_mysqld &'
@end example

You can also add options or @code{mysql.server} in a global
@file{/etc/my.cnf} file.  A typical @file{/etc/my.cnf} file might look like
this:

@example
[mysqld]
datadir=/usr/local/mysql/var
socket=/tmp/mysqld.sock
port=3306

[mysql.server]
user=mysql
basedir=/usr/local/mysql
@end example

The @code{mysql.server} script uses the following variables:
@code{user}, @code{datadir}, @code{basedir}, @code{bindir} and @code{pid-file}.

@xref{Option files}.

@cindex Default options
@cindex Option files
@node Option files,  , Automatic start, Post-installation
@subsection Option files

@strong{MySQL} 3.22 can read default startup options for the server and
for clients from option files.

@strong{MySQL} reads default options from the following files on Unix:

@tindex .my.cnf file
@multitable @columnfractions .3 .7
@item @strong{Filename} @tab @strong{Purpose}
@item @code{/etc/my.cnf} @tab Global options
@item @code{DATADIR/my.cnf} @tab Server-specific options
@item @code{~/.my.cnf} @tab User-specific options
@end multitable

@code{DATADIR} is the @strong{MySQL} data directory (typically
@file{/usr/local/mysql/data} for a binary installation, or
@file{/usr/local/var} for a source installation).  Note that this is the
directory that was specified at configuration time, not the one specified
with @code{--datadir} when @code{mysqld} starts up!  (@code{--datadir} has no
effect on where the server looks for option files, because it looks for them
before it processes any command-line arguments.)

@strong{MySQL} reads default options from the following files on Win32:

@multitable @columnfractions .3 .7
@item @strong{Filename} @tab @strong{Purpose}
@item @code{C:\my.cnf} @tab Global options
@item @code{C:\mysql\data\my.cnf} @tab Server-specific options
@end multitable

@cindex Environment variables
@strong{MySQL} tries to read option files in the order listed above.  If
multiple option files exist, an option specified in a file read later takes
precedence over the same option specified in a file read earlier.  Options
specified on the command line take precedence over options specified in any
option file.  Some options can be specified using environment variables.
Options specified on the command line or in option files take precedence over
environment variable values.

The following programs support option files:  @code{mysql},
@code{mysqladmin}, @code{mysqld}, @code{mysqldump}, @code{mysqlimport},
@code{mysql.server}, @code{isamchk} and @code{pack_isam}.

You can use option files to specify any long option that a program supports!
Run the program with @code{--help} to get a list of available options.

An option file can contain lines of the following forms:

@table @code
@item #comment
Comment lines starts with @samp{#} or @samp{;}. Empty lines are ignored.

@item [group]
@code{group} is the name of the program or group for which you want to set
options.  After a group line, any @code{option} or @code{set-variable} lines
apply to the named group until the end of the option file or another group
line is given.

@item option
This is equivalent to @code{--option} on the command line.

@item option=value
This is equivalent to @code{--option=value} on the command line.

@item set-variable = variable=value
This is equivalent to @code{--set-variable variable=value} on the command line.
This syntax must be used to set a @code{mysqld} variable.
@end table

The @code{client} group allows you to specify options that apply to all
@strong{MySQL} clients (not @code{mysqld}). This is the perfect group to use
to specify the password you use to connect to the server.  (But make
sure the option file is readable and writable only to yourself.)

Note that for options and values, all leading and trailing blanks are
automatically deleted.  You may use the escape sequences @samp{\b},
@samp{\t}, @samp{\n}, @samp{\r}, @samp{\\} and @samp{\s} in your value string
(@samp{\s} == blank).

Here is a typical global option file:

@example
[client]
port=3306
socket=/tmp/mysql.sock

[mysqld]
port=3306
socket=/tmp/mysql.sock
set-variable = key_buffer=16M
set-variable = max_allowed_packet=1M

[mysqldump]
quick
@end example

Here is typical user option file:

@example
[client]
# The following password will be sent to all standard MySQL clients
password=my_password

[mysql]
no-auto-rehash
@end example

@tindex .my.cnf file
If you have a source distribution, you will find a sample configuration file
named @file{my-example.cnf} in the @file{support-files} directory.  If you
have a binary distribution, look in the @file{DIR/share/mysql} directory,
where @code{DIR} is the pathname to the @strong{MySQL} installation directory
(typically @file{/usr/local/mysql}). You can copy @file{my-example.cnf} to
your home directory (rename the copy to @file{.my.cnf}) to experiment with.

To tell a @strong{MySQL} program not to read any option files, specify
@code{--no-defaults} as the first option on the command line.  This
@strong{MUST} be the first option or it will have no effect!
If you want to check which options are used, you can give the option
@code{--print-defaults} as the first option.

Note for developers:  Option file handling is implemented simply by
processing all matching options (i.e., options in the appropriate group)
before any command line arguments. This works nicely for programs that use
the last instance of an option that is specified multiple times. If you have
an old program that handles multiply-specified options this way but doesn't
read option files, you need add only two lines to give it that capability.
Check the source code of any of the standard @strong{MySQL} clients to see
how to do this.

@node Upgrade,  , Post-installation, Installing
@section Is there anything special to do when upgrading/downgrading @strong{MySQL}?

You can always move the @strong{MySQL} form and data files between
different versions on the same architecture as long as you have the same
base version of @strong{MySQL}. The current base version is
3. If you change the character set by recompiling @strong{MySQL} (which may
also change the sort order), you must run @code{isamchk -r -q} on all tables.
Otherwise your indexes may not be ordered correctly.

If you are paranoid and/or afraid of new versions, you can always rename your
old @code{mysqld} to something like @code{mysqld}-'old-version-number'.  If
your new @code{mysqld} then does something unexpected, you can simply shut it
down and restart with your old @code{mysqld}!

When you do an upgrade you should also backup your old databases, of course.
Sometimes it's good to be a little paranoid!

After an upgrade, if you experience problems with recompiled client programs,
like @code{Commands out of sync} or unexpected core dumps, you probably have
used an old header or library file when compiling your programs.  In this
case you should check the date for your @file{mysql.h} file and
@file{libmysqlclient.a} library to verify that they are from the new
@strong{MySQL} distribution.  If not, please recompile your programs!

If you get some problems that the new @code{mysqld} server doesn't want to
start or that you can't connect without a password, check that you don't
have some old @file{my.cnf} file from your old installation!  You can
check this with: @code{program-name --print-defaults}.  If this outputs
anything other than the program name, you have a active @code{my.cnf}
file that will may affect things!

It is a good idea to rebuild and reinstall the @code{Msql-Mysql-modules}
distribution whenever you install a new release of @strong{MySQL},
particularly if you notice symptoms such as all your @code{DBI} scripts
dumping core after you upgrade @strong{MySQL}.

@menu
* Upgrading-from-3.22::         Upgrading from a 3.22 version to 3.23
* Upgrading-from-3.21::         Upgrading from a 3.21 version to 3.22
* Upgrading-from-3.20::         Upgrading from a 3.20 version to 3.21
* Upgrading-to-arch::           Upgrading to another architecture
@end menu

@cindex Compatibility, between MySQL versions
@node Upgrading-from-3.22, Upgrading-from-3.21, Upgrade, Upgrade
@subsection Upgrading from a 3.22 version to 3.23

@strong{MySQL} 3.23 supports tables of the new @code{MYISAM} type and
the old @code{NISAM} type.  You don't have to convert your old tables to
use these with 3.23.  All new tables will by default be created with type
@code{MYISAM} (unless you start @code{mysqld} with the @code{--skip-new}
option. You can change an @code{ISAM} table to a @code{MYISAM} table with
@code{ALTER TABLE}.

3.22 and 3.21 clients will work without any problems with a 3.23 server.

The following lists what you have to watch out for when upgrading to 3.23:

@itemize @bullet
@item @code{INNER} and @code{DELAYED} are now reserved words.
@item @code{FLOAT(4)} and @code{FLOAT(8)} are now true floating point types.
@item When declaring @code{DECIMAL(length,dec)} the length argument no
longer includes a place for the sign or the decimal point. 
@item A @code{TIME} string must now be of one of the following formats: @code{[[[DAYS] [H]H:]MM:]SS[.fraction]} or @code{[[[[[H]H]H]H]MM]SS[.fraction]}
@item @code{LIKE} now compares strings using the same character comparison rules as @code{'='}.  If you require the old behaveour, you can compile @strong{MySQL} with the @code{CXXFLAGS=-DLIKE_CMP_TOUPPER} flag.
@item When you check/repair tables you should use @code{myisamchk} for @code{MYISAM} tables (@code{.MYI}) and @code{isamchk} for ISAM (@code{.ISM}) tables.
@item If you want your mysqldump:s to be compatible between @strong{MySQL} 3.22 and 3.23, you should not use the @code{--opt} or @code{--full} option to @code{mysqldump}.
@item Check all your calls to @code{DATE_FORMAT()} that there is a '%' before each format character.
@end itemize

@cindex Compatibility, between MySQL versions
@node Upgrading-from-3.21, Upgrading-from-3.20, Upgrading-from-3.22, Upgrade
@subsection Upgrading from a 3.21 version to 3.22

Nothing that affects compatibility has changed between 3.21 and 3.22.  The
only pitfall is that new tables that are created with @code{DATE} type
columns will use the new way to store the date. You can't access these new
fields from an old version of @code{mysqld}.

After installing @strong{MySQL} 3.22, you should start the new server and
then run the @code{mysql_fix_privilege_tables} script. This will add the new
privileges that you need to use the @code{GRANT} command.  If you forget
this, you will get @code{Access denied} when you try to use @code{ALTER
TABLE}, @code{CREATE INDEX} or @code{DROP INDEX}. If your @strong{MySQL} root
user requires a password, you should give this as an argument to
@code{mysql_fix_privilege_tables}.

The C API interface to @code{mysql_real_connect()} has changed.  If you have
an old client program that calls this function, you must place a @code{0} for
the new @code{db} argument (or recode the client to send the @code{db}
element for faster connections).  You must also call @code{mysql_init()}
before calling @code{mysql_real_connect()}!  This change was done to allow
the new @code{mysql_options()} function to save options in the @code{MYSQL}
handler structure.

@node Upgrading-from-3.20, Upgrading-to-arch, Upgrading-from-3.21, Upgrade
@subsection Upgrading from a 3.20 version to 3.21

If you are running a version older than 3.20.28 and want to
switch to 3.21.x, you need to do the following:

You can start the @code{mysqld} 3.21 server with @code{safe_mysqld
--old-protocol} to use it with clients from the 3.20 distribution.
In this case, the new client function @code{mysql_errno()} will not
return any server error, only @code{CR_UNKNOWN_ERROR}, (but it
works for client errors) and the server uses the old password() checking
rather than the new one.

If you are @strong{NOT} using the @code{--old-protocol} option to
@code{mysqld}, you will need to make the following changes:

@itemize @bullet
@item
All client code must be recompiled. If you are using ODBC, you must get
the new @strong{MyODBC} 2.x driver.
@item
The script @code{scripts/add_long_password} must be run to convert the
@code{Password} field in the @code{mysql.user} table to @code{CHAR(16)}.
@item
All passwords must be reassigned in the @code{mysql.user} table (to get 62-bit
rather than 31-bit passwords).
@item
The table format hasn't changed, so you don't have to convert any tables.
@end itemize

@strong{MySQL} 3.20.28 and above can handle the new @code{user} table format
without affecting clients. If you have a @strong{MySQL} version earlier than
3.20.28, passwords will no longer work with it if you convert the @code{user}
table. So to be safe, you should first upgrade to at least 3.20.28 and then
upgrade to 3.21.x.

@cindex Protocol mismatch
The new client code works with a 3.20.x @code{mysqld} server, so
if you experience problems with 3.21.x, you can use the old 3.20.x server
without having to recompile the clients again.

If you are not using the @code{--old-protocol} option to @code{mysqld},
old clients will issue the error message:

@example
ERROR: Protocol mismatch. Server Version = 10 Client Version = 9
@end example

The new Perl @code{DBI}/@code{DBD} interface also supports the old
@code{mysqlperl} interface.  The only change you have to make if you use
@code{mysqlperl} is to change the arguments to the @code{connect()} function.
The new arguments are: @code{host}, @code{database}, @code{user},
@code{password} (the @code{user} and @code{password} arguments have changed
places).
@xref{Perl DBI Class, , Perl @code{DBI} Class}.

The following changes may affect queries in old applications:

@itemize @bullet
@item
@code{HAVING} must now be specified before any @code{ORDER BY} clause.
@item
The parameters to @code{LOCATE()} have been swapped.
@item
There are some new reserved words. The most notable are @code{DATE},
@code{TIME} and @code{TIMESTAMP}.
@end itemize

@node Upgrading-to-arch,  , Upgrading-from-3.20, Upgrade
@subsection Upgrading to another architecture

If you are using @strong{MySQL} 3.23, you can copy the @code{.frm}, the
@code{.MYI} and the @code{.MYD} files between different architectures
that support the same floating point format.  (@strong{MySQL} takes care of
any byte swapping issues).

The @strong{MySQL} data @file{*.ISD} and the index files @file{*.ISM}
files) are architecture-dependent and in some case OS-dependent.  If you
want to move your applications to another machine that has a different
architecture or OS than your current machine, you should not try to move
a database by simply copying the files to the other machine.  Use
@code{mysqldump} instead.

By default, @code{mysqldump} will create a file full of SQL statements.  You
can then transfer the file to the other machine and feed it as input to the
@code{mysql} client.

Try @code{mysqldump --help} to see what options are available.
If you are moving the data to a newer version of @strong{MySQL}, you should use
@code{mysqldump --opt} with the newer version to get a fast, compact dump.

The easiest (although not the fastest) way to move a database between two
machines is to run the following commands on the machine on which the
database is located:

@example
shell> mysqladmin -h 'other hostname' create db_name
shell> mysqldump --opt db_name \
        | mysql -h 'other hostname' db_name
@end example

If you want to copy a database from a remote machine over a slow network,
you can use:

@example
shell> mysqladmin create db_name
shell> mysqldump -h 'other hostname' --opt --compress db_name \
        | mysql db_name
@end example

You can also store the result in a file, then transfer the file to the
target machine and load the file into the database there.  For example,
you can dump a database to a file on the source machine like this:

@example
shell> mysqldump --quick db_name | gzip > db_name.contents.gz
@end example

(The file created in this example is compressed.) Transfer the file
containing the database contents to the target machine and run these commands
there:

@example
shell> mysqladmin create db_name
shell> gunzip < db_name.contents.gz | mysql db_name
@end example

@cindex @code{mysqldump}
@cindex @code{mysqlimport}
You can also use @code{mysqldump} and @code{mysqlimport} to accomplish
the database transfer.
For big tables, this is much faster than simply using @code{mysqldump}.
In the commands shown below, @code{DUMPDIR} represents the full pathname
of the directory you use to store the output from @code{mysqldump}.

First, create the directory for the output files and dump the database:

@example
shell> mkdir DUMPDIR
shell> mysqldump --tab=DUMPDIR db_name
@end example

Then transfer the files in the @code{DUMPDIR} directory to some corresponding
directory on the target machine and load the files into @strong{MySQL}
there:

@example
shell> mysqladmin create db_name           # create database
shell> cat DUMPDIR/*.sql | mysql db_name   # create tables in database
shell> mysqlimport db_name DUMPDIR/*.txt   # load data into tables
@end example

Also, don't forget to copy the @code{mysql} database, since that's where the
grant tables (@code{user}, @code{db}, @code{host}) are stored.  You may have
to run commands as the @strong{MySQL} @code{root} user on the new machine
until you have the @code{mysql} database in place.

After you import the @code{mysql} database on the new machine, execute
@code{mysqladmin flush-privileges} so that the server reloads the grant table
information.

@cindex Compatibility, with ANSI SQL
@node Compatibility, Privilege system, Installing, Top
@chapter How standards-compatible is @strong{MySQL}?

@menu
* Extensions to ANSI::          @strong{MySQL} extensions to ANSI SQL92
* Differences from ANSI::       @strong{MySQL} differences compared to ANSI SQL92
* Missing functions::           Functionality missing from @strong{MySQL}
* Standards::                   What standards does @strong{MySQL} follow?
* Commit-rollback::             How to cope without @code{COMMIT}-@code{ROLLBACK}
@end menu

@node Extensions to ANSI, Differences from ANSI, Compatibility, Compatibility
@section @strong{MySQL} extensions to ANSI SQL92

@strong{MySQL} includes some extensions that you probably will not find in
other SQL databases.  Be warned that if you use them, your code will not be
portable to other SQL servers.  In some cases, you can write code that
includes @strong{MySQL} extensions, but is still portable, by using comments
of the form @code{/*! ... */}.  In this case, @strong{MySQL} will parse and
execute the code within the comment as it would any other @strong{MySQL}
statement, but other SQL servers will ignore the extensions.  For example:

@example
SELECT /*! STRAIGHT_JOIN */ col_name FROM table1,table2 WHERE ...
@end example

@strong{MySQL} extensions are listed below:

@itemize @bullet
@item
The field types @code{MEDIUMINT}, @code{SET}, @code{ENUM} and the
different @code{BLOB} and @code{TEXT} types.

@item
The field attributes @code{AUTO_INCREMENT}, @code{BINARY},
@code{UNSIGNED} and @code{ZEROFILL}.

@item
All string comparisons are case insensitive by default, with sort
ordering determined by the current character set (ISO-8859-1 Latin1 by
default).  If you don't like this, you should declare your columns with
the @code{BINARY} attribute or use the @code{BINARY} cast, which causes
comparisons to be done according to the ASCII order used on the
@strong{MySQL} server host.

@item
@strong{MySQL} maps each database to a directory under the @strong{MySQL}
data directory, and tables within a database to filenames in the database
directory.
This has two implications:

@itemize @minus
@item
@cindex Database names, case sensitivity
@cindex Table names, case sensitivity
@cindex Case sensitivity, of database names
@cindex Case sensitivity, of table names
Database names and table names are case sensitive in @strong{MySQL} on
operating systems that have case sensitive filenames (like most Unix
systems). If you have a problem remembering table names, adopt a consistent
convention, such as always creating databases and tables using lowercase
names.

@item
Database, table, index, column or alias names may begin with a digit
(but may not consist solely of digits).

@item
You can use standard system commands to backup, rename, move, delete and copy
tables.  For example, to rename a table, rename the @file{.ISD}, @file{.ISM}
and @file{.frm} files to which the table corresponds.
@end itemize

@item
In SQL statements, you can access tables from different databases
with the @code{db_name.tbl_name} syntax.  Some SQL servers provide
the same functionality but call this @code{User space}.
@strong{MySQL} dosen't support tablespaces like in:
@code{create table ralph.my_table...IN my_tablespace}.

@item
@code{LIKE} is allowed on numeric columns.

@item
Use of @code{INTO OUTFILE} and @code{STRAIGHT_JOIN} in a @code{SELECT}
statement. @xref{SELECT, , @code{SELECT}}.

@item
The @code{SQL_SMALL_RESULT} option in a @code{SELECT} statement.

@item
@code{EXPLAIN SELECT} to get a description on how tables are joined.

@item
Use of index names, indexes on a prefix of a field, and use of
@code{INDEX} or @code{KEY} in a @code{CREATE TABLE}
statement. @xref{CREATE TABLE, , @code{CREATE TABLE}}.

@item
Use of @code{CHANGE col_name}, @code{DROP col_name} or @code{DROP INDEX}
in an @code{ALTER TABLE} statement. @xref{ALTER TABLE, , @code{ALTER TABLE}}.

@item
Use of @code{IGNORE} in an @code{ALTER TABLE} statement.

@item
Use of multiple @code{ADD}, @code{ALTER}, @code{DROP} or @code{CHANGE}
clauses in an @code{ALTER TABLE} statement.

@item
Use of @code{DROP TABLE} with the keywords @code{IF EXISTS}.

@item
You can drop multiple tables with a single @code{DROP TABLE} statement.

@item
The @code{LIMIT} clause of the @code{DELETE} statement.

@item
The @code{DELAYED} clause of the @code{INSERT} and @code{REPLACE}
statements.

@item
The @code{LOW_PRIORITY} clause of the @code{INSERT}, @code{REPLACE},
@code{DELETE} and @code{UPDATE} statements.

@cindex Oracle compatibility
@cindex Compatibility, with Oracle
@item
Use of @code{LOAD DATA INFILE}. In many cases, this syntax is compatible with
Oracle's @code{LOAD DATA INFILE}. @xref{LOAD DATA, , @code{LOAD DATA}}.

@item
The @code{OPTIMIZE TABLE} statement.
@xref{OPTIMIZE TABLE, , @code{OPTIMIZE TABLE}}.

@item
The @code{SHOW} statement.
@xref{SHOW, , @code{SHOW}}.

@item
Strings may be enclosed by either @samp{"} or @samp{'}, not just by @samp{'}.

@item
Use of the escape @samp{\} character.

@item
The @code{SET OPTION} statement. @xref{SET OPTION, , @code{SET OPTION}}.

@item
You don't need to name all selected columns in the @code{GROUP BY} part.
This gives better performance for some very specific, but quite normal
queries.
@xref{Group by functions}.

@item
To make it easier for users that come from other SQL environments,
@strong{MySQL} supports aliases for many functions. For example, all
string functions support both ANSI SQL syntax and ODBC syntax.

@item
@strong{MySQL} understands the @code{||} and @code{&&} operators to mean
logical OR and AND, as in the C programming language.  In @strong{MySQL},
@code{||} and @code{OR} are synonyms, as are @code{&&} and @code{AND}.
Because of this nice syntax, @strong{MySQL} doesn't support
the ANSI SQL @code{||} operator for string concatenation; use
@code{CONCAT()} instead. Since @code{CONCAT()} takes any number
of arguments, it's easy to convert use of the @code{||} operator to
@strong{MySQL}.

@item
@code{CREATE DATABASE} or @code{DROP DATABASE}.
@xref{CREATE DATABASE, , @code{CREATE DATABASE}}.

@cindex PostgreSQL compatibility
@cindex Compatibility, with PostgreSQL
@item
The @code{%} operator is a synonym for @code{MOD()}.  That is,
@code{N % M} is equivalent to @code{MOD(N,M)}.  @code{%} is supported
for C programmers and for compatibility with PostgreSQL.

@item
The @code{=}, @code{<>}, @code{<=} ,@code{<}, @code{>=},@code{>},
@code{<<}, @code{>>}, @code{<=>}, @code{AND}, @code{OR} or @code{LIKE}
operators may be used in column comparisons to the left of the
@code{FROM} in @code{SELECT} statements.  For example:

@example
mysql> SELECT col1=1 AND col2=2 FROM tbl_name;
@end example

@item
The @code{LAST_INSERT_ID()} function.
@xref{mysql_insert_id, , @code{mysql_insert_id()}}.

@item
The @code{REGEXP} and @code{NOT REGEXP} extended regular expression
operators.

@item
@code{CONCAT()} or @code{CHAR()} with one argument or more than two
arguments.  (In @strong{MySQL}, these functions can take any number of
arguments.)

@item
The @code{BIT_COUNT()}, @code{ELT()}, @code{FROM_DAYS()}, @code{FORMAT()},
@code{IF()}, @code{PASSWORD()}, @code{ENCRYPT()},
@code{ENCODE()}, @code{DECODE()}, @code{PERIOD_ADD()},
@code{PERIOD_DIFF()}, @code{TO_DAYS()}, or @code{WEEKDAY()} functions.

@item
Use of @code{TRIM()} to trim substrings. ANSI SQL only supports removal
of single characters.

@item
The @code{GROUP BY} functions @code{STD()}, @code{BIT_OR()} and
@code{BIT_AND()}.

@item
Use of @code{REPLACE} instead of @code{DELETE} + @code{INSERT}.
@xref{REPLACE, , @code{REPLACE}}.

@item
The @code{FLUSH flush_option} statement.
@end itemize

@node Differences from ANSI, Missing functions, Extensions to ANSI, Compatibility
@section @strong{MySQL} differences compared to ANSI SQL92

We try to make @strong{MySQL} follow the ANSI SQL standard and the
ODBC SQL standard, but in some cases @strong{MySQL} does some things
differently:

@itemize @bullet
@item
@code{--} is not a comment. @xref{Missing comments}.
@item
For @code{VARCHAR} columns, trailing spaces are removed when the value is
stored. @xref{Bugs}.
@item
In some cases, @code{CHAR} columns are silently changed to @code{VARCHAR}
columns. @xref{Silent column changes}.
@item
Privileges for a table is not automatically revoked when you delete a
table. You must explicitly issue a @code{REVOKE} to revoke privileges for
a table. @xref{GRANT, , @code{GRANT}}.
@end itemize

@node Missing functions, Standards, Differences from ANSI, Compatibility
@section Functionality missing from @strong{MySQL}

The following functionality is missing in the current version of
@strong{MySQL}.  For a prioritized list indicating when new extensions may be
added to @strong{MySQL}, you should consult
@uref{http://www.mysql.com/Manual_split/manual_Todo.html, the online
@strong{MySQL} TODO list}. That is the latest version of the TODO list in
this manual. @xref{TODO}.

@menu
* Missing Sub-selects::         Sub-selects
* Missing SELECT INTO TABLE::   @code{SELECT INTO TABLE}
* Missing Transactions::        Transactions
* Missing Triggers::            Triggers
* Missing Foreign Keys::        Foreign Keys
* Missing Views::               Views
* Missing comments::            @samp{--} as the start of a comment
@end menu

@node Missing Sub-selects, Missing SELECT INTO TABLE, Missing functions, Missing functions
@subsection Sub-selects

The following will not yet work in @strong{MySQL}:

@example
SELECT * FROM table1 WHERE id IN (SELECT id FROM table2);
SELECT * FROM table1 WHERE id NOT IN (SELECT id FROM table2);
@end example

However, in many cases you can rewrite the query without a sub select:

@example
SELECT table1.* FROM table1,table2 WHERE table1.id=table2.id;
SELECT table1.* FROM table1 LEFT JOIN table2 ON table1.id=table2.id where table2.id IS NULL
@end example

For more complicated sub queries you can create temporary tables to hold the
sub query.

@strong{MySQL} only supports @code{INSERT ... SELECT ...} and @code{REPLACE
... SELECT ...} Independent sub-selects will be probably be available in
3.23.2.  You can now use the function @code{IN()} in other contexts,
however.

@node Missing SELECT INTO TABLE, Missing Transactions, Missing Sub-selects, Missing functions
@subsection @code{SELECT INTO TABLE}

@strong{MySQL} doesn't yet support the Oracle SQL extension:
@code{SELECT ... INTO TABLE ...}.  @strong{MySQL} supports instead the
ANSI SQL syntax @code{INSERT INTO ... SELECT ...}, which is basically
the same thing.

Alternatively, you can use @code{SELECT INTO OUTFILE...} or @code{CREATE
TABLE ... SELECT} to solve your problem.

@node Missing Transactions, Missing Triggers, Missing SELECT INTO TABLE, Missing functions
@subsection Transactions

Transactions are not supported. @strong{MySQL} shortly will support atomic
operations, which are like transactions without rollback. With atomic
operations, you can execute a group of @code{INSERT}/@code{SELECT}/whatever
commands and be guaranteed that no other thread will interfere. In this
context, you won't usually need rollback. Currently, you can prevent
interference from other threads by using the @code{LOCK TABLES} and
@code{UNLOCK TABLES} commands.
@xref{LOCK TABLES, , @code{LOCK TABLES}}.

@node Missing Triggers, Missing Foreign Keys, Missing Transactions, Missing functions
@subsection Stored procedures and triggers

A stored procedure is a set of SQL commands that can be compiled and stored
in the server. Once this has been done, clients don't need to keep reissuing
the entire query but can refer to the stored procedure. This provides better
performance because the query has to be parsed only once and less information
needs to be sent between the server and the client. You can also raise the
conceptual level by having libraries of functions in the server.

A trigger is a stored procedure that is invoked when a particular event
occurs.  For example, you can install a stored procedure that is triggered
each time a record is deleted from a transaction table and that automatically
deletes the corresponding customer from a customer table when all his
transactions are deleted.

The planned update language will be able to
handle stored procedures, but without triggers. Triggers usually slow
down everything, even queries for which they are not needed.

To see when @strong{MySQL} might get stored procedures, see @ref{TODO}.

@node Missing Foreign Keys, Missing Views, Missing Triggers, Missing functions
@subsection Foreign Keys

Note that foreign keys in SQL are not used to join tables, but are used
mostly for checking referential integrity.  If you want to get results from
multiple tables from a @code{SELECT} statement, you do this by joining
tables!

@example
SELECT * from table1,table2 where table1.id = table2.id;
@end example
@xref{JOIN, , @code{JOIN}}.

The @code{FOREIGN KEY} syntax in @strong{MySQL} exists only for compatibility
with other SQL vendors' @code{CREATE TABLE} commands; it doesn't do
anything.  The @code{FOREIGN KEY} syntax without @code{ON DELETE ...} is
mostly used for documentation purposes. Some ODBC applications may use this
to produce automatic @code{WHERE} clauses, but this is usually easy to
override. @code{FOREIGN KEY} is sometimes used as a constraint check, but
this check is unnecessary in practice if rows are inserted into the tables in
the right order. @strong{MySQL} only supports these clauses because some
applications require them to exist (regardless of whether or not they
work!).

In @strong{MySQL}, you can work around the problem of @code{ON DELETE
...} not being implemented by adding the appropriate @code{DELETE} statement to
an application when you delete records from a table that has a foreign key.
In practice this is as quick (in some cases quicker) and much more portable
than using foreign keys.

In the near future we will extend the @code{FOREIGN KEY} implementation so
that at least the information will be saved in the table specification file
and may be retrieved by @code{mysqldump} and ODBC.

@menu
* Broken Foreign KEY::          Reasons NOT to use foreign keys
@end menu

@node Broken Foreign KEY,  , Missing Foreign Keys, Missing Foreign Keys
@subsubsection Reasons NOT to use foreign keys

There are so many problems with @code{FOREIGN KEY}s that we don't
know where to start:

@itemize @bullet
@item
Foreign keys make life very complicated, because the foreign key definitions
must be stored in a database and implementing them would destroy the whole
``nice approach'' of using files that can be moved, copied and removed.

@item
The speed impact is terrible for @code{INSERT} and @code{UPDATE} statements,
and in this case almost all @code{FOREIGN KEY} checks are useless because you
usually insert records in the right tables in the right order, anyway.

@item
There is also a need to hold locks on many more tables when updating one
table, because the side effects can cascade through the entire database. It's
MUCH faster to delete records from one table first and subsequently delete
them from the other tables.

@item
You can no longer restore a table by doing a full delete from
the table and then restoring all records (from a new source or from a backup).

@item
If you have foreign keys you can't dump and restore tables unless you do so
in a very specific order.

@item
It's very easy to do ``allowed'' circular definitions that make the
tables impossible to recreate each table with a single create statement, even if
the definition works and is usable.
@end itemize

The only nice aspect of @code{FOREIGN KEY} is that it gives ODBC and some
other client programs the ability to see how a table is connected and to use
this to show connection diagrams and to help in building applicatons.

@strong{MySQL} will soon store @code{FOREIGN KEY} definitions so that
a client can ask for and receive an answer how the original connection was
made. The current @file{.frm} file format does not have any place for it.

@node Missing Views, Missing comments, Missing Foreign Keys, Missing functions
@subsection Views

@strong{MySQL} doesn't support views, but this is on the TODO.

@node Missing comments,  , Missing Views, Missing functions
@subsection @samp{--} as the start of a comment

Some other SQL databases use @samp{--} to start comments. @strong{MySQL}
has @samp{#} as the start comment character, even if the @code{mysql}
command line tool removes all lines that start with @samp{--}.
You can also use the C comment style @code{/* this is a comment */} with
@strong{MySQL}.
@xref{Comments}.

@strong{MySQL} will not support @samp{--}; this degenerate comment style has
caused many problems with automatically-generated SQL queries that have used
something like the following code, where we automatically insert the value of
the payment for @code{!payment!}:

@example
UPDATE tbl_name SET credit=credit-!payment!
@end example

What do you think will happen when the value of @code{payment} is negative?

Because @code{1--1} is legal in SQL, we think it is terrible that
@samp{--} means start comment.

If you have a SQL program in a text file that contains @samp{--} comments
you should use:

@example
shell> replace " --" " #" < text-file-with-funny-comments.sql \
         | mysql database
@end example

instead of the usual:

@example
shell> mysql database < text-file-with-funny-comments.sql
@end example

You can also edit the command file ``in place'' to change the @samp{--}
comments to @samp{#} comments:

@example
shell> replace " --" " #" -- text-file-with-funny-comments.sql
@end example

Change them back with this command:

@example
shell> replace " #" " --" -- text-file-with-funny-comments.sql
@end example

@node Standards, Commit-rollback, Missing functions, Compatibility
@section What standards does @strong{MySQL} follow?

Entry level SQL92. ODBC level 0-2.

@node Commit-rollback,  , Standards, Compatibility
@section How to cope without @code{COMMIT}-@code{ROLLBACK}

@strong{MySQL} doesn't support @code{COMMIT}-@code{ROLLBACK.} The problem is
that handling @code{COMMIT}-@code{ROLLBACK} efficiently would require a
completely different table layout than @strong{MySQL} uses today.
@strong{MySQL} would also need extra threads that do automatic cleanups on
the tables and the disk usage would be much higher. This would make
@strong{MySQL} about 2-4 times slower than it is today.  @strong{MySQL} is
much faster than almost all other SQL databases (typically at least 2-3 times
faster).  One of the reasons for this is the lack of
@code{COMMIT}-@code{ROLLBACK}.

For the moment, we are much more for implementing the SQL server
language (something like stored procedures). With this you would very
seldom really need @code{COMMIT}-@code{ROLLBACK.} This would also give much
better performance.

Loops that need transactions normally can be coded with the help of
@code{LOCK TABLES}, and you don't need cursors when you can update records
on the fly.

We have transactions and cursors on the TODO but not quite prioritized. If
we implement these, it will be as an option to @code{CREATE TABLE}. That
means that @code{COMMIT}-@code{ROLLBACK} will work only on those tables,
so that a speed penalty will be imposed on those table only.

We at TcX have a greater need for a real fast database than a 100%
general database. Whenever we find a way to implement these features without
any speed loss, we will probably do it. For the moment, there are many more
important things to do. Check the TODO for how we prioritize things at
the moment. (Customers with higher levels of support can alter this, so
things may be reprioritized.)

The current problem is actually @code{ROLLBACK}. Without @code{ROLLBACK}, you
can do any kind of @code{COMMIT} action with @code{LOCK TABLES}. To support
@code{ROLLBACK}, @strong{MySQL} would have to be changed to store all old
records that were updated and revert everything back to the starting point if
@code{ROLLBACK} was issued. For simple cases, this isn't that hard to do (the
current @code{isamlog} could be used for this purpose), but it would be much
more difficult to implement @code{ROLLBACK} for @code{ALTER/DROP/CREATE
TABLE}.

To avoid using @code{ROLLBACK}, you can use the following strategy:

@enumerate
@item
Use @code{LOCK TABLES ...} to lock all the tables you want to access.
@item
Test conditions.
@item
Update if everything is okay.
@item
Use @code{UNLOCK TABLES} to release your locks.
@end enumerate

This is usually a much faster method than using transactions with possible
@code{ROLLBACK}s, although not always. The only situation this solution
doesn't handle is when someone kills the threads in the middle of an
update. In this case, all locks will be released but some of the updates may
not have been executed.

You can also use functions to update records in a single operation.
You can get a very efficient application by using the following techniques:

@itemize @bullet
@item
Modify fields relative to their current value

@item
Update only those fields that actually have changed
@end itemize

For example, when we are doing updates to some customer information, we
update only the customer data that have changed and test only that none of
the changed data, or data that depend on the changed data, have changed
compared to the original row. The test for changed data is done with the
@code{WHERE} clause in the @code{UPDATE} statement. If the record wasn't
updated, we give the client a message: "Some of the data you have changed
have been changed by another user". Then we show the old row versus the new
row in a window, so the user can decide which version of the customer record
he should use.

This gives us something that is similar to ``column locking'' but is actually
even better, because we only update some of the columns, using values that
are relative to their current values.  This means that typical @code{UPDATE}
statements look something like these:

@example
UPDATE tablename SET pay_back=pay_back+'relative change';

UPDATE customer
  SET
    customer_date='current_date',
    address='new address',
    phone='new phone',
    money_he_owes_us=money_he_owes_us+'new_money'
  WHERE
    customer_id=id AND address='old address' AND phone='old phone';
@end example

As you can see, this is very efficient and works even if another client has
changed the values in the @code{pay_back} or @code{money_he_owes_us} columns.

@findex mysql_insert_id()
@findex LAST_INSERT_ID()
In many cases, users have wanted @code{ROLLBACK} and/or @code{LOCK
TABLES} for the purpose of managing unique identifiers for some tables. This
can be handled much more efficiently by using an @code{AUTO_INCREMENT} column
and either the SQL function @code{LAST_INSERT_ID()} or the C API function
@code{mysql_insert_id()}. @xref{mysql_insert_id, , @code{mysql_insert_id()}}.

@cindex Row-level locking
At TcX, we have never had any need for row-level locking because we have
always been able to code around it. Some cases really need row
locking, but they are very few. If you want row-level locking, you
can use a flag column in the table and do something like this:

@example
UPDATE tbl_name SET row_flag=1 WHERE id=ID;
@end example

@strong{MySQL} returns 1 for the number of affected rows if the row was
found and @code{row_flag} wasn't already 1 in the original row.

You can think of it as @strong{MySQL} changed the above query to:

@example
UPDATE tbl_name SET row_flag=1 WHERE id=ID and row_flag <> 1;
@end example

@node Privilege system, Reference, Compatibility, Top
@chapter The @strong{MySQL} access privilege system

@strong{MySQL} has an advanced but non-standard security/privilege
system.  This section describes how it works.

@menu
* What Privileges::             What the privilege system does
* User names::                  @strong{MySQL} user names and passwords
* Connecting::                  Connecting to the @strong{MySQL} server
* Password security::           Keeping your password secure
* Privileges provided::         Privileges provided by @strong{MySQL}
* Privileges::                  How the privilege system works
* Connection access::           Access control, stage 1: Connection verification
* Request access::              Access control, stage 2: Request verification
* Privilege changes::           When privilege changes take effect
* Default privileges::          Setting up the initial @strong{MySQL} privileges
* Adding users::                Adding new user privileges to @strong{MySQL}
* Passwords::                   How to set up passwords
* Access denied::               Causes of @code{Access denied} errors
* Security::                    How to make @strong{MySQL} secure against crackers
@end menu

@node What Privileges, User names, Privilege system, Privilege system
@section What the privilege system does

The primary function of the @strong{MySQL} privilege system is to
authenticate a user connecting from a given host, and to associate that user
with @strong{select}, @strong{insert}, @strong{update} and @strong{delete}
privileges on a database.

Additional functionality includes the ability to have an anonymous user and
to grant privileges for @strong{MySQL}-specific functions such as @code{LOAD
DATA INFILE} and administrative operations.

@node User names, Connecting, What Privileges, Privilege system
@section @strong{MySQL} user names and passwords

There are several distinctions between the way user names and passwords are
used by @strong{MySQL}, and the way they are used by Unix or Windows:

@itemize @bullet
@item
User names, as used by @strong{MySQL} for authentication purposes, have
nothing to do with Unix user names (login names) or Windows user names.  Most
@strong{MySQL} clients by default try to log in using the current Unix user
name as the @strong{MySQL} user name, but that is for convenience only.
Client programs allow a different name to be specified with the @code{-u} or
@code{--user} options. This means that you can't make a database secure in
any way unless all @strong{MySQL} user names have passwords.  Anyone may
attempt to connect to the server using any name, and they will succeed if
they specify any name that doesn't have a password.

@item
@strong{MySQL} user names can be up to 16 characters long; Unix user names
typically are limited to 8 characters.

@item
@strong{MySQL} passwords have nothing to do with Unix passwords.  There is no
necessary connection between the password you use to log in to a Unix machine
and the password you use to access a database on that machine.

@item
@strong{MySQL} encrypts passwords using a different algorithm than the one
used during the Unix login process.  See the descriptions of the
@code{PASSWORD()} and @code{ENCRYPT()} functions in @ref{Miscellaneous
functions}.
@end itemize

@node Connecting, Password security, User names, Privilege system
@section Connecting to the @strong{MySQL} server

@strong{MySQL} client programs generally require that you specify connection
parameters when you want to access a @strong{MySQL} server: the host you want
to connect to, your user name and your password.  For example, the
@code{mysql} client can be started like this (optional arguments are enclosed
between @samp{[} and @samp{]}):

@example
shell> mysql [-h host_name] [-u user_name] [-pyour_pass]
@end example

Alternate forms of the @code{-h}, @code{-u} and @code{-p} options are
@code{--host=host_name}, @code{--user=user_name} and
@code{--password=your_pass}.  Note that there is @emph{no space} between
@code{-p} or @code{--password=} and the password following it.

@emph{Note:} Specifing a password on the command line is not secure!
Any user on your system may then find out your password by typing a command
like: @code{ps auxww}.  @xref{Option files}.

@code{mysql} uses default values for connection parameters that are missing
from the command line:

@itemize @bullet
@item
The default hostname is @code{localhost}.

@item
The default user name is your Unix login name.

@item
No password is supplied if @code{-p} is missing.
@end itemize

Thus, for a Unix user @code{joe}, the following commands are equivalent:

@example
shell> mysql -h localhost -u joe
shell> mysql -h localhost
shell> mysql -u joe
shell> mysql
@end example

Other @strong{MySQL} clients behave similarly.

On Unix systems, you can specify different default values to be used when you
make a connection, so that you need not enter them on the command line each
time you invoke a client program.  This can be done in a couple of ways:

@itemize @bullet
@item
@tindex .my.cnf file
You can specify connection parameters in the @code{[client]} section of the
@file{.my.cnf} configuration file in your home directory.  The relevant
section of the file might look like this:

@example
[client]
host=host_name
user=user_name
password=your_pass
@end example

@xref{Option files}.

@item
@tindex MYSQL_HOST environment variable
@tindex Environment variable, MYSQL_HOST
@tindex MYSQL_PWD environment variable
@tindex Environment variable, MYSQL_PWD
@tindex USER environment variable
@tindex Environment variable, USER
@tindex LOGNAME environment variable
@tindex Environment variable, LOGNAME
@tindex LOGIN environment variable
@tindex Environment variable, LOGIN
You can specify connection parameters using environment values.  The host can
be specified using @code{MYSQL_HOST}.  The @strong{MySQL} user name can be
specified using @code{USER}, @code{LOGNAME} or @code{LOGIN} (although these
variables might already be set to your Unix login name, and it may be unwise
to change them).  The password can be specified using @code{MYSQL_PWD}
(but this is insecure; see next section).
@end itemize

@cindex Environment variables
If connection parameters are specified in multiple ways, values specified on
the command line take precedence over values specified in configuration files
and environment variables, and values in configuration files take precedence
over values in environment variables.

@node Password security, Privileges provided, Connecting, Privilege system
@section Keeping your password secure

It is inadvisable to specify your password in a way that exposes it to
discovery by other users.  The methods you can use to specify your password
when you run client programs are listed below, along with an assessment of
the risks of each method:

@itemize @bullet
@item
Use a @code{-pyour_pass} or @code{--password=your_pass} option on the command
line.  This is convenient but insecure, since your password becomes visible
to system status programs (such as @code{ps}) that may be invoked by other
users to display command lines.  (@strong{MySQL} clients typically overwrite
the command line argument with zeroes during their initialization sequence,
but there is still a brief interval during which the value is visible.)

@item
Use a @code{-p} or @code{--password} option (with no @code{your_pass} value
specified).  In this case, the client program solicits the password from
the terminal:

@example
shell> mysql -u user_name -p
Enter password: ********
@end example

The client echoes @samp{*} characters to the terminal as you enter your
password so that onlookers cannot see it.

It is more secure to enter your password this way than to specify it on the
command line because it is not visible to other users.  However, this method
of entering a password is suitable only for programs that you run
interactively.  If you want to invoke a client from a script that runs
non-interactively, there is no opportunity to enter the password from the
terminal.

@item
@tindex .my.cnf file
Store your password in a configuration file.  For example, you can list your
password in the @code{[client]} section of the @file{.my.cnf} file in your
home directory:

@example
[client]
password=your_pass
@end example

If you store your password in @file{.my.cnf}, the file should not be group or
world readable or writable.  Make sure the file's access mode is @code{400}
or @code{600}.

@xref{Option files}.
@item
You can store your password in the @code{MYSQL_PWD} environment variable, but
this method must be considered extremely insecure and should not be used.
Some versions of @code{ps} include an option to display the environment of
running processes; your password will be in plain sight for all to see if
you set @code{MYSQL_PWD}.  Even on systems without such a version of
@code{ps}, it is unwise to assume there is no other method to observe process
environments.
@end itemize

All in all, the safest methods are to have the client program prompt for the
password or to specify the password in a properly-protected @file{.my.cnf}
file.

@node Privileges provided, Privileges, Password security, Privilege system
@section Privileges provided by @strong{MySQL}

Privilege information is stored in the @code{user}, @code{db}, @code{host},
@code{tables_priv} and @code{columns_priv} tables in the @code{mysql}
database (that is, in the database named @code{mysql}).  The @strong{MySQL}
server reads the contents of these tables when it starts up and under the
circumstances indicated in @ref{Privilege changes}.

The names used in this manual to refer to the privileges provided by
@strong{MySQL} are shown below, along with the table column name associated
with each privilege in the grant tables and the context in which the
privilege applies:

@multitable @columnfractions .15 .25 .6
@item @strong{Privilege}  @tab @strong{Column}       @tab @strong{Context}
@item @strong{select}      @tab @code{Select_priv}   @tab tables
@item @strong{insert}      @tab @code{Insert_priv}   @tab tables
@item @strong{update}      @tab @code{Update_priv}   @tab tables
@item @strong{delete}      @tab @code{Delete_priv}   @tab tables
@item @strong{index}       @tab @code{Index_priv}    @tab tables
@item @strong{alter}       @tab @code{Alter_priv}    @tab tables
@item @strong{create}      @tab @code{Create_priv}   @tab databases, tables or indexes
@item @strong{drop}        @tab @code{Drop_priv}     @tab databases or tables
@item @strong{grant}       @tab @code{Grant_priv}    @tab databases or tables
@item @strong{reload}      @tab @code{Reload_priv}   @tab server administration
@item @strong{shutdown}    @tab @code{Shutdown_priv} @tab server administration
@item @strong{process}     @tab @code{Process_priv}  @tab server administration
@item @strong{file}        @tab @code{File_priv}     @tab file access on server
@end multitable

The @strong{select}, @strong{insert}, @strong{update} and @strong{delete}
privileges allow you to perform operations on rows in existing tables in
a database.

@code{SELECT} statements require the @strong{select} privilege only if they
actually retrieve rows from a table.  You can execute certain @code{SELECT}
statements even without permission to access any of the databases on the
server.  For example, you could use the @code{mysql} client as a simple
calculator:

@example
mysql> SELECT 1+1;
mysql> SELECT PI()*2;
@end example

The @strong{index} privilege allows you to create or drop (remove) indexes.

The @strong{alter} privilege allows you to use @code{ALTER TABLE}.

The @strong{create} and @strong{drop} privileges allow you to create new
databases and tables, or to drop (remove) existing databases and tables.

Note that if you grant the @strong{drop} privilege for the @code{mysql}
database to a user, that user can drop the database in which the
@strong{MySQL} access privileges are stored!

The @strong{grant} privilege allows you to give to other users those
privileges you yourself possess.

The @strong{file} privilege gives you permission to read and write files on
the server using the @code{LOAD DATA INFILE} and @code{SELECT ... INTO
OUTFILE} statements.  Any user to whom this privilege is granted can read or
write any file that the @strong{MySQL} server can read or write.

The remaining privileges are used for administrative operations, which are
performed using the @code{mysqladmin} program.  The table below shows which
@code{mysqladmin} commands each administrative privilege allows you to
execute:

@multitable @columnfractions .15 .85
@item @strong{Privilege}  @tab @strong{Commands permitted to privilege holders}
@item @strong{reload}     @tab @code{reload}, @code{refresh},
@code{flush-privileges},
@code{flush-hosts}, @code{flush-logs}, @code{flush-tables}
@item @strong{shutdown}   @tab @code{shutdown}
@item @strong{process}    @tab @code{processlist}, @code{kill}
@end multitable

The @code{reload} command tells the server to reread the grant tables.  The
@code{refresh} command flushes all tables and opens and closes the log
files.  @code{flush-privileges} is a synonym for @code{reload}.  The other
@code{flush-*} commands perform functions similar to @code{refresh} but are
more limited in scope, and may be preferable in some instances.  For example,
if you want to flush just the log files, @code{flush-logs} is a better choice
than @code{refresh}.

The @code{shutdown} command shuts down the server.

The @code{processlist} command displays information about the threads
executing within the server.  The @code{kill} command kills server threads.
You can always display or kill your own threads, but you need the
@strong{process} privilege to display or kill threads initiated by other
users.

It is a good idea in general to grant privileges only to those users who need
them, but you should exercise particular caution in granting certain
privileges:

@itemize @bullet
@item
The @strong{grant} privilege allows users to give away their privileges to
other users.  Two users with different privileges and with the @strong{grant}
privilege are able to combine privileges.

@item
The @strong{alter} privilege may be used to subvert the privilege system
by renaming tables.

@item
The @strong{file} privilege can be abused to read any world-readable file on
the server into a database table, the contents of which can then be
accessed using @code{SELECT}.

@item
The @strong{shutdown} privilege can be abused to deny service to other
users entirely, by terminating the server.

@item
The @strong{process} privilege can be used to view the plain text of
currently executing queries, including queries that set or change passwords.

@item
Privileges on the @code{mysql} database can be used to change passwords and
other access privilege information.  (Passwords are stored encrypted, so a
malicious user cannot simply read them.  However, with sufficient privileges,
that same user can replace a password with a different one.)
@end itemize

There are some things that you cannot do with the @strong{MySQL}
privilege system:

@itemize @bullet
@item
You cannot explicitly specify that a given user should be denied access.
That is, you cannot explicitly match a user and then refuse the connection.

@item
You cannot specify that a user has privileges to create or drop tables
in a database but not to create or drop the database itself.
@end itemize

@node Privileges, Connection access, Privileges provided, Privilege system
@section How the privilege system works

The @strong{MySQL} privilege system ensures that all users may do exactly the
things that they are supposed to be allowed to do.  When you connect to a
@strong{MySQL} server, your identity is determined by @strong{the host from
which you connect} and @strong{the user name you specify}.  The system grants
privileges according to your identity and @strong{what you want to do}.

@strong{MySQL} considers both your hostname and user name in identifying you
because there is little reason to assume that a given user name belongs to
the same person everywhere on the Internet.  For example, the user
@code{bill} who connects from @code{whitehouse.gov} need not be the same
person as the user @code{bill} who connects from @code{microsoft.com}.
@strong{MySQL} handles this by allowing you to distinguish users on different
hosts that happen to have the same name:  you can grant @code{bill} one set
of privileges for connections from @code{whitehouse.gov}, and a different set
of privileges for connections from @code{microsoft.com}.

@strong{MySQL} access control involves two stages:

@itemize @bullet
@item
Stage 1: The server checks whether or not you are even allowed to connect.

@item
Stage 2: Assuming you can connect, the server checks each request you issue
to see whether or not you have sufficient privileges to perform it.  For
example, if you try to select rows from a table in a database or drop a table
from the database, the server makes sure you have the @strong{select}
privilege for the table or the @strong{drop} privilege for the database.
@end itemize

The server uses the @code{user}, @code{db} and @code{host} tables in the
@code{mysql} database at both stages of access control.  The fields in these
grant tables are shown below:

@multitable @columnfractions .2 .25 .25 .25
@item @strong{Table name} @tab @code{user} @tab @code{db} @tab @code{host}

@item @strong{Scope fields} @tab @code{Host}          @tab @code{Host}        @tab @code{Host}
@item @tab @code{User}          @tab @code{Db}          @tab @code{Db}
@item @tab @code{Password}      @tab @code{User}        @tab

@item @strong{Privilege fields} @tab @code{Select_priv}   @tab @code{Select_priv} @tab @code{Select_priv}
@item @tab @code{Insert_priv}   @tab @code{Insert_priv} @tab @code{Insert_priv}
@item @tab @code{Update_priv}   @tab @code{Update_priv} @tab @code{Update_priv}
@item @tab @code{Delete_priv}   @tab @code{Delete_priv} @tab @code{Delete_priv}
@item @tab @code{Index_priv}    @tab @code{Index_priv}  @tab @code{Index_priv}
@item @tab @code{Alter_priv}    @tab @code{Alter_priv}  @tab @code{Alter_priv}
@item @tab @code{Create_priv}   @tab @code{Create_priv} @tab @code{Create_priv}
@item @tab @code{Drop_priv}     @tab @code{Drop_priv}   @tab @code{Drop_priv}
@item @tab @code{Grant_priv}    @tab @code{Grant_priv}  @tab @code{Grant_priv}
@item @tab @code{Reload_priv}   @tab                    @tab
@item @tab @code{Shutdown_priv} @tab                    @tab
@item @tab @code{Process_priv}  @tab                    @tab
@item @tab @code{File_priv}     @tab                    @tab
@end multitable

For the second stage of access control (request verification), the server
may, if the request involves tables, additionally consult the
@code{tables_priv} and @code{columns_priv} tables.  The fields in these
tables are shown below:

@multitable @columnfractions .2 .25 .25
@item @strong{Table name}   @tab @code{tables_priv} @tab @code{columns_priv}

@item @strong{Scope fields} @tab @code{Host}        @tab @code{Host}
@item                       @tab @code{Db}          @tab @code{Db}
@item                       @tab @code{User}        @tab @code{User}
@item                       @tab @code{Table_name}  @tab @code{Table_name}
@item                       @tab                    @tab @code{Column_name}

@item @strong{Privilege fields} @tab @code{Table_priv}   @tab @code{Column_priv}
@item                           @tab @code{Column_priv}  @tab

@item @strong{Other fields} @tab @code{Timestamp}   @tab @code{Timestamp}
@item                       @tab @code{Grantor}     @tab
@end multitable

Each grant table contains scope fields and privilege fields.

Scope fields determine the scope of each entry in the tables, i.e., the
context in which the entry applies.  For example, a @code{user} table entry
with @code{Host} and @code{User} values of @code{'thomas.loc.gov'} and
@code{'bob'} would be used for authenticating connections made to the server
by @code{bob} from the host @code{thomas.loc.gov}.  Similarly, a @code{db}
table entry with @code{Host}, @code{User} and @code{Db} fields of
@code{'thomas.loc.gov'}, @code{'bob'} and @code{'reports'} would be used when
@code{bob} connects from the host @code{thomas.loc.gov} to access the
@code{reports} database.  The @code{tables_priv} and @code{columns_priv}
tables contain scope fields indicating tables or table/column combinations
to which each entry applies.

@cindex Case sensitivity, in access checking
For access-checking purposes, comparisons of @code{Host} values are
case insensitive.  @code{User}, @code{Password}, @code{Db} and
@code{Table_name} values are case sensitive.
@code{Column_name} values are case insensitive in @strong{MySQL} 3.22.12
or later.

Privilege fields indicate the privileges granted by a table entry, that is,
what operations can be performed.  The server combines the information in the
various grant tables to form a complete description of a user's privileges.
The rules used to do this are described in @ref{Request access}.

Scope fields are strings, declared as shown below; the default value for
each is the empty string:

@multitable @columnfractions .15 .15 .7
@item @strong{Field name} @tab @strong{Type}
@item @code{Host}         @tab @code{CHAR(60)}
@item @code{User}         @tab @code{CHAR(16)}
@item @code{Password}     @tab @code{CHAR(16)}
@item @code{Db}           @tab @code{CHAR(64)} @tab (@code{CHAR(60)} for the
@code{tables_priv} and @code{columns_priv} tables)
@end multitable

In the @code{user}, @code{db} and @code{host} tables,
all privilege fields are declared as @code{ENUM('N','Y')} --- each can have a
value of @code{'N'} or @code{'Y'}, and the default value is @code{'N'}.

In the @code{tables_priv} and @code{columns_priv} tables, the privilege
fields are declared as @code{SET} fields:

@multitable @columnfractions .2 .2 .6
@item @strong{Table name} @tab @strong{Field name} @tab @strong{Possible set elements}
@item @code{tables_priv} @tab @code{Table_priv} @tab @code{'Select', 'Insert',
'Update', 'Delete', 'Create', 'Drop', 'Grant', 'References', 'Index', 'Alter'}
@item @code{tables_priv} @tab @code{Column_priv} @tab @code{'Select', 'Insert',
'Update', 'References'}
@item @code{columns_priv} @tab @code{Column_priv} @tab @code{'Select', 'Insert',
'Update', 'References'}
@end multitable

Briefly, the server uses the grant tables like this:

@itemize @bullet
@item
The @code{user} table scope fields determine whether to allow or reject
incoming connections.  For allowed connections, the privilege fields indicate
the user's global (superuser) privileges.

@item
The @code{db} and @code{host} tables are used together:

@itemize @minus
@item
The @code{db} table scope fields determine which users can access which
databases from which hosts.  The privilege fields determine which operations
are allowed.

@item
The @code{host} table is used as an extension of the @code{db} table when you
want a given @code{db} table entry to apply to several hosts.  For example,
if you want a user to be able to use a database from several hosts in
your network, leave the @code{Host} value empty in the user's @code{db} table
entry, then populate the @code{host} table with an entry for each of those
hosts.  This mechanism is described more detail in @ref{Request access}.
@end itemize

@item
The @code{tables_priv} and @code{columns_priv} tables are similar to
the @code{db} table, but are more fine-grained: they apply at the
table and column level rather than at the database level.
@end itemize

Note that administrative privileges (@strong{reload}, @strong{shutdown},
etc.) are specified only in the @code{user} table.  This is because
administrative operations are operations on the server itself and are not
database-specific, so there is no reason to list such privileges in the
other grant tables.  In fact, only the @code{user} table need
be consulted to determine whether or not you can perform an administrative
operation.

The @strong{file} privilege is specified only in the @code{user} table, too.
It is not an administrative privilege as such, but your ability to read or
write files on the server host is independent of the database you are
accessing.

The @code{mysqld} server reads the contents of the grant tables once, when it
starts up.  Changes to the grant tables take effect as indicated in
@ref{Privilege changes}.

When you modify the contents of the grant tables, it is a good idea to make
sure that your changes set up privileges the way you want.  For help in
diagnosing problems, see @ref{Access denied}.  For advice on security issues,
@ref{Security}.

A useful
diagnostic tool is the @code{mysqlaccess} script, which Yves Carlier has
provided for the @strong{MySQL} distribution.  Invoke @code{mysqlaccess} with
the @code{--help} option to find out how it works.
Note that @code{mysqlaccess} checks access using only the @code{user},
@code{db} and @code{host} tables.  It does not check table- or column-level
privileges.

@node Connection access, Request access, Privileges, Privilege system
@section Access control, stage 1: Connection verification

When you attempt to connect to a @strong{MySQL} server, the server accepts or
rejects the connection based on your identity and whether or not you can
verify your identity by supplying the correct password.  If not, the server
denies access to you completely.  Otherwise, the server accepts the
connection, then enters stage 2 and waits for requests.

Your identity is based on two pieces of information:

@itemize @bullet
@item
The host from which you connect

@item
Your @strong{MySQL} user name
@end itemize

Identity checking is performed using the three @code{user} table scope fields
(@code{Host}, @code{User} and @code{Password}).  The server accepts the
connection only if a @code{user} table entry matches your hostname and user
name, and you supply the correct password.

Values in the @code{user} table scope fields may be specified as follows:

@itemize @bullet
@item
A @code{Host} value may be a hostname or an IP number, or @code{'localhost'}
to indicate the local host.

@item
@cindex Wildcards, in @code{mysql.user} table
You can use the wildcard characters @samp{%} and @samp{_} in the @code{Host}
field.

@item
A @code{Host} value of @code{'%'} matches any hostname.  A blank @code{Host}
value is equivalent to @code{'%'}.  Note that these values match @emph{any
host that can create a connection to your server!}

@item
@cindex Anonymous user
Wildcard characters are not allowed in the @code{User} field, but you can
specify a blank value, which matches any name.  If the @code{user} table
entry that matches an incoming connection has a blank user name, the user is
considered to be the anonymous user (the user with no name), rather than the
name that the client actually specified.  This means that a blank user name
is used for all further access checking for the duration of the connection
(that is, during stage 2).

@item
The @code{Password} field can be blank.  This does not mean that any password
matches, it means the user must connect without specifying a password.
@end itemize

@findex PASSWORD()
Non-blank @code{Password} values represent encrypted passwords.
@strong{MySQL} does not store passwords in plaintext form for anyone to see.
Rather, the password supplied by a user who is attempting to connect is
encrypted (using the @code{PASSWORD()} function) and compared to the
already-encrypted version stored in the @code{user} table.  If they match,
the password is correct.

The examples below show how various combinations of @code{Host} and
@code{User} values in @code{user} table entries apply to incoming
connections:

@multitable @columnfractions .25 .15 .60
@item @code{Host} @strong{value} @tab @code{User} @strong{value} @tab @strong{Connections matched by entry}
@item @code{'thomas.loc.gov'} @tab @code{'fred'} @tab @code{fred}, connecting from @code{thomas.loc.gov}
@item @code{'thomas.loc.gov'} @tab @code{''} @tab Any user, connecting from @code{thomas.loc.gov}
@item  @code{'%'} @tab @code{'fred'} @tab @code{fred}, connecting from any host
@item @code{'%'} @tab  @code{''} @tab Any user, connecting from any host
@item @code{'%.loc.gov'} @tab @code{'fred'} @tab @code{fred}, connecting from any host in the @code{loc.gov} domain
@item @code{'x.y.%'} @tab @code{'fred'} @tab @code{fred}, connecting from @code{x.y.net}, @code{x.y.com},@code{x.y.edu}, etc. (this is probably not useful)
@item @code{'144.155.166.177'} @tab @code{'fred'} @tab @code{fred}, connecting from the host with IP address @code{144.155.166.177}
@item @code{'144.155.166.%'} @tab @code{'fred'} @tab @code{fred}, connecting from any host in the @code{144.155.166} class C subnet
@end multitable

Since you can use IP wildcard values in the @code{Host} field (e.g.,
@code{'144.155.166.%'} to match every host on a subnet), there is the
possibility that someone might try to exploit this capability by naming a
host @code{144.155.166.somewhere.com}.  To foil such attempts, @strong{MySQL}
disallows matching on hostnames that start with digits and a dot. Thus, if
you have a host named something like @code{1.2.foo.com}, its name will never
match the @code{Host} column of the grant tables.  Only an IP number can
match an IP wildcard value.

An incoming connection may be matched by more than one entry in the
@code{user} table.  For example, a connection from @code{thomas.loc.gov} by
@code{fred} would be matched by several of the entries just shown above.  How
does the server choose which entry to use if more than one matches?  The
server resolves this question by sorting the @code{user} table after reading
it at startup time, then looking through the entries in sorted order when a
user attempts to connect.  The first matching entry is the one that is used.

@code{user} table sorting works as follows.  Suppose the @code{user} table
looks like this:

@example
+-----------+----------+-
| Host      | User     | ...
+-----------+----------+-
| %         | root     | ...
| %         | jeffrey  | ...
| localhost | root     | ...
| localhost |          | ...
+-----------+----------+-
@end example

When the server reads in the table, it orders the entries with the
most-specific @code{Host} values first (@code{'%'} in the @code{Host} column
means ``any host'' and is least specific).  Entries with the same @code{Host}
value are ordered with the most-specific @code{User} values first (a blank
@code{User} value means ``any user'' and is least specific).  The resulting
sorted @code{user} table looks like this:

@example
+-----------+----------+-
| Host      | User     | ...
+-----------+----------+-
| localhost | root     | ...
| localhost |          | ...
| %         | jeffrey  | ...
| %         | root     | ...
+-----------+----------+-
@end example

@cindex Grant tables, sorting
@cindex Sorting, grant tables
@cindex @code{user} table, sorting
When a connection is attempted, the server looks through the sorted entries
and uses the first match found.  For a connection from @code{localhost} by
@code{jeffrey}, the entries with @code{'localhost'} in the @code{Host} column
match first.  Of those, the entry with the blank user name matches both the
connecting hostname and user name.  (The @code{'%'/'jeffrey'} entry would
have matched, too, but it is not the first match in the table.)

Here is another example.  Suppose the @code{user} table looks like this:

@example
+----------------+----------+-
| Host           | User     | ...
+----------------+----------+-
| %              | jeffrey  | ...
| thomas.loc.gov |          | ...
+----------------+----------+-
@end example

The sorted table looks like this:

@example
+----------------+----------+-
| Host           | User     | ...
+----------------+----------+-
| thomas.loc.gov |          | ...
| %              | jeffrey  | ...
+----------------+----------+-
@end example

A connection from @code{thomas.loc.gov} by @code{jeffrey} is matched by the
first entry, whereas a connection from @code{whitehouse.gov} by
@code{jeffrey} is matched by the second.

A common misconception is to think that for a given user name, all entries
that explicitly name that user will be used first when the server attempts to
find a match for the connection.  This is simply not true.  The previous
example illustrates this, where a connection from @code{thomas.loc.gov} by
@code{jeffrey} is first matched not by the entry containing @code{'jeffrey'}
as the @code{User} field value, but by the entry with no user name!

If you have problems connecting to the server, print out the @code{user}
table and sort it by hand to see where the first match is being made.

@node Request access, Privilege changes, Connection access, Privilege system
@section Access control, stage 2: Request verification

Once you establish a connection, the server enters stage 2.  For each request
that comes in on the connection, the server checks whether you have
sufficient privileges to perform it, based on the type of operation you wish
to perform.  This is where the privilege fields in the grant tables come into
play.  These privileges can come from any of the @code{user}, @code{db},
@code{host}, @code{tables_priv} or @code{columns_priv} tables.  The grant
tables are manipulated with @code{GRANT} and @code{REVOKE} commands.
@xref{GRANT, , @code{GRANT}}.  (You may find it helpful to refer to
@ref{Privileges}, which lists the fields present in each of the grant
tables.)

The @code{user} table grants privileges that are assigned to you on a global
basis and that apply no matter what the current database is.  For example, if
the @code{user} table grants you the @strong{delete} privilege, you can
delete rows from any database on the server host!  In other words,
@code{user} table privileges are superuser privileges.  It is wise to grant
privileges in the @code{user} table only to superusers such as server or
database administrators.  For other users, you should leave the privileges
in the @code{user} table set to @code{'N'} and grant privileges on a
database-specific basis only, using the @code{db} and @code{host} tables.

@cindex Anonymous user
@cindex Wildcards, in @code{mysql.db} table
@cindex Wildcards, in @code{mysql.host} table
The @code{db} and @code{host} tables grant database-specific privileges.
Values in the scope fields may be specified as follows:

@itemize @bullet
@item
The
wildcard characters @samp{%} and @samp{_} can be used in the @code{Host} and
@code{Db} fields of either table.

@item
A @code{'%'} @code{Host} value in the @code{db} table means ``any host.'' A
blank @code{Host} value in the @code{db} table means ``consult the
@code{host} table for further information.''

@item
A @code{'%'} or blank @code{Host} value in the @code{host} table means ``any
host.''

@item
A @code{'%'} or blank @code{Db} value in either table means ``any database.''

@item
A blank @code{User} value in either table matches the anonymous user.
@end itemize

@cindex Grant tables, sorting
@cindex Sorting, grant tables
@cindex @code{db} table, sorting
@cindex @code{host} table, sorting
The @code{db} and @code{host} tables are read in and sorted when the server
starts up (at the same time that it reads the @code{user} table).  The
@code{db} table is sorted on the @code{Host}, @code{Db} and @code{User} scope
fields, and the @code{host} table is sorted on the @code{Host} and @code{Db}
scope fields.  As with the @code{user} table, sorting puts the most-specific
values first and least-specific values last, and when the server looks for
matching entries, it uses the first match that it finds.


@cindex Wildcards, in @code{mysql.tables_priv} table
@cindex Wildcards, in @code{mysql.columns_priv} table
The @code{tables_priv} and @code{columns_priv} tables grant table- and
column-specific privileges.  Values in the scope fields may be specified as
follows:

@itemize @bullet
@item
The wildcard characters @samp{%} and @samp{_}
can be used in the @code{Host} field of either table.

@item
A @code{'%'} or blank @code{Host} value in either table means ``any host.''

@item
The @code{Db}, @code{Table_name} and @code{Column_name} fields cannot contain
wildcards or be blank in either table.
@end itemize

The @code{tables_priv} and @code{columns_priv} tables are sorted on
the @code{Host}, @code{Db} and @code{User} fields.  This is similar to
@code{db} table sorting, although since only the @code{Host} field may
contain wildcards, the sorting is simpler.

The request verification process is described below.  (If you are familiar
with the access-checking source code, you will notice that the description
here differs slightly from the algorithm used in the code.  The description
is equivalent to what the code actually does; it differs only to make the
explanation simpler.)

For administrative requests (@strong{shutdown}, @strong{reload}, etc.), the
server checks only the @code{user} table entry, since that is the only table
that specifies administrative privileges.  Access is granted if the entry
allows the requested operation and denied otherwise.  For example, if you
want to execute @code{mysqladmin shutdown} but your @code{user} table entry
doesn't grant the @strong{shutdown} privilege to you, access is denied
without even checking the @code{db} or @code{host} tables.  (Since they
contain no @code{Shutdown_priv} column, there is no need to do so.)

For database-related requests (@strong{insert}, @strong{update}, etc.), the
server first checks the user's global (superuser) privileges by looking in
the @code{user} table entry.  If the entry allows the requested operation,
access is granted.  If the global privileges in the @code{user} table are
insufficient, the server determines the user's database-specific privileges
by checking the @code{db} and @code{host} tables:

@enumerate
@item
The server looks in the @code{db} table for a match on the @code{Host},
@code{Db} and @code{User} fields.  @code{Host} and @code{User} are matched to
the connecting user's hostname and @strong{MySQL} user name.  The @code{Db}
field is matched to the database the user wants to access.  If there is no
entry for the @code{Host} and @code{User}, access is denied.

@item
If there is a matching @code{db} table entry and its @code{Host} field is
not blank, that entry defines the user's database-specific privileges.

@item
If the matching @code{db} table entry's @code{Host} field is blank, it
signifies that the @code{host} table enumerates which hosts should be allowed
access to the database.  In this case, a further lookup is done in the
@code{host} table to find a match on the @code{Host} and @code{Db} fields.
If no @code{host} table entry matches, access is denied.  If there is a
match, the user's database-specific privileges are computed as the
intersection (@emph{not} the union!) of the privileges in the @code{db} and
@code{host} table entries, i.e., the privileges that are @code{'Y'} in both
entries.  (This way you can grant general privileges in the @code{db} table
entry and then selectively restrict them on a host-by-host basis using the
@code{host} table entries.)
@end enumerate

After determining the database-specific privileges granted by the @code{db}
and @code{host} table entries, the server adds them to the global privileges
granted by the @code{user} table.  If the result allows the requested
operation, access is granted.  Otherwise, the server checks the user's
table and column privileges in the @code{tables_priv} and @code{columns_priv}
tables and adds those to the user's privileges.  Access is allowed or denied
based on the result.

Expressed in boolean terms, the preceding description of how a user's
privileges are calculated may be summarized like this:

@example
global privileges
OR (database privileges AND host privileges)
OR table privileges
OR column privileges
@end example

It may not be apparent why, if the global @code{user} entry privileges are
initially found to be insufficient for the requested operation, the server
adds those privileges to the database-, table- and column-specific privileges
later. The reason is that a request might require more than one type of
privilege.  For example, if you execute an @code{INSERT ...  SELECT}
statement, you need both @strong{insert} and @strong{select} privileges.
Your privileges might be such that the @code{user} table entry grants one
privilege and the @code{db} table entry grants the other.  In this case, you
have the necessary privileges to perform the request, but the server cannot
tell that from either table by itself; the privileges granted by both entries
must be combined.

The @code{host} table can be used to maintain a list of ``secure'' servers.
At TcX, the @code{host} table contains a list of all machines on the local
network. These are granted all privileges.

You can also use the @code{host} table to indicate hosts that are @emph{not}
secure.  Suppose you have a machine @code{public.your.domain} that is located
in a public area that you do not consider secure.  You can allow access to
all hosts on your network except that machine by using @code{host} table
entries
like this:

@example
+--------------------+----+-
| Host               | Db | ...
+--------------------+----+-
| public.your.domain | %  | ... (all privileges set to 'N')
| %.your.domain      | %  | ... (all privileges set to 'Y')
+--------------------+----+-
@end example

Naturally, you should always test your entries in the grant tables (e.g.,
using @code{mysqlaccess}) to make sure your access privileges are actually
set up the way you think they are.

@node Privilege changes, Default privileges, Request access, Privilege system
@section When privilege changes take effect

When @code{mysqld} starts, all grant table contents are read into memory and
become effective at that point.

Modifications to the grant tables that you perform using @code{GRANT},
@code{REVOKE}, or @code{SET PASSWORD} are noticed by the server immediately.

If you modify the grant tables manually (using @code{INSERT}, @code{UPDATE},
etc.), you should execute a @code{FLUSH PRIVILEGES} statement or run
@code{mysqladmin flush-privileges} to tell the server to reload the grant
tables.  Otherwise your changes will have @emph{no effect} until
you restart the server.

When the server notices that the grant tables have been changed,
existing client connections are affected as follows:

@itemize @bullet
@item
Table and column privilege changes take effect with the client's next
request.

@item
Database privilege changes take effect at the next @code{USE db_name}
command.
@end itemize

Global privilege changes and password changes take effect the next time the
client connects.

@node Default privileges, Adding users, Privilege changes, Privilege system
@section Setting up the initial @strong{MySQL} privileges

After installing @strong{MySQL}, you set up the initial access privileges by
running @code{scripts/mysql_install_db}.
@xref{Quick install}.
The @code{scripts/mysql_install_db} script starts up the @code{mysqld}
server, then initializes the grant tables to contain the following set
of privileges:

@itemize @bullet
@item
The @strong{MySQL} @code{root} user is created as a superuser who can do
anything.  Connections must be made from the local host.

@strong{Note:}
The initial @code{root} password is empty, so anyone can connect as @code{root}
@emph{without a password} and be granted all privileges.

@item
@cindex Anonymous user
An anonymous user is created that can do anything with databases that have a
name of @code{'test'} or starting with @code{'test_'}.  Connections must be
made from the local host.  This means any local user can connect and be
treated as the anonymous user.

@item
Other privileges are denied.  For example, normal users can't use
@code{mysqladmin shutdown} or @code{mysqladmin processlist}.
@end itemize

@strong{Note:} The default privileges are different for Win32.
@xref{Win32 running}.


Since your installation is initially wide open, one of the first things you
should do is specify a password for the @strong{MySQL}
@code{root} user.  You can do this as follows (note that you specify the
password using the @code{PASSWORD()} function):

@example
shell> mysql -u root mysql
mysql> UPDATE user SET Password=PASSWORD('new_password')
           WHERE user='root';
mysql> FLUSH PRIVILEGES;
@end example

You can also use the @code{SET PASSWORD} statement:

@example
shell> mysql -u root mysql
mysql> SET PASSWORD FOR root=PASSWORD('new_password');
@end example

Another way to set the password is by using the @code{mysqladmin} command:

@example
shell> mysqladmin -u root password new_password
@end example

Note that if you update the password in the @code{user} table directly using
the first method, you must tell the server to reread the grant tables (with
@code{FLUSH PRIVILEGES}), since the change will go unnoticed otherwise.

Once the @code{root} password has been set, thereafter you must supply that
password when you connect to the server as @code{root}.

You may wish to leave the @code{root} password blank so that you don't need
to specify it while you perform additional setup or testing, but be sure to
set it before using your installation for any real production work.

See the @code{scripts/mysql_install_db} script to see how it sets up
the default privileges.  You can use this as a basis to see how to
add other users.

If you want the initial privileges to be different than those just described
above, you can modify @code{mysql_install_db} before you run it.

To recreate the grant tables completely, remove all the @file{*.frm},
@file{*.ISM} and @file{*.ISD} files in the directory containing the
@code{mysql} database.  (This is the directory named @file{mysql} under
the database directory, which is listed when you run @code{mysqld
--help}.) Then run the @code{mysql_install_db} script, possibly after
editing it first to have the privileges you want.

@strong{NOTE:} For @strong{MySQL} versions before 3.22.10, you should NOT
delete the @file{*.frm} files.  If you accidentally do this, you should
copy them back from your @strong{MySQL} distribution before running
@code{mysql_install_db}.

@node Adding users, Passwords, Default privileges, Privilege system
@section Adding new user privileges to @strong{MySQL}

You can add users two different ways: by using @code{GRANT} statements
or by manipulating the @strong{MySQL} grant tables directly.  The
preferred method is to use @code{GRANT} statements, because they are
more concise and less error-prone.

The examples below show how to use the @code{mysql} client to set up new
users.  These examples assume that privileges are set up according to the
defaults described in the previous section.  This means that to make changes,
you must be on the same machine where @code{mysqld} is running, you must
connect as the @strong{MySQL} @code{root} user, and the @code{root} user must
have the @strong{insert} privilege for the @code{mysql} database and the
@strong{reload} administrative privilege.  Also, if you have changed the
@code{root} user password, you must specify it for the @code{mysql} commands
below.

You can add new users by issuing @code{GRANT} statements:

@example
shell> mysql --user=root mysql
mysql> GRANT ALL PRIVILEGES ON *.* TO monty@@localhost
           IDENTIFIED BY 'something' WITH GRANT OPTION;
mysql> GRANT ALL PRIVILEGES ON *.* TO monty@@"%"
           IDENTIFIED BY 'something' WITH GRANT OPTION;
mysql> GRANT RELOAD,PROCESS ON *.* TO admin@@localhost;
mysql> GRANT USAGE ON *.* TO dummy@@localhost;
@end example

These @code{GRANT} statements set up three new users:

@table @code
@item monty
A full superuser who can connect to the server from anywhere, but who must
use a password (@code{'something'} to do so.  Note that we must issue
@code{GRANT} statements for both @code{monty@@localhost} and
@code{monty@@"%"}.  If we don't add the entry with @code{localhost}, the
anonymous user entry for @code{localhost} that is created by
@code{mysql_install_db} will take precedence when we connect from the local
host, because it has a more specific @code{Host} field value and thuse comes
earlier in the @code{user} table sort order.

@item admin
A user who can connect from @code{localhost} without a password and who is
granted the @strong{reload} and @strong{process} administrative privileges.
This allows the user to execute the @code{mysqladmin reload},
@code{mysqladmin refresh} and @code{mysqladmin flush-*} commands, as well as
@code{mysqladmin processlist} .  No database-related privileges are granted.
They can be granted later by issuing additional @code{GRANT} statements.

@item dummy
A user who can connect without a password, but only from the local host.  The
global privileges are all set to @code{'N'} --- the @code{USAGE} privilege
type allows you to set up a user with no privileges.  It is assumed that you
will grant database-specific privileges later.
@end table

You can also add the same user access information directly by issuing
@code{INSERT} statements and then telling the server to reload the grant
tables:

@example
shell> mysql --user=root mysql
mysql> INSERT INTO user VALUES('localhost','monty',PASSWORD('something'),
                'Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y')
mysql> INSERT INTO user VALUES('%','monty',PASSWORD('something'),
                'Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y')
mysql> INSERT INTO user SET Host='localhost',User='admin',
                 Reload_priv='Y', Process_priv='Y';
mysql> INSERT INTO user (Host,User,Password)
                        VALUES('localhost','dummy','');
mysql> FLUSH PRIVILEGES;
@end example

Depending on your @strong{MySQL} version, you may have to use a different
number of @code{'Y'} values above (versions prior to 3.22.11 had fewer
privilege columns).  For the @code{admin} user, the more readable extended
@code{INSERT} syntax that is available starting with 3.22.11 is used.

Note that to set up a superuser, you need only create a @code{user} table
entry with the privilege fields set to @code{'Y'}.  No @code{db} or
@code{host} table entries are necessary.

The privilege columns in the @code{user} table were not set explicitly in the
last @code{INSERT} statement (for the @code{dummy} user), so those columns
are assigned the default value of @code{'N'}.  This is the same thing that
@code{GRANT USAGE} does.

The following example adds a user @code{custom} who can connect from hosts
@code{localhost}, @code{server.domain} and @code{whitehouse.gov}.  He wants
to access the @code{bankaccount} database only from @code{localhost},
the @code{expenses} database only from @code{whitehouse.gov} and
the @code{customer} database from all three hosts.  He wants
to use the password @code{stupid} from all three hosts.

To set up this user's privileges using @code{GRANT} statements, run these
commands:

@example
shell> mysql --user=root mysql
mysql> GRANT SELECT,INSERT,UPDATE,DELETE,CREATE,DROP
           ON bankaccount.*
           TO custom@@localhost
           IDENTIFIED BY 'stupid';
mysql> GRANT SELECT,INSERT,UPDATE,DELETE,CREATE,DROP
           ON expenses.*
           TO custom@@whitehouse.gov
           IDENTIFIED BY 'stupid';
mysql> GRANT SELECT,INSERT,UPDATE,DELETE,CREATE,DROP
           ON customer.*
           TO custom@@'%'
           IDENTIFIED BY 'stupid';
@end example

To set up the user's privileges by modifying the grant tables directly,
run these commands (note the @code{FLUSH PRIVILEGES} at the end):

@example
shell> mysql --user=root mysql
mysql> INSERT INTO user (Host,User,Password)
       VALUES('localhost','custom',PASSWORD('stupid'));
mysql> INSERT INTO user (Host,User,Password)
       VALUES('server.domain','custom',PASSWORD('stupid'));
mysql> INSERT INTO user (Host,User,Password)
       VALUES('whitehouse.gov','custom',PASSWORD('stupid'));
mysql> INSERT INTO db
       (Host,Db,User,Select_priv,Insert_priv,Update_priv,Delete_priv,
        Create_priv,Drop_priv)
       VALUES
       ('localhost','bankaccount','custom','Y','Y','Y','Y','Y','Y');
mysql> INSERT INTO db
       (Host,Db,User,Select_priv,Insert_priv,Update_priv,Delete_priv,
        Create_priv,Drop_priv)
       VALUES
       ('whitehouse.gov','expenses','custom','Y','Y','Y','Y','Y','Y');
mysql> INSERT INTO db
       (Host,Db,User,Select_priv,Insert_priv,Update_priv,Delete_priv,
        Create_priv,Drop_priv)
       VALUES('%','customer','custom','Y','Y','Y','Y','Y','Y');
mysql> FLUSH PRIVILEGES;
@end example

The first three @code{INSERT} statements add @code{user} table entries that
allow user @code{custom} to connect from the various hosts with the given
password, but grant no permissions to him (all privileges are set to the
default value of @code{'N'}).  The next three @code{INSERT} statements add
@code{db} table entries that grant privileges to @code{custom} for the
@code{bankaccount}, @code{expenses} and @code{customer} databases, but only
when accessed from the proper hosts.  As usual, when the grant tables are
modified directly, the server must be told to reload them (with
@code{FLUSH PRIVILEGES}) so that the privilege changes take effect.

If you want to give a specific user access from any machine in a given
domain, you can issue a @code{GRANT} statement like the following:

@example
mysql> GRANT ...
           ON *.*
           TO myusername@@"%.mydomainname.com"
           IDENTIFIED BY 'mypassword';
@end example

To do the same thing by modifying the grant tables directly, do this:

@example
mysql> INSERT INTO user VALUES ('%.mydomainname.com', 'myusername',
           PASSWORD('mypassword'),...);
mysql> FLUSH PRIVILEGES;
@end example

You can also use @code{xmysqladmin}, @code{mysql_webadmin} and even
@code{xmysql} to insert, change and update values in the grant tables.
You can find these utilities at the @strong{MySQL}
@uref{http://www.mysql.com/Contrib/,Contrib directory}.

@node Passwords, Access denied, Adding users, Privilege system
@section How to set up passwords
@cindex Passwords, setting
@findex PASSWORD()

The examples in the preceding sections illustrate an important principle:
when you store a non-empty password using @code{INSERT} or @code{UPDATE}
statements, you must use the @code{PASSWORD()} function to encrypt it.  This
is because the @code{user} table stores passwords in encrypted form, not as
plaintext.  If you forget that fact, you are likely to attempt to set
passwords like this:

@example
shell> mysql -u root mysql
mysql> INSERT INTO user (Host,User,Password)
       VALUES('%','jeffrey','biscuit');
mysql> FLUSH PRIVILEGES;
@end example

The result is that the plaintext value @code{'biscuit'} is stored as the
password in the @code{user} table.  When the user @code{jeffrey} attempts to
connect to the server using this password, the @code{mysql} client encrypts
it with @code{PASSWORD()} and sends the result to the server.  The server
compares the value in the @code{user} table (which is the plaintext value
@code{'biscuit'}) to the encrypted password (which is @emph{not}
@code{'biscuit'}).  The comparison fails and the server rejects the
connection:

@example
shell> mysql -u jeffrey -pbiscuit test
Access denied
@end example

Since passwords must be encrypted when they are inserted in the @code{user}
table, the @code{INSERT} statement should have been specified like this
instead:

@example
mysql> INSERT INTO user (Host,User,Password)
       VALUES('%','jeffrey',PASSWORD('biscuit'));
@end example

You must also use the @code{PASSWORD()} function when you use @code{SET
PASSWORD} statements:

@example
mysql> SET PASSWORD FOR jeffrey@@"%" = PASSWORD('biscuit');
@end example

If you set passwords using the @code{GRANT ... IDENTIFIED BY} statement
or the @code{mysqladmin password} command, the @code{PASSWORD()} function
is unnecessary.  They both take care of encrypting the password for you,
so you would specify a password of @code{'biscuit'} like this:

@example
mysql> GRANT USAGE ON *.* TO jeffrey@@"%" IDENTIFIED BY 'biscuit';
@end example

or

@example
shell> mysqladmin -u jeffrey password biscuit
@end example

Note: @code{PASSWORD()} does not perform password encryption in the same way
that Unix passwords are encrypted.  You should not assume that if your Unix
password and your @strong{MySQL} password are the same, @code{PASSWORD()}
will result in the same encrypted value as is stored in the Unix password
file.
@xref{User names}.

@node Access denied, Security, Passwords, Privilege system
@section Causes of @code{Access denied} errors

If you encounter @code{Access denied} errors when you try to connect to the
@strong{MySQL} server, the list below indicates some courses of
action you can take to correct the problem:

@itemize @bullet
@item
Did you run the @code{mysql_install_db} script after installing
@strong{MySQL}, to set up the initial grant table contents?  If not, do
so.  @xref{Default privileges}.  Test the initial privileges by
executing this command:

@example
shell> mysql -u root test
@end example

The server should let you connect without error.  You should also make sure
you have a file @file{user.ISD} in the @strong{MySQL} database directory.
Ordinarily, this is @file{PATH/var/mysql/user.ISD}, where @code{PATH} is the
pathname to the @strong{MySQL} installation root.

@item
After a fresh installation, you should connect to the server and set up
your users and their access permissions:

@example
shell> mysql -u root mysql
@end example

The server should let you connect because the @strong{MySQL} @code{root} user
has no password initially.  Since that is also a security risk, setting the
@code{root} password is something you should do while you're setting up
your other @strong{MySQL} users.

If you try to connect as @code{root} and get this error:

@example
Access denied for user: '@@unknown' to database mysql
@end example

this means that you don't have an entry in the @code{user} table with a
@code{User} column value of @code{'root'} and that @code{mysqld} cannot
resolve the hostname for your client.  In this case, you must restart the
server with the @code{--skip-grant-tables} option and edit your
@file{/etc/hosts} or @file{\windows\hosts} file to add a entry for your
host.

@item
@cindex @code{mysql_fix_privilege_tables}
If you updated an existing @strong{MySQL} installation from a pre-3.22.11
version to 3.22.11 or later, did you run the
@code{mysql_fix_privilege_tables} script?  If not, do so.  The structure of
the grant tables changed with @strong{MySQL} 3.22.11 when the @code{GRANT}
statement became functional.

@item
If you make changes to the grant tables directly (using @code{INSERT} or
@code{UPDATE} statement) and your changes seem to be ignored, remember that
you must issue a @code{FLUSH PRIVILEGES} statement or execute a
@code{mysqladmin flush-privileges} command to cause the server to reread the
tables.  Otherwise your changes have no effect until the next time the server
is restarted.  Remember that after you set the @code{root} password, you
won't need to specify it until after you flush the privileges, because the
server still won't know you've changed the password yet!

@item
If your privileges seem to have changed in the middle of a session, it may be
that a superuser has changed them.  Reloading the grant tables affects new
client connections, but it also affects existing connections as indicated in
@ref{Privilege changes}.

@item
For testing, start the @code{mysqld} daemon with the
@code{--skip-grant-tables} option.  Then you can change the @strong{MySQL}
grant tables and use the @code{mysqlaccess} script to check whether or not
your modifications have the desired effect.  When you are satisfied with your
changes, execute @code{mysqladmin flush-privileges} to tell the @code{mysqld}
server to start using the new grant tables.  @strong{Note:} Reloading the
grant tables overrides the @code{--skip-grant-tables} option.  This allows
you to tell the server to begin using the grant tables again without bringing
it down and restarting it.

@item
If you have access problems with a Perl, Python or ODBC program, try to
connect to the server with @code{mysql -u user_name db_name} or @code{mysql
-u user_name -pyour_pass db_name}.  If you are able to connect using the
@code{mysql} client, there is a problem with your program and not with the
access privileges.  (Notice that there is no space between @code{-p} and the
password; you can also use the @code{--password=your_pass} syntax to specify
the password.)

@item
If you can't get your password to work, remember that you must use
the @code{PASSWORD()} function if you set the password with the
@code{INSERT}, @code{UPDATE} or @code{SET PASSWORD} statements.  The
@code{PASSWORD()} function is unnecessary if you specify the password using
the @code{GRANT ... INDENTIFIED BY} statement or the @code{mysqladmin
password} command.
@xref{Passwords}.

@item
@code{localhost} is a synonym for your local hostname, and is also the
default host to which clients try to connect if you specify no host
explicitly.  However, connections to @code{localhost} do not work if you are
running on a system that uses MIT-pthreads (@code{localhost} connections are
made using Unix sockets, which are not supported by MIT-pthreads).  To avoid
this problem on such systems, you should use the @code{--host} option to name
the server host explicitly.  This will make a TCP/IP connection to the
@code{mysqld} server.  In this case, you must have your real hostname in
@code{user} table entries on the server host.  (This is true even if you are
running a client program on the same host as the server.)

@item
If you get an @code{Access denied} error when trying to connect to the
database with @code{mysql -u user_name db_name}, you may have a problem
with the @code{user} table. Check this by executing @code{mysql -u root
mysql} and issuing this SQL statement:

@example
mysql> SELECT * FROM user;
@end example

The result should include an entry with the @code{Host} and @code{User}
columns matching your computer's hostname and your @strong{MySQL} user name.

@item
The @code{Access denied} error message will tell you who you are trying
to log in as, the host from which you are trying to connect, and whether
or not you were using a password. Normally, you should have one entry in
the @code{user} table that exactly matches the hostname and user name
that were given in the error message.

@item
If you get the following error when you try to connect from a different host
than the one on which the @strong{MySQL} server is running, then there is no
row in the @code{user} table that matches that host:

@example
Host ... is not allowed to connect to this MySQL server
@end example

You can fix this by using the command line tool @code{mysql} (on the server
host!) to add a row to the @code{user} table for the user/hostname combination
from which you are trying to connect.  If you are not running @strong{MySQL}
3.22 and you don't know the IP number or hostname of the machine from which
you are connecting, you should put an entry with @code{'%'} as the
@code{Host} column value in the @code{user} table and restart @code{mysqld}
with the @code{--log} option on the server machine.  After trying to connect
from the client machine, the information in the @strong{MySQL} log will
indicate how you really did connect.  (Then replace the @code{'%'} in the
@code{user} table entry with the actual hostname that shows up in the log.
Otherwise, you'll have a system that is insecure.)

@item
If @code{mysql -u root test} works but @code{mysql -h your_hostname -u root
test} results in @code{Access denied}, then you may not have the correct name
for your host in the @code{user} table.  A common problem here is that the
@code{Host} value in the user table entry specifies an unqualified hostname,
but your system's name resolution routines return a fully-qualified domain
name (or vice-versa).  For example, if you have an entry with host
@code{'tcx'} in the @code{user} table, but your DNS tells @strong{MySQL} that
your hostname is @code{'tcx.subnet.se'}, the entry will not work. Try adding
an entry to the @code{user} table that contains the IP number of your host as
the @code{Host} column value.  (Alternatively, you could add an entry to the
@code{user} table with a @code{Host} value that contains a wildcard---for
example, @code{'tcx.%'}.  However, use of hostnames ending with @samp{%} is
@emph{insecure} and is @emph{not} recommended!)

@item
If @code{mysql -u user_name test} works but @code{mysql -u user_name
other_db_name} doesn't work, you don't have an entry for @code{other_db_name}
listed in the @code{db} table.

@item
If @code{mysql -u user_name db_name} works when executed on the server
machine, but @code{mysql -u host_name -u user_name db_name} doesn't work when
executed on another client machine, you don't have the client machine listed
in the @code{user} table or the @code{db} table.

@item
If you can't figure out why you get @code{Access denied}, remove from the
@code{user} table all entries that have @code{Host} values containing
wildcards (entries that contain @samp{%} or @samp{_}).  A very common error
is to insert a new entry with @code{Host}=@code{'%'} and
@code{User}=@code{'some user'}, thinking that this will allow you to specify
@code{localhost} to connect from the same machine.  The reason that this
doesn't work is that the default privileges include an entry with
@code{Host}=@code{'localhost'} and @code{User}=@code{''}.  Since that entry
has a @code{Host} value @code{'localhost'} that is more specific than
@code{'%'}, it is used in preference to the new entry when connecting from
@code{localhost}!  The correct procedure is to insert a second entry with
@code{Host}=@code{'localhost'} and @code{User}=@code{'some_user'}, or to
remove the entry with with @code{Host}=@code{'localhost'} and
@code{User}=@code{''}.

@item
If you get the following error, you may have a problem with the @code{db} or
@code{host} table:

@example
Access to database denied
@end example

If the entry selected from the @code{db} table has an empty value in the
@code{Host} column, make sure there are one or more corresponding entries in
the @code{host} table specifying which hosts the @code{db} table entry
applies to.

If you get the error when using the SQL commands @code{SELECT ...
INTO OUTFILE} or @code{LOAD DATA INFILE}, your entry in the @code{user} table
probably doesn't have the @strong{file} privilege enabled.

@item
@cindex Configuration files
@cindex Environment variables
@tindex .my.cnf file
Remember that client programs will use connection parameters specified in
configuration files or environment variables.  If a client seems to be
sending the wrong default connection parameters when you don't specify them
on the command line, check your environment and the @file{.my.cnf} file in
your home directory.  You might also check the system-wide @strong{MySQL}
configuration files, though it is far less likely that client connection
parameters will be specified there. @xref{Option files}.  If you get
@code{Access denied} when you run a client without any options, make sure you
haven't specified an old password in any of your option files!
@xref{Option files}.

@item
If everything else fails, start the @code{mysqld} daemon with a debugging
option (for example, @code{--debug=d,general,query}). This will print host and
user information about attempted connections, as well as information about
each command issued. @xref{Debugging server}.

@item
If you have any other problems with the @strong{MySQL} grant tables and
feel you must post the problem to the mailing list, always provide a
dump of the @strong{MySQL} grant tables. You can dump the tables with
the @code{mysqldump mysql} command. As always, post your problem using
the @code{mysqlbug} script.  In some cases you may restart @code{mysqld} with
@code{--skip-grant-tables} to be able to run @code{mysqldump}.
@end itemize

@node Security,  , Access denied, Privilege system
@section How to make @strong{MySQL} secure against crackers

When you connect to a @strong{MySQL} server, you should normally use
a password.  The password is not transmitted in clear text over the connection.

All other information is transferred as text that can be read by anyone that
is able to watch the connection.  If you are concerned about this, you can
use the compressed protocol (in @strong{MySQL} 3.22 and above) to make things
much harder.  To make things even more secure you should install @code{ssh}
(see @uref{http://www.cs.hut.fi/ssh}).  With this, you can get an encrypted
TCP/IP connection between a @strong{MySQL} server and a @strong{MySQL}
client.

To make a @strong{MySQL} system secure, you should strongly consider the
following suggestions:

@itemize @bullet
@item
Use passwords for all @strong{MySQL} users. Remember that anyone can log in
as any other person as simply as @code{mysql -u other_user db_name} if
@code{other_user} has no password.  It is common behavior with client/server
applications that the client may specify any user name.  You can change the
password of all users by editing the @code{mysql_install_db} script before
you run it, or only the password for the @strong{MySQL} @code{root} user like
this:

@example
shell> mysql -u root mysql
mysql> UPDATE user SET Password=PASSWORD('new_password')
           WHERE user='root';
mysql> FLUSH PRIVILEGES;
@end example

@item
Don't run the @strong{MySQL} daemon as the Unix @code{root} user.
@code{mysqld} can be run as any user.  You can also create a new Unix user
@code{mysql} to make everything even more secure.  If you run @code{mysqld}
as another Unix user, you don't need to change the @code{root} user name in
the @code{user} table, because @strong{MySQL} user names have nothing to do
with Unix user names.  You can edit the @code{mysql.server} script to start
@code{mysqld} as another Unix user.  Normally this is done with the @code{su}
command.  For more details, see @ref{Changing MySQL user, , Changing
@strong{MySQL} user}.

@item
If you put a password for the Unix @code{root} user in the @code{mysql.server}
script, make sure this script is readable only by @code{root}.

@item
Check that the Unix user that @code{mysqld} runs as is the only user with
read/write privileges in the database directories.

@item
Don't give the @strong{process} privilege to all users.  The output of
@code{mysqladmin processlist} shows the text of the currently executing
queries, so any user who is allowed to execute that command might be able to
see if another user issues an @code{UPDATE user SET
password=PASSWORD('not_secure')} query.

@code{mysqld} saves an extra connection for users who have the
@strong{process} privilege, so that a @strong{MySQL} @code{root} user can log
in and check things even if all normal connections are in use.

@item
Don't give the @strong{file} privilege to all users.  Any user that has this
privilege can write a file anywhere in the file system with the privileges of
the @code{mysqld} daemon!  To make this a bit safer, all files generated with
@code{SELECT ... INTO OUTFILE} are readable to everyone, and you can't
overwrite existing files.

@tindex /etc/passwd
The @strong{file} privilege may also be used to read any file accessible
to the Unix user that the server runs as.  This could be abused, for example,
by using @code{LOAD DATA} to load @file{/etc/passwd} into a table, which
can then be read with @code{SELECT}.

@item
If you don't trust your DNS, you should use IP numbers instead of hostnames
in the grant tables.  In principle, the @code{--secure} option to
@code{mysqld} should make hostnames safe.  In any case, you should be very
careful about using hostname values that contain wildcards!
@end itemize

The following @code{mysqld} options affect security:

@table @code
@item --secure
IP numbers returned by the @code{gethostbyname()} system call are checked to
make sure they resolve back to the original hostname. This makes it harder
for someone on the outside to get access by simulating another host.  This
option also adds some sanity checks of hostnames.  The option is turned off
by default in @strong{MySQL} 3.21 since it sometimes takes a long time to
perform backward resolutions.  @strong{MySQL} 3.22 caches hostnames and has
this option enabled by default.

@item --skip-grant-tables
This option causes the server not to use the privilege system at all. This
gives everyone @emph{full access} to all databases!  (You can tell a running
server to start using the grant tables again by executing @code{mysqladmin
reload}.)

@item --skip-name-resolve
Hostnames are not resolved.  All @code{Host} column values in the grant
tables must be IP numbers or @code{localhost}.

@item --skip-networking
Don't allow TCP/IP connections over the network.  All connections to
@code{mysqld} must be made via Unix sockets. This option is unsuitable for
systems that use MIT-pthreads, because the MIT-pthreads package doesn't
support Unix sockets.
@end table

@node Reference, Tutorial, Privilege system, Top
@chapter @strong{MySQL} language reference

@menu
* Literals::                    Literals: how to write strings and numbers
* Column types::                Column types
* Functions::                   Functions
* CREATE DATABASE::             @code{CREATE DATABASE} syntax
* DROP DATABASE::               @code{DROP DATABASE} syntax
* CREATE TABLE::                @code{CREATE TABLE} syntax
* ALTER TABLE::                 @code{ALTER TABLE} syntax
* OPTIMIZE TABLE::              @code{OPTIMIZE TABLE} syntax
* DROP TABLE::                  @code{DROP TABLE} syntax
* DELETE::                      @code{DELETE} syntax
* SELECT::                      @code{SELECT} syntax
* JOIN::                        @code{JOIN} syntax
* INSERT::                      @code{INSERT} syntax
* REPLACE::                     @code{REPLACE} syntax
* LOAD DATA::                   @code{LOAD DATA INFILE} syntax
* UPDATE::                      @code{UPDATE} syntax
* USE::                         @code{USE} syntax
* FLUSH::                       @code{Flush} syntax (clearing caches)
* KILL::                        @code{KILL} syntax
* SHOW::                        @code{SHOW} syntax (Get information about tables, columns, ...)
* EXPLAIN::                     @code{EXPLAIN} syntax (Get information about a @code{SELECT})
* DESCRIBE::                    @code{DESCRIBE} syntax (Get information about names of columns)
* LOCK TABLES::                 @code{LOCK TABLES/UNLOCK TABLES} syntax
* SET OPTION::                  @code{SET OPTION} syntax
* GRANT::                       @code{GRANT} and @code{REVOKE} syntax
* CREATE INDEX::                @code{CREATE INDEX} syntax
* DROP INDEX::                  @code{DROP INDEX} syntax
* Comments::                    Comment syntax
* CREATE FUNCTION::             @code{CREATE FUNCTION} syntax
* Reserved words::              Is @strong{MySQL} picky about reserved words?
@end menu


@cindex Strings
@cindex Strings, escaping characters
@node Literals, Column types, Reference, Reference
@section Literals: how to write strings and numbers

@menu
* String syntax::               Strings
* Number syntax::               Numbers
* NULL values::                 @code{NULL} values
* Legal names::                 Database, table, index, column and alias names
@end menu

@node String syntax, Number syntax, Literals, Literals
@subsection Strings

A string is a sequence of characters, surrounded by either single quote
(@samp{'}) or double quote (@samp{"}) characters.  Examples:

@example
'a string'
"another string"
@end example

Within a string, certain sequences have special meaning.  Each of these
sequences begins with a backslash (@samp{\}), known as the @emph{escape
character}.  @strong{MySQL} recognizes the following escape sequences:

@c these aren't really functions, but that's probably the most reasonable index
@table @code
@findex \0 (ASCII 0)
@findex NUL
@item \0
An ASCII 0 (@code{NUL}) character.

@findex \n (newline)
@findex newline (\n)
@item \n
A newline character.

@findex \t (tab)
@findex tab (\t)
@item \t
A tab character.

@findex \r (carriage return)
@findex return (\r)
@findex carriage return (\r)
@item \r
A carriage return character.

@findex \b (backspace)
@findex backspace (\b)
@item \b
A backspace character.

@findex \' (single quote)
@findex single quote (\')
@item \'
A single quote (@samp{'}) character.

@findex \" (double quote)
@findex double quote (\")
@item \"
A double quote (@samp{"}) character.

@findex \\ (escape)
@findex escape (\\)
@item \\
A backslash (@samp{\}) character.

@findex % (wildcard character)
@findex Wildcard character (%)
@item \%
A @samp{%} character. This is used to search for literal instances of
@samp{%} in contexts where @samp{%} would otherwise be interpreted
as a wildcard character.

@findex _ (wildcard character)
@findex Wildcard character (_)
@item \_
A @samp{_} character. This is used to search for literal instances of
@samp{_} in contexts where @samp{_} would otherwise be interpreted
as a wildcard character.
@end table

@noindent
There are several ways to include quotes within a string:

@itemize @bullet
@item
A @samp{'} inside a string quoted with @samp{'} may be written as @samp{''}.

@item
A @samp{"} inside a string quoted with @samp{"} may be written as @samp{""}.

@item
You can precede the quote character with an escape character (@samp{\}).

@item
A @samp{'} inside a string quoted with @samp{"} needs no special treatment
and need not be doubled or escaped.  In the same way, @samp{"} inside a
string quoted with @samp{'} needs no special treatment.
@end itemize

The @code{SELECT} statements shown below demonstrate how quoting and
escaping work:

@example
mysql> SELECT 'hello', '"hello"', '""hello""', 'hel''lo', '\'hello';
+-------+---------+-----------+--------+--------+
| hello | "hello" | ""hello"" | hel'lo | 'hello |
+-------+---------+-----------+--------+--------+

mysql> SELECT "hello", "'hello'", "''hello''", "hel""lo", "\"hello";
+-------+---------+-----------+--------+--------+
| hello | 'hello' | ''hello'' | hel"lo | "hello |
+-------+---------+-----------+--------+--------+

mysql> SELECT "This\nIs\nFour\nlines";
+--------------------+
| This
Is
Four
lines |
+--------------------+
@end example

@cindex Quoting binary data

If you want to insert binary data into a @code{BLOB} column, the following
characters must be represented by escape sequences:
@table @code
@item NUL
ASCII 0. You should represent this by @samp{\0} (a backslash and an ASCII @samp{0} character).
@item \
ASCII 92, backslash.  Represent this by @samp{\\}.
@item '
ASCII 39, single quote.  Represent this by @samp{\'}.
@item "
ASCII 34, double quote.  Represent this by @samp{\"}.
@end table

@cindex Quoting
@cindex @code{BLOB}, inserting binary data
@findex mysql_escape_string()
@findex DBI->quote
If you write C code, you can use the C API function
@code{mysql_escape_string()} to escape characters for the @code{INSERT}
statement.  @xref{C API function overview}.  In Perl, you can use the
@code{quote} method of the @code{DBI} package to convert special
characters to the proper escape sequences.  @xref{Perl DBI Class, , Perl
@code{DBI} Class}.

You should use an escape function on any string that might contain any of the
special characters listed above!

@node Number syntax, NULL values, String syntax, Literals
@subsection Numbers

Integers are represented as a sequence of digits. Floats use @samp{.} as a
decimal separator.  Either type of number may be preceded by @samp{-} to
indicate a negative value.

Examples of valid integers:

@example
1221
0
-32
@end example

Examples of valid floating-point numbers:

@example
294.42
-32032.6809e+10
148.00
@end example

An integer may be used in a floating-point context; it is interpreted
as the equivalent floating-point number.

@tindex NULL value
@node NULL values, Legal names, Number syntax, Literals
@subsection @code{NULL} values

The @code{NULL} value means ``no data'' and is different from values such
as @code{0} for numeric types or the empty string for string types.
@xref{Problems with NULL, , Problems with @code{NULL}}.

@code{NULL} may be represented by @code{\N} when using the text file import
or export formats (@code{LOAD DATA INFILE}, @code{SELECT ... INTO OUTFILE}).
@xref{LOAD DATA, , @code{LOAD DATA}}.

@node Legal names,  , NULL values, Literals
@subsection Database, table, index, column and alias names

@menu
* Name case sensitivity::       Case sensitivity in names
@end menu

Database, table, index, column and alias names all follow the same rules in
@strong{MySQL}:

@itemize @bullet
@item
A name may consist of alphanumeric characters from the current character set
and also @samp{_} and @samp{$}. The default character set is ISO-8859-1
Latin1; this may be changed by recompiling @strong{MySQL}.
@xref{Character sets}.

@item
A database, table, index or column name can be up to 64 characters long. An
alias name can be up to 256 characters long.

@item
A name may start with any character that is legal in a name.  In particular,
a name may start with a number (this differs from many other database
systems!).  However, a name cannot consist @emph{only} of numbers.

@item
It is recommended that you do not use names like @code{1e}, because
an expression like @code{1e+1} is ambiguous. It may be interpreted as the
expression @code{1e + 1} or as the number @code{1e+1}.

@item
You cannot use the @samp{.} character in names because it is used to extend the
format by which you can refer to columns (see immediately below).
@end itemize

In @strong{MySQL} you can refer to a column using any of the following forms:

@multitable @columnfractions .35 .65
@item @strong{Column reference} @tab @strong{Meaning}
@item @code{col_name} @tab Column @code{col_name}
from whichever table used in the query contains a column of that name
@item @code{tbl_name.col_name} @tab Column @code{col_name} from table
@code{tbl_name} of the current database
@item @code{db_name.tbl_name.col_name} @tab Column @code{col_name} from table
@code{tbl_name} of the database @code{db_name}.  This form is available in
@strong{MySQL} 3.22 or later.
@end multitable

You need not specify a @code{tbl_name} or @code{db_name.tbl_name} prefix for
a column reference in a statement unless the reference would be ambiguous.
For example, suppose tables @code{t1} and @code{t2} each contain a column
@code{c}, and you retrieve @code{c} in a @code{SELECT} statement that uses
both @code{t1} and @code{t2}.  In this case, @code{c} is ambiguous because it
is not unique among the tables used in the statement, so you must indicate
which table you mean by writing @code{t1.c} or @code{t2.c}.  Similarly, if
you are retrieving from a table @code{t} in database @code{db1} and from a
table @code{t} in database @code{db2}, you must refer to columns in those
tables as @code{db1.t.col_name} and @code{db2.t.col_name}.

@cindex ODBC compatibility
@cindex Compatibility, with ODBC
The syntax @code{.tbl_name} means the table @code{tbl_name} in the current
database.  This syntax is accepted for ODBC compatibility, because some ODBC
programs prefix table names with a @samp{.} character.

@node Name case sensitivity,  , Legal names, Legal names
@subsubsection Case sensitivity in names
@cindex Database names, case sensitivity
@cindex Table names, case sensitivity
@cindex Column names, case sensitivity
@cindex Alias names, case sensitivity
@cindex Case sensitivity, of database names
@cindex Case sensitivity, of table names
@cindex Case sensitivity, of column names
@cindex Case sensitivity, of alias names

In @strong{MySQL}, databases and tables correspond to directories and files
within those directories.  Consequently, the case sensitivity of the
underlying operating system determines the case sensitivity of database and
table names.  This means database and table names are case sensitive in Unix
and case insensitive in Win32.

@strong{Note:} Although database and table names are case insensitive for
Win32, you should not refer to a given database or table using different
cases within the same query.  The following query would not work because it
refers to a table both as @code{my_table} and as @code{MY_TABLE}:

@example
SELECT * FROM my_table WHERE MY_TABLE.col=1;
@end example

Column names are case insensitive in all cases.

Aliases on tables are case sensitive.  The following query would not work
because it refers to the alias both as @code{a} and as @code{A}:

@example
mysql> SELECT col_name FROM tbl_name AS a
           WHERE a.col_name = 1 OR A.col_name = 2;
@end example

Aliases on columns are case insensitive.

@node Column types, Functions, Literals, Reference
@section Column types

@strong{MySQL} supports a number of column types, which may be grouped into
three categories: numeric types, date and time types, and string (character)
types.  This section first gives an overview of the types available and
summarizes the storage requirements for each column type, then provides a
more detailed description of the properties of the types in each category.
The overview is intentionally brief.  The more detailed descriptions should
be consulted for additional information about particular column types, such
as the allowable formats in which you can specify values.

The column types supported by @strong{MySQL} are listed below.
The following code letters are used in the descriptions:

@table @code
@item M
Indicates the maximum display size.  The maximum legal display size is 255.

@item D
Applies to floating-point types and indicates the number of digits
following the decimal point.
@end table

Square brackets (@samp{[} and @samp{]}) indicate parts of type specifiers
that are optional.

@tindex Types

@c The @w{-number} stuff keeps a linebreak from occurring between
@c the - and number.

@table @code
@tindex TINYINT
@item TINYINT[(M)] [UNSIGNED] [ZEROFILL]

A very small integer. The signed range is @code{-128} to @code{127}. The
unsigned range is @code{0} to @code{255}.

@tindex SMALLINT
@item SMALLINT[(M)] [UNSIGNED] [ZEROFILL]

A small integer. The signed range is @code{-32768} to @code{32767}. The
unsigned range is @code{0} to @code{65535}.

@tindex MEDIUMINT
@item MEDIUMINT[(M)] [UNSIGNED] [ZEROFILL]

A medium-size integer. The signed range is @code{-8388608} to
@code{8388607}. The unsigned range is @code{0} to @code{16777215}.

@tindex INT
@item INT[(M)] [UNSIGNED] [ZEROFILL]

A normal-size integer. The signed range is @code{-2147483648} to
@code{2147483647}.  The unsigned range is @code{0} to @code{4294967295}.

@tindex INTEGER
@item INTEGER[(M)] [UNSIGNED] [ZEROFILL]

This is a synonym for @code{INT}.

@tindex BIGINT
@item BIGINT[(M)] [UNSIGNED] [ZEROFILL]

A large integer. The signed range is @code{-9223372036854775808} to
@code{9223372036854775807}. The unsigned range is @code{0} to
@code{18446744073709551615}.  Note
that all arithmetic is done using signed @code{BIGINT} or @code{DOUBLE}
values, so you shouldn't use unsigned big integers larger than
@code{9223372036854775807} (63 bits) except with bit functions!
Note that @code{-}, @code{+} and @code{*} will use @code{BIGINT} arithmetic when
both arguments are @code{INTEGER} values!  This means that if you multiply two big integers
(or results from functions that return integers) you may get unexpected results
if the result is larger than @code{9223372036854775807}.

@tindex FLOAT(4)
@tindex FLOAT(8)
@item FLOAT(precision) [ZEROFILL]

A floating-point number. Cannot be unsigned.  @code{precision} can be
@code{4} or @code{8}. @code{FLOAT(4)} is a single-precision number and
@code{FLOAT(8)} is a double-precision number.  These types are like the
@code{FLOAT} and @code{DOUBLE} types described immediately below.
@code{FLOAT(4)} and @code{FLOAT(8)} have the same ranges as the corresponding
@code{FLOAT} and @code{DOUBLE} types, but their display size and number of
decimals is undefined.

In @strong{MySQL} 3.23, this is a true floating point value.  In
earlier @strong{MySQL} versions, @code{FLOAT(precision)} always has 2 decimals.

@cindex ODBC compatibility
@cindex Compatibility, with ODBC
This syntax is provided for ODBC compatibility.

@tindex FLOAT
@tindex FLOAT(M,D)
@item FLOAT[(M,D)] [ZEROFILL]

A small (single-precision) floating-point number. Cannot be unsigned.
Allowable values are @code{@w{-3.402823466E+38}} to
@code{@w{-1.175494351E-38}}, @code{0} and @code{@w{1.175494351E-38}} to
@code{3.402823466E+38}.

@tindex DOUBLE
@item DOUBLE[(M,D)] [ZEROFILL]

A normal-size (double-precision) floating-point number. Cannot be
unsigned. Allowable values are @code{@w{-1.7976931348623157E+308}} to
@code{@w{-2.2250738585072014E-308}}, @code{0} and
@code{2.2250738585072014E-308} to @code{1.7976931348623157E+308}.

@tindex DOUBLE PRECISION
@tindex REAL
@item DOUBLE PRECISION[(M,D)] [ZEROFILL]
@itemx REAL[(M,D)] [ZEROFILL]

These are synonyms for @code{DOUBLE}.

@tindex DECIMAL
@item DECIMAL(M,D) [ZEROFILL]

An unpacked floating-point number.  Cannot be unsigned.  Behaves like a
@code{CHAR} column: ``unpacked'' means the number is stored as a string, using
one character for each digit of the value, the decimal point, and, for
negative numbers, the @samp{-} sign.  If @code{D} is 0, values will have
no decimal point or fractional part.  The maximum range of
@code{DECIMAL} values is the same as for @code{DOUBLE}, but the actual range
for a given @code{DECIMAL} column may be constrained by the choice of
@code{M} and @code{D}.

In @strong{MySQL} 3.23 the @code{M} argument no longer includes the sign
or the decimal point. (This is according to ANSI SQL.)

@tindex NUMERIC
@item NUMERIC(M,D) [ZEROFILL]

This is a synonym for @code{DECIMAL}.

@tindex DATE
@item DATE

A date.  The supported range is @code{'1000-01-01'} to @code{'9999-12-31'}.
@strong{MySQL} displays @code{DATE} values in @code{'YYYY-MM-DD'} format, but
allows you to assign values to @code{DATE} columns using either strings or
numbers.

@tindex DATETIME
@item DATETIME

A date and time combination.  The supported range is @code{'1000-01-01
00:00:00'} to @code{'9999-12-31 23:59:59'}.  @strong{MySQL} displays
@code{DATETIME} values in @code{'YYYY-MM-DD HH:MM:SS'} format, but allows you
to assign values to @code{DATETIME} columns using either strings or numbers.

@tindex TIMESTAMP
@item TIMESTAMP[(M)]

A timestamp.  The range is @code{'1970-01-01 00:00:00'} to sometime in the
year @code{2037}.  @strong{MySQL} displays @code{TIMESTAMP} values in
@code{YYYYMMDDHHMMSS}, @code{YYMMDDHHMMSS}, @code{YYYYMMDD} or @code{YYMMDD}
format, depending on whether @code{M} is @code{14} (or missing), @code{12},
@code{8} or @code{6}, but allows you to assign values to @code{TIMESTAMP}
columns using either strings or numbers.  A @code{TIMESTAMP} column is useful
for recording the date and time of an @code{INSERT} or @code{UPDATE}
operation because it is automatically set to the date and time of the most
recent operation if you don't give it a value yourself.  You can also set it
to the current date and time by assigning it a @code{NULL} value.  @xref{Date
and time types}.

@tindex TIME
@item TIME

A time.  The range is @code{'-838:59:59'} to @code{'838:59:59'}.
@strong{MySQL} displays @code{TIME} values in @code{'HH:MM:SS'} format, but
allows you to assign values to @code{TIME} columns using either strings or
numbers.

@tindex YEAR
@item YEAR

A year.  The allowable values are @code{1901} to @code{2155}, and @code{0000}.
@strong{MySQL} displays @code{YEAR} values in @code{YYYY} format, but allows
you to assign values to @code{YEAR} columns using either strings or numbers.
(The @code{YEAR} type is new in @strong{MySQL} 3.22.)

@tindex CHAR
@item CHAR(M) [BINARY]

A fixed-length string that is always right-padded with spaces to the
specified length when stored. The range of @code{M} is 1 to 255 characters.
Trailing spaces are removed when the value is retrieved. @code{CHAR} values
are sorted and compared in case-insensitive fashion unless the @code{BINARY}
keyword is given.

@tindex VARCHAR
@item VARCHAR(M) [BINARY]

A variable-length string.  Note:
Trailing spaces are removed when the value is stored (this differs from the
ANSI SQL specification). The range of @code{M} is 1 to 255 characters.
@code{VARCHAR} values are sorted and compared in case-insensitive fashion
unless the @code{BINARY} keyword is given. @xref{Silent column changes}.

@tindex TINYBLOB
@tindex TINYTEXT
@item TINYBLOB
@itemx TINYTEXT

A @code{BLOB} or @code{TEXT} column with a maximum length of 255 (2^8 - 1)
characters. @xref{Silent column changes}.

@tindex BLOB
@tindex TEXT
@item BLOB
@itemx TEXT

A @code{BLOB} or @code{TEXT} column with a maximum length of 65535 (2^16 - 1)
characters. @xref{Silent column changes}.

@tindex MEDIUMBLOB
@tindex MEDIUMTEXT
@item MEDIUMBLOB
@itemx MEDIUMTEXT

A @code{BLOB} or @code{TEXT} column with a maximum length of 16777215
(2^24 - 1) characters. @xref{Silent column changes}.

@tindex LONGBLOB
@tindex LONGTEXT
@item LONGBLOB
@itemx LONGTEXT

A @code{BLOB} or @code{TEXT} column with a maximum length of 4294967295
(2^32 - 1) characters. @xref{Silent column changes}.

@tindex ENUM
@item ENUM('value1','value2',...)

An enumeration.
A string object that can have only one value, chosen from the list of values
@code{'value1'}, @code{'value2'}, @code{...}, or @code{NULL}.  An @code{ENUM}
can have a maximum of 65535 distinct values.

@tindex SET
@item SET('value1','value2',...)

A set.  A string object that can have zero or more values, each of which must
be chosen from the list of values @code{'value1'}, @code{'value2'},
@code{...} A @code{SET} can have a maximum of 64 members.
@end table

@menu
* Storage requirements::        Column type storage requirements
* Numeric types::               Numeric types
* Date and time types::         Date and time types
* String types::                String types
* Choosing types::              Choosing the right type for a column
* Indexes::                     Column indexes
* Multiple-column indexes::     Multiple-column indexes
* Other-vendor column types::   Using column types from other database engines
@end menu

@cindex Storage requirements
@node Storage requirements, Numeric types, Column types, Column types
@subsection Column type storage requirements

The storage requirements for each of the column types supported by
@strong{MySQL} are listed below by category.

@subheading Numeric types

@multitable @columnfractions .35 .65
@item @strong{Column type} @tab @strong{Storage required}
@item @code{TINYINT}       @tab 1 byte
@item @code{SMALLINT}      @tab 2 bytes
@item @code{MEDIUMINT}     @tab 3 bytes
@item @code{INT}           @tab 4 bytes
@item @code{INTEGER}       @tab 4 bytes
@item @code{BIGINT}        @tab 8 bytes
@item @code{FLOAT(4)}      @tab 4 bytes
@item @code{FLOAT(8)}      @tab 8 bytes
@item @code{FLOAT}         @tab 4 bytes
@item @code{DOUBLE}        @tab 8 bytes
@item @code{DOUBLE PRECISION} @tab 8 bytes
@item @code{REAL}         @tab 8 bytes
@item @code{DECIMAL(M,D)} @tab @code{M} bytes (@code{D}+2, if @code{M < D})
@item @code{NUMERIC(M,D)} @tab @code{M} bytes (@code{D}+2, if @code{M < D})
@end multitable

@subheading Date and time types

@multitable @columnfractions .35 .65
@item @strong{Column type} @tab @strong{Storage required}
@item @code{DATETIME}      @tab 8 bytes
@item @code{DATE}          @tab 3 bytes
@item @code{TIMESTAMP}     @tab 4 bytes
@item @code{TIME}          @tab 3 bytes
@item @code{YEAR}          @tab 1 byte
@end multitable

@subheading String types

@multitable @columnfractions .35 .65
@item @strong{Column type} @tab @strong{Storage required}
@item @code{CHAR(M)} @tab @code{M} bytes, @code{1 <= M <= 255}
@item @code{VARCHAR(M)} @tab @code{L}+1 bytes, where @code{L <= M} and
@code{1 <= M <= 255}
@item @code{TINYBLOB}, @code{TINYTEXT} @tab @code{L}+1 bytes,
where @code{L} < 2^8
@item @code{BLOB}, @code{TEXT} @tab @code{L}+2 bytes,
where @code{L} < 2^16
@item @code{MEDIUMBLOB}, @code{MEDIUMTEXT} @tab @code{L}+3 bytes,
where @code{L} < 2^24
@item @code{LONGBLOB}, @code{LONGTEXT} @tab @code{L}+4 bytes,
where @code{L} < 2^32
@item @code{ENUM('value1','value2',...)} @tab 1 or 2 bytes, depending on
the number of enumeration values (65535 values maximum)
@item @code{SET('value1','value2',...)} @tab 1, 2, 3, 4 or 8 bytes, depending
on the number of set members (64 members maximum)
@end multitable

@code{VARCHAR} and the @code{BLOB} and @code{TEXT} types are variable-length
types, for which the storage requirements depend on the actual length of
column values (represented by @code{L} in the preceding table), rather than
on the type's maximum possible size.  For example, a @code{VARCHAR(10)}
column can hold a string with a maximum length of 10 characters.  The actual
storage required is the length of the string (@code{L}), plus 1 byte to
record the length of the string.  For the string @code{'abcd'}, @code{L} is 4
and the storage requirement is 5 bytes.

The @code{BLOB} and @code{TEXT} types require 1, 2, 3 or 4 bytes to record
the length of the column value, depending on the maximum possible length of
the type.

If a table includes any variable-length column types, the record format will
also be variable-length.  Note that when a table is created, @strong{MySQL}
may under certain conditions change a column from a variable-length type to a
fixed-length type, or vice-versa.  @xref{Silent column changes}.

The size of an @code{ENUM} object is determined by the number of different
enumeration values.  1 byte is used for enumerations with up to 255 possible
values.  2 bytes are used for enumerations with up to 65535 values.

The size of a @code{SET} object is determined by the number of different
set members.  If the set size is @code{N}, the object occupies @code{(N+7)/8}
bytes, rounded up to 1, 2, 3, 4 or 8 bytes.  A @code{SET} can have a maximum
of 64 members.

@node Numeric types, Date and time types, Storage requirements, Column types
@subsection Numeric types

All integer types can have an optional attribute @code{UNSIGNED}.  Unsigned
values can be used when you want to allow only positive numbers in a column
and you need a little bigger numeric range for the column.

All numeric types can have an optional attribute @code{ZEROFILL}.  Values for
@code{ZEROFILL} columns are left-padded with zeroes up to the maximum display
length when they are displayed.  For example, for a column declared as
@code{INT(5) ZEROFILL}, a value of @code{4} is retrieved as @code{00004}.

When asked to store a value in a numeric column that is outside the column
type's allowable range, @strong{MySQL} clips the value to the appropriate
endpoint of the range and stores the resulting value instead.

For example, the range of an @code{INT} column is @code{-2147483648} to
@code{2147483647}.  If you try to insert @code{-9999999999} into an
@code{INT} column, the value is clipped to the lower endpoint of the range,
and @code{-2147483648} is stored instead. Similarly, if you try to insert
@code{9999999999}, @code{2147483647} is stored instead.

If the @code{INT} column is @code{UNSIGNED}, the size of the column's
range is the same but its endpoints shift up to @code{0} and @code{4294967295}.
If you try to store @code{-9999999999} and @code{9999999999},
the values stored in the column become @code{0} and @code{4294967296}.

Conversions that occur due to clipping are reported as ``warnings'' for
@code{ALTER TABLE}, @code{LOAD DATA INFILE}, @code{UPDATE} and
multi-row @code{INSERT} statements.

The maximum display size (@code{M}) and number of decimals (@code{D})
are used for formatting and calculation of maximum column width.

@c HOW? (PD)

@strong{MySQL} will store any value that fits a column's storage type even if
the value exceeds the display size.  For example, an @code{INT(4)} column has
a display size of 4.  Suppose you insert a value which has more than 4 digits
into the column, such as @code{12345}.  The display size is exceeded, but the
allowable range of the @code{INT} type is not, so @strong{MySQL} stores the
actual value, @code{12345}.  When retrieving the value from the column,
@strong{MySQL} returns the actual value stored in the column.

The @code{DECIMAL} type is considered a numeric type (as is its synonym,
@code{NUMERIC}), but such values are stored as strings.  One character is
used for each digit of the value, the decimal point (if @code{D} > 0) and the
@samp{-} sign (for negative numbers).  If @code{D} is 0, @code{DECIMAL} and
@code{NUMERIC} values contain no decimal point or fractional part.

The maximum range of @code{DECIMAL} values is the same as for
@code{DOUBLE}, but the actual range for a given @code{DECIMAL} column
may be constrained by the choice of @code{M} and @code{D}.  For
example, a type specification such as @code{DECIMAL(4,2)} indicates a
maximum length of four characters with two digits after the decimal
point.  Due to the way the @code{DECIMAL} type is stored, this
specification results in an allowable range of @code{-.99} to
@code{9.99}, much less than the range of a @code{DOUBLE}.

To avoid some rounding problems, @strong{MySQL} always rounds everything that
it stores in any floating-point column to the number of decimals indicated by
the column specification.  Suppose you have a column type of
@code{FLOAT(8,2)}. The number of decimals is 2, so a value such as
@code{2.333} is rounded to two decimals and stored as @code{2.33}.

@cindex Types, Date and Time
@cindex Date and Time types
@node Date and time types, String types, Numeric types, Column types
@subsection Date and time types

@menu
* Y2K issues::                  Y2K issues and date types
* DATETIME::                    The @code{DATETIME}, @code{DATE} and @code{TIMESTAMP} types
* TIME::                        The @code{TIME} type
* YEAR::                        The @code{YEAR} type
@end menu

The date and time types are @code{DATETIME}, @code{DATE}, @code{TIMESTAMP},
@code{TIME} and @code{YEAR}.  Each of these has a range of legal values, as
well as a ``zero'' value that is used when you specify an illegal value.

Here are some general considerations to keep in mind when working
with date and time types:

@itemize @bullet
@item
@strong{MySQL} retrieves values for a given date or time type in a standard
format, but it attempts to interpret a variety of formats for values that
you supply (e.g., when you specify a value to be assigned to or compared to a
date or time type).  Nevertheless, only the formats described in the
following sections are supported.  It is expected that you will supply legal
values, and unpredictable results may occur if you use values in other
formats.

@item
Although @strong{MySQL} tries to interpret values in several formats, it
always expects the year part of date values to be leftmost.  Dates must be
given in year-month-day order (e.g., @code{'98-09-04'}), rather than in the
month-day-year or day-month-year orders commonly used elsewhere (e.g.,
@code{'09-04-98'}, @code{'04-09-98'}).

@item
@strong{MySQL} automatically converts a date or time type value to a number
if the value is used in a numeric context, and vice versa.

@item
When @strong{MySQL} encounters a value for a date or time type that is out of
range or otherwise illegal for the type, it converts the value to the ``zero''
value for that type.  (The exception is that out-of-range @code{TIME} values
are clipped to the appropriate endpoint of the @code{TIME} range.)  The table
below shows the format of the ``zero'' value for each type:

@multitable @columnfractions .3 .7
@item @strong{Column type} @tab @strong{``Zero'' value}
@item @code{DATETIME}      @tab @code{'0000-00-00 00:00:00'}
@item @code{DATE}          @tab @code{'0000-00-00'}
@item @code{TIMESTAMP}     @tab @code{00000000000000} (length depends on display size)
@item @code{TIME}          @tab @code{'00:00:00'}
@item @code{YEAR}          @tab @code{0000}
@end multitable

@item
The ``zero'' values are special, but you can store or refer to them
explicitly using the values shown in the table.  You can also do this
using the values @code{'0'} or @code{0}, which are easier to write.

@item
``Zero'' date or time values used through @strong{MyODBC} are converted
automatically to @code{NULL} in @strong{MyODBC} 2.50.12 and above, because
ODBC can't handle such values.
@end itemize

@cindex Year 2000 issues
@node Y2K issues, DATETIME, Date and time types, Date and time types
@subsubsection Y2K issues and date types

@strong{MySQL} itself is Y2K-safe (@pxref{Year 2000 compliance}),
but input values presented to @strong{MySQL} may not be.  Any input
containing 2-digit year values is ambiguous, since the century is unknown.
Such values must be interpreted into 4-digit form since @strong{MySQL} stores
years internally using four digits.

For @code{DATETIME}, @code{DATE}, @code{TIMESTAMP} and @code{YEAR} types,
@strong{MySQL} interprets dates with ambiguous year values using the
following rules:

@itemize @bullet
@item
Year values in the range @code{00-69} are converted to @code{2000-2069}.

@item
Year values in the range @code{70-99} are converted to @code{1970-1999}.
@end itemize

Remember that these rules provide only reasonable guesses as to what your
data mean.  If the heuristics used by @strong{MySQL} don't produce the
correct values, you should provide unambiguous input containing 4-digit
year values.

@tindex DATETIME
@tindex DATE
@tindex TIMESTAMP
@node DATETIME, TIME, Y2K issues, Date and time types
@subsubsection The @code{DATETIME}, @code{DATE} and @code{TIMESTAMP} types

The @code{DATETIME}, @code{DATE} and @code{TIMESTAMP} types are related.
This section describes their characteristics, how they are similar and how
they differ.

The @code{DATETIME} type is used when you need values that contain both date
and time information.  @strong{MySQL} retrieves and displays @code{DATETIME}
values in @code{'YYYY-MM-DD HH:MM:SS'} format.  The supported range is
@code{'1000-01-01 00:00:00'} to @code{'9999-12-31 23:59:59'}.  (``Supported''
means that although earlier values might work, there is no guarantee that
they will.)

The @code{DATE} type is used when you need only a date value, without a time
part.  @strong{MySQL} retrieves and displays @code{DATE} values in
@code{'YYYY-MM-DD'} format.  The supported range is @code{'1000-01-01'} to
@code{'9999-12-31'}.

The @code{TIMESTAMP} column type provides a type that you can use to
automatically mark @code{INSERT} or @code{UPDATE} operations with the current
date and time.  If you have multiple @code{TIMESTAMP} columns, only the first
one is updated automatically.

Automatic updating of the first @code{TIMESTAMP} column occurs under any of
the following conditions:

@itemize @bullet
@item
The column is not specified explicitly in an @code{INSERT} or
@code{LOAD DATA INFILE} statement.
@item
The column is not specified explicitly in an @code{UPDATE} statement and some
other column changes value.  (Note that an @code{UPDATE} that sets a column
to the value it already has will not cause the @code{TIMESTAMP} column to be
updated, because if you set a column to its current value, @strong{MySQL}
ignores the update for efficiency.)
@item
You explicitly set the @code{TIMESTAMP} column to @code{NULL}.
@end itemize

@code{TIMESTAMP} columns other than the first may also be set to the current
date and time.  Just set the column to @code{NULL}, or to @code{NOW()}.

You can set any @code{TIMESTAMP} column to a value different than the current
date and time by setting it explicitly to the desired value.  This is true
even for the first @code{TIMESTAMP} column.  You can use this property if,
for example, you want a @code{TIMESTAMP} to be set to the current date and
time when you create a row, but not to be changed whenever the row is updated
later:

@itemize @bullet
@item
Let @strong{MySQL} set the column when the row is created.
This will initialize it to the current date and time.

@item
When you perform subsequent updates to other columns in the row, set
the @code{TIMESTAMP} column explicitly to its current value.
@end itemize

On the other hand, you may find it just as easy to use a @code{DATETIME}
column that you initialize to @code{NOW()} when the row is created and
leave alone for subsequent updates.

@code{TIMESTAMP} values may range from the beginning of 1970 to sometime in
the year 2037, with a resolution of one second.  Values are displayed as
numbers.

The format in which @strong{MySQL} retrieves and displays @code{TIMESTAMP}
values depends on the display size, as illustrated by the table below.  The
`full' @code{TIMESTAMP} format is 14 digits, but @code{TIMESTAMP} columns may
be created with shorter display sizes:

@multitable @columnfractions .3 .7
@item @strong{Column type}  @tab @strong{Display format}
@item @code{TIMESTAMP(14)}  @tab @code{YYYYMMDDHHMMSS}
@item @code{TIMESTAMP(12)}  @tab @code{YYMMDDHHMMSS}
@item @code{TIMESTAMP(10)}  @tab @code{YYMMDDHHMM}
@item @code{TIMESTAMP(8)}   @tab @code{YYYYMMDD}
@item @code{TIMESTAMP(6)}   @tab @code{YYMMDD}
@item @code{TIMESTAMP(4)}   @tab @code{YYMM}
@item @code{TIMESTAMP(2)}   @tab @code{YY}
@end multitable

All @code{TIMESTAMP} columns have the same storage size, regardless of
display size.  The most common display sizes are 6, 8, 12, and 14.  You can
specify an arbitrary display size at table creation time, but values of 0 or
greater than 14 are coerced to 14.  Odd-valued sizes in the range from 1 to
13 are coerced to the next higher even number.

You can specify @code{DATETIME}, @code{DATE} and @code{TIMESTAMP} values using
any of a common set of formats:

@itemize @bullet
@item
As a string in either @code{'YYYY-MM-DD HH:MM:SS'} or @code{'YY-MM-DD
HH:MM:SS'} format.  A ``relaxed'' syntax is allowed---any non-numeric
character may be used as the delimiter between date parts or time parts.
For example, @code{'98-12-31 11:30:45'}, @code{'98.12.31 11+30+45'},
@code{'98/12/31 11*30*45'} and @code{'98@@12@@31 11^30^45'} are
equivalent.

@item
As a string in either @code{'YYYY-MM-DD'} or @code{'YY-MM-DD'} format.
A ``relaxed'' syntax is allowed here, too.  For example, @code{'98-12-31'},
@code{'98.12.31'}, @code{'98/12/31'} and @code{'98@@12@@31'} are
equivalent.

@item
As a string with no delimiters in either @code{'YYYYMMDDHHMMSS'} or
@code{'YYMMDDHHMMSS'} format, provided that the string makes sense as a
date.  For example, @code{'19970523091528'} and @code{'970523091528'} are
interpreted as @code{'1997-05-23 09:15:28'}, but @code{'971122459015'} is
illegal (it has a nonsensical minute part) and becomes @code{'0000-00-00
00:00:00'}.

@item
As a string with no delimiters in either @code{'YYYYMMDD'} or @code{'YYMMDD'}
format, provided that the string makes sense as a date.  For example,
@code{'19970523'} and @code{'970523'} are interpreted as
@code{'1997-05-23'}, but @code{'971332'} is illegal (it has nonsensical month
and day parts) and becomes @code{'0000-00-00'}.

@item
As a number in either @code{YYYYMMDDHHMMSS} or @code{YYMMDDHHMMSS}
format, provided that the number makes sense as a date.  For example,
@code{19830905132800} and @code{830905132800} are interpreted as
@code{'1983-09-05 13:28:00'}.

@item
As a number in either @code{YYYYMMDD} or @code{YYMMDD}
format, provided that the number makes sense as a date.  For example,
@code{19830905} and @code{830905} are interpreted as @code{'1983-09-05'}.

@item
As the result of a function that returns a value that is acceptable
in a @code{DATETIME}, @code{DATE} or @code{TIMESTAMP} context, such as
@code{NOW()} or @code{CURRENT_DATE}.
@end itemize

Illegal @code{DATETIME}, @code{DATE} or @code{TIMESTAMP} values are converted
to the ``zero'' value of the appropriate type (@code{'0000-00-00 00:00:00'},
@code{'0000-00-00'} or @code{00000000000000}).

For values specified as strings that include date part delimiters, it is not
necessary to specify two digits for month or day values that are less than
@code{10}.  @code{'1979-6-9'} is the same as @code{'1979-06-09'}.  Similarly,
for values specified as strings that include time part delimiters, it is not
necessary to specify two digits for hour, month or second values that are
less than @code{10}.  @code{'1979-10-30 1:2:3'} is the same as
@code{'1979-10-30 01:02:03'}.

Values specified as numbers should be 6, 8, 12 or 14 digits long.  If the
number is 8 or 14 digits long, it is assumed to be in @code{YYYYMMDD} or
@code{YYYYMMDDHHMMSS} format and that the year is given by the first 4
digits.  If the number is 6 or 12 digits long, it is assumed to be in
@code{YYMMDD} or @code{YYMMDDHHMMSS} format and that the year is given by the
first 2 digits.  Numbers that are not one of these lengths are interpreted
as though padded with leading zeros to the closest length.

Values specified as non-delimited strings are interpreted using their length
as given.  If the string is 8 or 14 characters long, the year is assumed to
be given by the first 4 characters.  Otherwise the year is assumed to be
given by the first 2 characters.  The string is interpreted from left to
right to find year, month, day, hour, minute and second values, for as many
parts as are present in the string.  This means you should not use strings
that have fewer than 6 characters.  For example, if you specify @code{'9903'},
thinking that will represent March, 1999, you will find that @strong{MySQL}
inserts a ``zero'' date into your table.  This is because the year and month
values are @code{99} and @code{03}, but the day part is missing (zero), so
the value is not a legal date.

@code{TIMESTAMP} columns store legal values using the full precision with
which the value was specified, regardless of the display size.  This has
several implications:

@itemize @bullet
@item
Always specify year, month, and day, even if your column types are
@code{TIMESTAMP(4)} or @code{TIMESTAMP(2)}.  Otherwise, the value will not
be a legal date and @code{0} will be stored.

@item
If you use @code{ALTER TABLE} to widen a narrow @code{TIMESTAMP} column,
information will be displayed that previously was ``hidden''.

@item
Similarly, narrowing a @code{TIMESTAMP} column does not cause information to
be lost, except in the sense that less information is shown when the values
are displayed.

@item
Although @code{TIMESTAMP} values are stored to full precision, the only
function that operates directly on the underlying stored value is
@code{UNIX_TIMESTAMP()}.  Other functions operate on the formatted retrieved
value.  This means you cannot use functions such as @code{HOUR()} or
@code{SECOND()} unless the relevant part of the @code{TIMESTAMP} value is
included in the formatted value.  For example, the @code{HH} part of a
@code{TIMESTAMP} column is not displayed unless the display size is at least
10, so trying to use @code{HOUR()} on shorter @code{TIMESTAMP} values
produces a meaningless result.
@end itemize

You can to some extent assign values of one date type to an object
of a different date type.  However, there may be some alteration
of the value or loss of information:

@itemize @bullet
@item
If you assign a @code{DATE} value to a @code{DATETIME} or @code{TIMESTAMP}
object, the time part of the resulting value is set to @code{'00:00:00'},
because the @code{DATE} value contains no time information.

@item
If you assign a @code{DATETIME} or @code{TIMESTAMP} value to a @code{DATE}
object, the time part of the resulting value is deleted, because the
@code{DATE} type stores no time information.

@item
Remember that although @code{DATETIME}, @code{DATE} and @code{TIMESTAMP}
values all can be specified using the same set of formats, the types do not
all have the same range of values.  For example, @code{TIMESTAMP} values
cannot be earlier than @code{1970} or later than @code{2037}.  This means
that a date such as @code{'1968-01-01'}, while legal as a @code{DATETIME} or
@code{DATE} value, is not a valid @code{TIMESTAMP} value and will be
converted to @code{0} if assigned to such an object.
@end itemize

Be aware of certain pitfalls when specifying date values:

@itemize @bullet
@item
The relaxed format allowed for values specified as strings can be deceiving.
For example, a value such as @code{'10:11:12'} might look like a time value
because of the @samp{:} delimiter, but if used in a date context will be
interpreted as the year @code{'2010-11-12'}.  The value @code{'10:45:15'}
will be converted to @code{'0000-00-00'} because @code{'45'} is not a legal
month.

@item
Year values specified as two digits are ambiguous, since the century is
unknown.  @strong{MySQL} interprets 2-digit year values using the following
rules:

@itemize @minus
@item
Year values in the range @code{00-69} are converted to @code{2000-2069}.

@item
Year values in the range @code{70-99} are converted to @code{1970-1999}.
@end itemize
@end itemize

@tindex TIME
@node TIME, YEAR, DATETIME, Date and time types
@subsubsection The @code{TIME} type

@strong{MySQL} retrieves and displays @code{TIME} values in @code{'HH:MM:SS'}
format (or @code{'HHH:MM:SS'} format for large hours values).  @code{TIME}
values may range from @code{'-838:59:59'} to @code{'838:59:59'}.  The reason
the hours part may be so large is that the @code{TIME} type may be used not
only to represent a time of day (which must be less than 24 hours), but also
elapsed time or a time interval between two events (which may be much greater
than 24 hours, or even negative).

You can specify @code{TIME} values in a variety of formats:

@itemize @bullet
@item
As a string in @code{'HH:MM:SS'} format.
A ``relaxed'' syntax is allowed---any non-numeric character may be
used as the delimiter between time parts.  For example, @code{'10:11:12'}
and @code{'10.11.12'} are equivalent.

@item
As a string with no delimiters in @code{'HHMMSS'} format, provided that
it makes sense as a time.  For example, @code{'101112'} is understood as
@code{'10:11:12'}, but @code{'109712'} is illegal (it has a nonsensical
minute part) and becomes @code{'00:00:00'}.

@item
As a number in @code{HHMMSS} format, provided that it makes sense as a time.
For example, @code{101112} is understood as @code{'10:11:12'}.

@item
As the result of a function that returns a value that is acceptable
in a @code{TIME} context, such as @code{CURRENT_TIME}.
@end itemize

For @code{TIME} values specified as strings that include a time part
delimiter, it is not necessary to specify two digits for hours, minutes or
seconds values that are less than @code{10}.  @code{'8:3:2'} is the same as
@code{'08:03:02'}.

Be careful about assigning ``short'' @code{TIME} values to a @code{TIME}
column.  @strong{MySQL} interprets values using the assumption that the
rightmost digits represent seconds.  (@strong{MySQL} interprets @code{TIME}
values as elapsed time, rather than as time of day.)  For example, you might
think of @code{'11:12'}, @code{'1112'} and @code{1112} as meaning
@code{'11:12:00'} (12 minutes after 11 o'clock), but @strong{MySQL}
interprets them as @code{'00:11:12'} (11 minutes, 12 seconds).  Similarly,
@code{'12'} and @code{12} are interpreted as @code{'00:00:12'}.

Values that lie outside the @code{TIME} range
but are otherwise legal are clipped to the appropriate
endpoint of the range.  For example, @code{'-850:00:00'} and
@code{'850:00:00'} are converted to @code{'-838:59:59'} and
@code{'838:59:59'}.

Illegal @code{TIME} values are converted to @code{'00:00:00'}.  Note that
since @code{'00:00:00'} is itself a legal @code{TIME} value, there is no way
to tell, from a value of @code{'00:00:00'} stored in a table, whether the
original value was specified as @code{'00:00:00'} or whether it was illegal.

@tindex YEAR
@node YEAR,  , TIME, Date and time types
@subsubsection The @code{YEAR} type

The @code{YEAR} type is a 1-byte type used for representing years.

@strong{MySQL} retrieves and displays @code{YEAR} values in @code{YYYY}
format.  The range is @code{1901} to @code{2155}.

You can specify @code{YEAR} values in a variety of formats:

@itemize @bullet
@item
As a four-digit string in the range @code{'1901'} to @code{'2155'}.

@item
As a four-digit number in the range @code{1901} to @code{2155}.

@item
As a two-digit string in the range @code{'00'} to @code{'99'}.  Values in the
ranges @code{'00'} to @code{'69'} and @code{'70'} to @code{'99'} are
converted to @code{YEAR} values in the ranges @code{2000} to @code{2069} and
@code{1970} to @code{1999}.

@item
As a two-digit number in the range @code{1} to @code{99}.  Values in the
ranges @code{1} to @code{69} and @code{70} to @code{99} are converted to
@code{YEAR} values in the ranges @code{2001} to @code{2069} and @code{1970}
to @code{1999}.  Note that the range for two-digit numbers is slightly
different than the range for two-digit strings, since you cannot specify zero
directly as a number and have it be interpreted as @code{2000}.  You
@emph{must} specify it as a string @code{'0'} or @code{'00'} or it will be
interpreted as @code{0000}.

@item
As the result of a function that returns a value that is acceptable
in a @code{YEAR} context, such as @code{NOW()}.
@end itemize

Illegal @code{YEAR} values are converted to @code{0000}.

@node String types, Choosing types, Date and time types, Column types
@subsection String types

The string types are @code{CHAR}, @code{VARCHAR}, @code{BLOB}, @code{TEXT},
@code{ENUM} and @code{SET}.

@tindex CHAR
@tindex VARCHAR
@menu
* CHAR::                        
* BLOB::                        
* ENUM::                        
* SET::                         
@end menu

@node CHAR, BLOB, String types, String types
@subsubsection The @code{CHAR} and @code{VARCHAR} types

The @code{CHAR} and @code{VARCHAR} types are similar, but differ in the
way they are stored and retrieved.

The length of a @code{CHAR} column is fixed to the length that you declare
when you create the table.  The length can be any value between 1 and 255.
When @code{CHAR} values are stored, they are right-padded with spaces to the
specified length.  When @code{CHAR} values are retrieved, trailing spaces are
removed.

Values in @code{VARCHAR} columns are variable-length strings.  You can
declare a @code{VARCHAR} column to be any length between 1 and 255, just as
for @code{CHAR} columns.  However, in contrast to @code{CHAR}, @code{VARCHAR}
values are stored using only as many characters as are needed, plus one byte
to record the length.  Values are not padded; instead, trailing spaces are
removed when values are stored.  (This space removal differs from the ANSI
SQL specification.)

If you assign a value to a @code{CHAR} or @code{VARCHAR} column that
exceeds the column's maximum length, the value is truncated to fit.

The table below illustrates the differences between the two types of columns
by showing the result of storing various string values into @code{CHAR(4)}
and @code{VARCHAR(4)} columns:

@c Need to use @(space) to make sure second column values retain spacing
@c in output for table below.

@multitable @columnfractions .2 .15 .2 .2 .25
@item @strong{Value}  @tab @code{CHAR(4)}     @tab @strong{Storage required} @tab @code{VARCHAR(4)} @tab @strong{Storage required}
@item @code{''}       @tab @code{'@ @ @ @ '} @tab 4 bytes @tab @code{''} @tab 1 byte
@item @code{'ab'}     @tab @code{'ab@ @ '}   @tab 4 bytes @tab @code{'ab'} @tab 3 bytes
@item @code{'abcd'}   @tab @code{'abcd'}     @tab 4 bytes @tab @code{'abcd'} @tab 5 bytes
@item @code{'abcdefgh'} @tab @code{'abcd'}     @tab 4 bytes @tab @code{'abcd'} @tab 5 bytes
@end multitable

The values retrieved from the @code{CHAR(4)} and @code{VARCHAR(4)} columns
will be the same in each case, because trailing spaces are removed from
@code{CHAR} columns upon retrieval.

Values in @code{CHAR} and @code{VARCHAR} columns are sorted and compared in
case-insensitive fashion, unless the @code{BINARY} attribute was specified
when the table was created.  The @code{BINARY} attribute means that column
values are sorted and compared in case-sensitive fashion according to the
ASCII order of the machine where the @strong{MySQL} server is running.

The @code{BINARY} attribute is ``sticky''.  This means that if a column marked
@code{BINARY} is used in an expression, the whole expression is compared as a
@code{BINARY} value.

@strong{MySQL} may silently change the type of a @code{CHAR} or @code{VARCHAR}
column at table creation time.
@xref{Silent column changes}.

@tindex BLOB
@tindex TEXT
@node BLOB, ENUM, CHAR, String types
@subsubsection The @code{BLOB} and @code{TEXT} types

A @code{BLOB} is a binary large object that can hold a variable amount of
data.  The four @code{BLOB} types @code{TINYBLOB}, @code{BLOB},
@code{MEDIUMBLOB} and @code{LONGBLOB} differ only in the maximum length of
the values they can hold.
@xref{Storage requirements}.

The four @code{TEXT} types @code{TINYTEXT}, @code{TEXT}, @code{MEDIUMTEXT}
and @code{LONGTEXT} correspond to the four @code{BLOB} types and have the
same maximum lengths and storage requirements.  The only difference between
@code{BLOB} and @code{TEXT} types is that sorting and comparison is performed
in case-sensitive fashion for @code{BLOB} values and case-insensitive fashion
for @code{TEXT} values.  In other words, a @code{TEXT} is a case-insensitive
@code{BLOB}.

If you assign a value to a @code{BLOB} or @code{TEXT} column that exceeds
the column type's maximum length, the value is truncated to fit.

In most respects, you can regard a @code{TEXT} column as a @code{VARCHAR}
column that can be as big as you like.  Similarly, you can regard a
@code{BLOB} column as a @code{VARCHAR BINARY} column.  The differences are:

@itemize @bullet
@item
@code{BLOB} and @code{TEXT} columns cannot be indexed, unlike all other
@strong{MySQL} column types.

@item
There is no trailing-space removal for @code{BLOB} and @code{TEXT} columns
when values are stored, as there is for @code{VARCHAR} columns.

@item
@cindex Default values, @code{BLOB} and @code{TEXT} columns
@cindex @code{BLOB} columns, default values
@cindex @code{TEXT} columns, default values
@code{BLOB} and @code{TEXT} columns cannot have @code{DEFAULT} values.

@item
@cindex @code{NULL} values, and @code{BLOB} and @code{TEXT} columns
@cindex @code{BLOB} columns, and @code{NULL} values
@cindex @code{TEXT} columns, and @code{NULL} values
@code{BLOB} and @code{TEXT} columns are always @code{NULL} columns, even if
you specify @code{NOT NULL} in the column specification.
@end itemize

@strong{MyODBC} defines @code{BLOB} values as @code{LONGVARBINARY} and
@code{TEXT} values as @code{LONGVARCHAR}.

Because @code{BLOB} and @code{TEXT} values may be extremely long, you
may run up against some constraints when using them:

@itemize @bullet
@item
If you want to use @code{GROUP BY} or @code{ORDER BY} on a @code{BLOB} or
@code{TEXT} column, you must convert the column value into a fixed-length
object. The standard way to do this is with the @code{SUBSTRING}
function.  For example:

@example
mysql> select comment from tbl_name ORDER BY substring(comment,20);
@end example

If you don't do this, only the first @code{max_sort_length} bytes of the
column are used when sorting.  The default value of @code{max_sort_length} is
1024; this value can be changed using the @code{-O} option when starting the
@code{mysqld} server. You can group on an expression involving @code{BLOB} or
@code{TEXT} values by specifying the column position or by using an alias:

@example
mysql> select id,substring(blob_col,1,100) from tbl_name
           GROUP BY 2;
mysql> select id,substring(blob_col,1,100) as b from tbl_name
           GROUP BY b;
@end example

@item
The maximum size of a @code{BLOB} or @code{TEXT} object is determined by its
type, but the largest value you can actually transmit between the client and
server is determined by the amount of available memory and the size of the
communications buffers.  You can change the message buffer size, but you must
do so on both the server and client ends. @xref{Server parameters}.
@end itemize

Note that each @code{BLOB} or @code{TEXT} value is represented internally by
a separately-allocated object. This is in contrast to all other column types,
for which storage is allocated once per column when the table is opened.

@tindex ENUM
@node ENUM, SET, BLOB, String types
@subsubsection The @code{ENUM} type

An @code{ENUM} is a string object whose value normally is chosen from a list
of allowed values that are enumerated explicitly in the column specification
at table creation time.

The value may also be the empty string (@code{""}) or @code{NULL} under
certain circumstances:

@itemize @bullet
@item
If you insert an invalid value into an @code{ENUM} (that is, a string not
present in the list of allowed values), the empty string is inserted
instead as a special error value.

@item
If an @code{ENUM} is declared @code{NULL}, @code{NULL} is also a legal value
for the column, and the default value is @code{NULL}.  If an @code{ENUM} is
declared @code{NOT NULL}, the default value is the first element of the
list of allowed values.
@end itemize

Each enumeration value has an index:

@itemize @bullet
@item
Values from the list of allowable elements in the column specification are
numbered beginning with 1.

@item
The index value of the empty string error value is 0.  This means that you
can use the following @code{SELECT} statement to find rows into which invalid
@code{ENUM} values were assigned:

@example
mysql> SELECT * FROM tbl_name WHERE enum_col=0;
@end example

@item
The index of the @code{NULL} value is @code{NULL}.
@end itemize

For example, a column specified as @code{ENUM("one", "two", "three")} can
have any of the values shown below.  The index of each value is also shown:

@multitable @columnfractions .2 .8
@item @strong{Value} @tab @strong{Index}
@item @code{NULL}    @tab @code{NULL}
@item @code{""}      @tab 0
@item @code{"one"}   @tab 1
@item @code{"two"}   @tab 2
@item @code{"three"} @tab 3
@end multitable

An enumeration can have a maximum of 65535 elements.

Lettercase is irrelevant when you assign values to an @code{ENUM} column.
However, values retrieved from the column later have lettercase matching the
values that were used to specify the allowable values at table creation time.

If you retrieve an @code{ENUM} in a numeric context, the column value's index
is returned.  If you store a number into an @code{ENUM}, the number is
treated as an index, and the the value stored is the enumeration member with
that index.

@code{ENUM} values are sorted according to the order in which the enumeration
members were listed in the column specification.  (In other words,
@code{ENUM} values are sorted according to their index numbers.)  For
example, @code{"a"} sorts before @code{"b"} for @code{ENUM("a", "b")}, but
@code{"b"} sorts before @code{"a"} for @code{ENUM("b", "a")}.  The empty
string sorts before non-empty strings, and @code{NULL} values sort before
all other enumeration values.

If you want to get all possible values for an @code{ENUM} column, you should
use: @code{SHOW COLUMNS FROM table_name LIKE enum_column_name} and parse
the @code{ENUM} definition in the second column.

@tindex SET
@node SET,  , ENUM, String types
@subsubsection The @code{SET} type

A @code{SET} is a string object that can have zero or more values, each of
which must be chosen from a list of allowed values specified when the table
is created.  @code{SET} column values that consist of multiple set members
are specified with members separated by commas (@samp{,}).  A consequence of
this is that @code{SET} member values cannot themselves contain commas.

For example, a column specified as @code{SET("one", "two") NOT NULL} can have
any of these values:

@example
""
"one"
"two"
"one,two"
@end example


A @code{SET} can have a maximum of 64 different members.

@strong{MySQL} stores @code{SET} values numerically, with the low-order bit
of the stored value corresponding to the first set member.  If you retrieve a
@code{SET} value in a numeric context, the value retrieved has bits set
corresponding to the set members that make up the column value.  If a number
is stored into a @code{SET} column, the bits that are set in the binary
representation of the number determine the set members in the column value.
Suppose a column is specified as @code{SET("a","b","c","d")}.  Then the
members have the following bit values:

@multitable @columnfractions .2 .2 .6
@item @code{SET} @strong{member} @tab @strong{Decimal value} @tab @strong{Binary value}
@item @code{a} @tab @code{1} @tab @code{0001}
@item @code{b} @tab @code{2} @tab @code{0010}
@item @code{c} @tab @code{4} @tab @code{0100}
@item @code{d} @tab @code{8} @tab @code{1000}
@end multitable

If you assign a value of @code{9} to this column, that is @code{1001} in
binary, so the first and fourth @code{SET} value members @code{"a"} and
@code{"d"} are selected and the resulting value is @code{"a,d"}.

For a value containing more than one @code{SET} element, it does not matter
what order the elements are listed in when you insert the value.  It also
doesn't not matter how many times a given element is listed in the value.
When the value is retrieved later, each element in the value will appear
once, with elements listed according to the order in which they were
specified at table creation time.  For example, if a column is specified as
@code{SET("a","b","c","d")}, then @code{"a,d"}, @code{"d,a"} and
@code{"d,a,a,d,d"} will all appear as @code{"a,d"} when retrieved.

@code{SET} values are sorted numerically.  @code{NULL} values sort before
non-@code{NULL} @code{SET} values.

Normally, you perform a @code{SELECT} on a @code{SET} column using
the @code{LIKE} operator or the @code{FIND_IN_SET()} function:

@example
mysql> SELECT * FROM tbl_name WHERE set_col LIKE '%value%';
mysql> SELECT * FROM tbl_name WHERE FIND_IN_SET('value',set_col)>0;
@end example

But the following will also work:

@example
mysql> SELECT * FROM tbl_name WHERE set_col = 'val1,val2';
mysql> SELECT * FROM tbl_name WHERE set_col & 1;
@end example

The first of these statements looks for an exact match.  The second looks
for values containing the first set member.

If you want to get all possible values for an @code{SET} column, you should
use: @code{SHOW COLUMNS FROM table_name LIKE set_column_name} and parse
the @code{SET} definition in the second column.

@cindex Types, choosing
@cindex Choosing types
@node Choosing types, Indexes, String types, Column types
@subsection Choosing the right type for a column

For the most efficient use of storage, try to use the most precise type in
all cases. For example, if an integer column will be used for values in the
range between @code{1} and @code{99999}, @code{MEDIUMINT UNSIGNED} is the
best type.

Accurate representation of monetary values is a common problem. In
@strong{MySQL}, you should use the @code{DECIMAL} type. This is stored as
a string, so no loss of accuracy should occur. If accuracy is not
too important, the @code{DOUBLE} type may also be good enough.

For high precision, you can always convert to a fixed-point type
stored in a @code{BIGINT}. This allows you to do all calculations with
integers and convert results back to floating-point values only when necessary.

@xref{Row format}.

@cindex Indexes
@cindex Keys
@node Indexes, Multiple-column indexes, Choosing types, Column types
@subsection Column indexes

All @strong{MySQL} column types can be indexed except @code{BLOB}
and @code{TEXT} types. Use of indexes on the relevant columns is the best
way to improve the performance of @code{SELECT} operations.

A table may have up to 16 indexes.  The maximum index length is
256 bytes, although this may be changed when compiling @strong{MySQL}.

You cannot index a column that may contain @code{NULL} values, so indexed
columns must be declared @code{NOT NULL}.

For @code{CHAR} and @code{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 @code{CREATE TABLE} statement to
index a column prefix looks like this:

@example
KEY index_name (col_name(length))
@end example

The example below creates an index for the first 10 characters of the
@code{name} column:

@example
mysql> CREATE TABLE test (
           name CHAR(200) NOT NULL,
           KEY index_name (name(10)));
@end example

@node Multiple-column indexes, Other-vendor column types, Indexes, Column types
@subsection Multiple-column indexes

@strong{MySQL} can create indexes from multiple columns.  An index may
consist up up to 15 columns (or column prefixes, for @code{CHAR} and
@code{VARCHAR} columns).

A multiple-column index can be considered a sorted array containing values
that are created by concatenating the values of the indexed columns.

@strong{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
@code{WHERE} clause, even if you don't specify values for the other columns.

Suppose a table is created using the following specification:

@example
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));
@end example

Then the index @code{name} is an index over @code{last_name} and
@code{first_name}.  The index will be used for queries that specify
values in a known range for @code{last_name}, or for both @code{last_name}
and @code{first_name}.
Therefore, the @code{name} index will be used in the following queries:

@example
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";
@end example

However, the @code{name} index will NOT be used in the following queries:

@example
mysql> SELECT * FROM test WHERE first_name="Michael";

mysql> SELECT * FROM test WHERE last_name="Widenius"
                          OR first_name="Michael";
@end example

For more information on the manner in which @strong{MySQL} uses indexes to
improve query performance, see @ref{MySQL indexes, , @strong{MySQL}
indexes}.

@cindex Type portability
@node Other-vendor column types,  , Multiple-column indexes, Column types
@subsection Using column types from other database engines

To make it easier to use code written for SQL implementations from other
vendors, @strong{MySQL} maps column types as shown in the table below.  These
mappings make it easier to move table definitions from other database engines
to @strong{MySQL}:

@multitable @columnfractions .4 .6
@item @strong{Other vendor type}        @tab @strong{MySQL type}
@item @code{BINARY(NUM)}		@tab @code{CHAR(NUM) BINARY}
@item @code{CHAR VARYING(NUM)}		@tab @code{VARCHAR(NUM)}
@item @code{FLOAT4}			@tab @code{FLOAT}
@item @code{FLOAT8}			@tab @code{DOUBLE}
@item @code{INT1}			@tab @code{TINYINT}
@item @code{INT2}			@tab @code{SMALLINT}
@item @code{INT3}			@tab @code{MEDIUMINT}
@item @code{INT4}			@tab @code{INT}
@item @code{INT8}			@tab @code{BIGINT}
@item @code{LONG VARBINARY}		@tab @code{MEDIUMBLOB}
@item @code{LONG VARCHAR}		@tab @code{MEDIUMTEXT}
@item @code{MIDDLEINT}			@tab @code{MEDIUMINT}
@item @code{VARBINARY(NUM)}		@tab @code{VARCHAR(NUM) BINARY}
@end multitable

Column type mapping occurs at table creation time.  If you create a table
with types used by other vendors and then issue a @code{DESCRIBE tbl_name}
statement, @strong{MySQL} reports the table structure using the equivalent
@strong{MySQL} types.

@cindex Functions for @code{SELECT} and @code{WHERE} clauses
@node Functions, CREATE DATABASE, Column types, Reference
@section Functions for use in @code{SELECT} and @code{WHERE} clauses

A @code{select_expression} or @code{where_definition} in a SQL statement
can consist of any expression using the functions described below.

An expression that contains @code{NULL} always produces a @code{NULL} value
unless otherwise indicated in the documentation for the operators and
functions involved in the expression.

@strong{Note:} There must be no whitespace between a function name and the
parenthesis following it. This helps the @strong{MySQL} parser distinguish
between function calls and references to tables or columns that happen to
have the same name as a function.  Spaces around arguments are permitted,
though.

@need 2000
For the sake of brevity, examples display the output from the @code{mysql}
program in abbreviated form.  So this:

@example
mysql> select MOD(29,9);
1 rows in set (0.00 sec)

+-----------+
| mod(29,9) |
+-----------+
|         2 |
+-----------+
@end example

Is displayed like this:

@example
mysql> select MOD(29,9);
        -> 2
@end example

@menu
* Grouping functions::          Grouping functions
* Arithmetic functions::        Normal arithmetic operations
* Bit functions::               Bit functions
* Logical functions::           Logical operations
* Comparison functions::        Comparison operators
* String comparison functions::  String comparison functions
* Casts::                       Cast operators
* Control flow functions::      Control flow functions
* Mathematical functions::      Mathematical functions
* String functions::            String functions
* Date and time functions::     Date and time functions
* Miscellaneous functions::     Miscellaneous functions
* Group by functions::          Functions for @code{GROUP BY} clause
@end menu

@node Grouping functions, Arithmetic functions, Functions, Functions
@subsection Grouping functions
@cindex Grouping of expressions
@table @code

@findex () (parentheses)
@findex parentheses ( and )
@item ( ... )
Parentheses. Use these to force the order of evaluation in an expression.
@example
mysql> select 1+2*3;
        -> 7
mysql> select (1+2)*3;
        -> 9
@end example
@end table

@node Arithmetic functions, Bit functions, Grouping functions, Functions
@subsection Normal arithmetic operations

The usual arithmetic operators are available.  Note that in the case of
@code{-}, @code{+} and @code{*}, the result is calculated with @code{BIGINT}
(64-bit) precision if both arguments are integers!

@cindex Arithmetic expressions
@table @code
@findex + (addition)
@findex addition (+)
@item +
Addition
@example
mysql> select 3+5;
        -> 8
@end example

@findex - (subtraction)
@findex subtraction (-)
@item -
Subtraction
@example
mysql> select 3-5;
        -> -2
@end example

@findex * (multiplication)
@findex multiplication (*)
@item *
Multiplication
@example
mysql> select 3*5;
        -> 15
mysql> select 18014398509481984*18014398509481984.0;
        -> 324518553658426726783156020576256.0
mysql> select 18014398509481984*18014398509481984;
        -> 0
@end example

The result of the last expression is incorrect because the result of the integer
multiplication exceeds the 64-bit range of @code{BIGINT} calculations.

@findex / (division)
@findex division (/)
@item /
Division
@example
mysql> select 3/5;
        -> 0.60
@end example

Division by zero produces a @code{NULL} result:

@example
mysql> select 102/(1-1);
        -> NULL
@end example

A division will be calculated with @code{BIGINT} arithmetic only if performed
in a context where its result is converted to an integer!
@end table

@findex Arithmetic functions
@findex Bit functions
@findex Functions, arithmetic
@findex Functions, bit
@node Bit functions, Logical functions, Arithmetic functions, Functions
@subsection Bit functions

@strong{MySQL} uses @code{BIGINT} (64-bit) arithmetic for bit operations, so
these operators have a maximum range of 64 bits.

@table @code
@findex | (bitwise OR)
@findex OR, bitwise
@item |
Bitwise OR
@example
mysql> select 29 | 15;
        -> 31
@end example

@findex & (bitwise AND)
@findex AND, bitwise
@item &
Bitwise AND
@example
mysql> select 29 & 15;
        -> 13
@end example

@findex << (left shift)
@item <<
Shifts a longlong (@code{BIGINT}) number to the left.
@example
mysql> select 1 << 2
        -> 4
@end example

@findex >> (right shift)
@item >>
Shifts a longlong (@code{BIGINT}) number to the right.
@example
mysql> select 4 >> 2
        -> 1
@end example

@findex BIT_COUNT()
@item BIT_COUNT(N)
Returns the number of bits that are set in the argument @code{N}.
@example
mysql> select BIT_COUNT(29);
        -> 4
@end example
@end table

@findex Logical functions
@findex Functions, logical
@node Logical functions, Comparison functions, Bit functions, Functions
@subsection Logical operations

All logical functions return @code{1} (TRUE) or @code{0} (FALSE).

@table @code
@findex NOT, logical
@findex ! (logical NOT)
@item NOT
@itemx !
Logical NOT. Returns @code{1} if the argument is @code{0}, otherwise returns
@code{0}.
Exception: @code{NOT NULL} returns @code{NULL}.
@example
mysql> select NOT 1;
        -> 0
mysql> select NOT NULL;
        -> NULL
mysql> select ! (1+1);
        -> 0
mysql> select ! 1+1;
        -> 1
@end example
The last example returns @code{1} because the expression evaluates
the same way as @code{(!1)+1}.

@findex OR, logical
@findex || (logical OR)
@item OR
@itemx ||
Logical OR. Returns @code{1} if either argument is not @code{0} and not
@code{NULL}.
@example
mysql> select 1 || 0;
        -> 1
mysql> select 0 || 0;
        -> 0
mysql> select 1 || NULL;
        -> 1

@end example

@findex AND, logical
@findex && (logical AND)
@item AND
@itemx &&
Logical AND. Returns @code{0} if either argument is @code{0} or @code{NULL},
otherwise returns @code{1}.
@example
mysql> select 1 && NULL;
        -> 0
mysql> select 1 && 0;
        -> 0
@end example
@end table

@cindex Casts
@cindex Type conversions
@findex Comparison operators
@node Comparison functions, String comparison functions, Logical functions, Functions
@subsection Comparison operators

Comparison operations result in a value of @code{1} (TRUE), @code{0} (FALSE)
or @code{NULL}. These functions work for both numbers and strings.  Strings
are automatically converted to numbers and numbers to strings as needed (as
in Perl).

@strong{MySQL} performs comparisons using the following
rules:

@itemize @bullet
@item
If one or both arguments are @code{NULL}, the result of the comparison
is @code{NULL}.

@item
If both arguments in a comparison operation are strings, they are compared as
strings.

@item
If both arguments are integers, they are compared as integers.

@item
@cindex ODBC compatibility
@cindex Compatibility, with ODBC
If one of the arguments is a @code{TIMESTAMP} or @code{DATETIME} column and
the other argument is a constant, the constant is converted
to a timestamp before the comparison is performed. This is done to be more
ODBC-friendly.

@item
In all other cases, the arguments are compared as floating-point (real) numbers.
@end itemize

By default, string comparisons are done in case-independent fashion using the
current character set (ISO-8859-1 Latin1 by default, which also works
excellently for English).

The examples below illustrate conversion of strings to numbers for comparison
operations:

@example
mysql> SELECT 1 > '6x';
         -> 0
mysql> SELECT 7 > '6x';
         -> 1
mysql> SELECT 0 > 'x6';
         -> 0
mysql> SELECT 0 = 'x6';
         -> 1
@end example

@table @code
@findex = (equal)
@findex equal (=)
@item =
Equal
@example
mysql> select 1 = 0;
        -> 0
mysql> select '0' = 0;
        -> 1
mysql> select '0.0' = 0;
        -> 1
mysql> select '0.01' = 0;
        -> 0
mysql> select '.01' = 0.01;
        -> 1
@end example

@findex <> (not equal)
@findex not equal (<>)
@findex != (not equal)
@findex not equal (!=)
@item <>
@itemx !=
Not equal
@example
mysql> select '.01' <> '0.01';
        -> 1
mysql> select .01 <> '0.01';
        -> 0
mysql> select 'zapp' <> 'zappp';
        -> 1
@end example

@findex <= (less than or equal)
@findex less than or equal (<=)
@item <=
Less than or equal
@example
mysql> select 0.1 <= 2;
        -> 1
@end example

@findex < (less than)
@findex less than (<)
@item <
Less than
@example
mysql> select 2 <= 2;
        -> 1
@end example

@findex >= (greater than or equal)
@findex greater than or equal (>=)
@item >=
Greater than or equal
@example
mysql> select 2 >= 2;
        -> 1
@end example

@findex > (greater than)
@findex greater than (>)
@item >
Greater than
@example
mysql> select 2 > 2;
        -> 0
@end example

@findex <=> (Equal to)
@item <=>
Null safe equal
@example
mysql> select 1 <=> 1, NULL <=> NULL, 1 <=> NULL;
        -> 1 1 0
@end example

@findex ISNULL()
@item ISNULL(expr)
If @code{expr} is @code{NULL}, @code{ISNULL()} returns @code{1}, otherwise
it returns @code{0}.
@example
mysql> select ISNULL(1+1);
        -> 0
mysql> select ISNULL(1/0);
        -> 1
@end example

Note that a comparison of @code{NULL} values using @code{=} will always be
false!

@findex BETWEEN ... AND
@item expr BETWEEN min AND max
If @code{expr} is greater than or equal to @code{min} and @code{expr} is less
than or equal to @code{max}, @code{BETWEEN} returns @code{1}, otherwise it
returns @code{0}.  This is equivalent to the expression @code{(min <= expr
AND expr <= max)} if all the arguments are of the same type.  The first
argument (@code{expr}) determines how the comparison is performed.  If
@code{expr} is a string expression, a case-insensitive string comparison is
done.  If @code{expr} is a binary string, a case-sensitive string comparison
is done.  If @code{expr} is an integer expression, an integer comparison is
done.  Otherwise, a floating-point (real) comparison is done.

@example
mysql> select 1 BETWEEN 2 AND 3;
        -> 0
mysql> select 'b' BETWEEN 'a' AND 'c';
        -> 1
mysql> select 2 BETWEEN 2 AND '3';
        -> 1
mysql> select 2 BETWEEN 2 AND 'x-3';
        -> 0
@end example

@findex IN
@item expr IN (value,...)
Returns @code{1} if @code{expr} is any of the values in the @code{IN} list,
else returns @code{0}.  If all values are constants, then all values are
evaluated according to the type of @code{expr} and sorted. The search for the
item is then done using a binary search. This means @code{IN} is very quick
if the @code{IN} value list consists entirely of constants.  If @code{expr}
is a case-sensitive string expression, the string comparison is performed in
case-sensitive fashion.

@example
mysql> select 2 IN (0,3,5,'wefwf');
        -> 0
mysql> select 'wefwf' IN (0,3,5,'wefwf');
        -> 1
@end example

@findex NOT IN
@item expr NOT IN (value,...)
Same as @code{NOT (expr IN (value,...))}.

@findex INTERVAL()
@item INTERVAL(N,N1,N2,N3,...)
Returns @code{0} if @code{N} < @code{N1}, @code{1} if @code{N} < @code{N2}
and so on. All arguments are treated as numbers.  It is required that
@code{N1} < @code{N2} < @code{N3} < @code{...} < @code{Nn} for this function
to work correctly. This is because a binary search is used (very fast).

@example
mysql> select INTERVAL(23, 1, 15, 17, 30, 44, 200);
        -> 3
mysql> select INTERVAL(10, 1, 10, 100, 1000);
        -> 2
mysql> select INTERVAL(22, 23, 30, 44, 200);
        -> 0
@end example
@end table

@findex String comparison functions
@findex Functions, string comparison
@node String comparison functions, Casts, Comparison functions, Functions
@subsection String comparison functions

@cindex Case sensitivity, in string comparisons
@cindex String comparisons, case sensitivity
Normally, if any expression in a string comparison is case sensitive, the
comparison is performed in case-sensitive fashion.

@table @code
@findex LIKE
@item expr1 LIKE expr2 [ESCAPE 'escape-char']
SQL simple regular expression comparison. Returns @code{1} (TRUE) or @code{0}
(FALSE).  With @code{LIKE} you can use the following two wildcard characters:

@multitable @columnfractions .1 .9
@item @code{%} @tab Matches any number of characters, even zero characters
@item @code{_} @tab Matches exactly one character
@end multitable

@example
mysql> select 'David!' LIKE 'David_';
        -> 1
mysql> select 'David!' LIKE '%D%v%';
        -> 1
@end example

To test for literal instances of a wildcard character, precede the character
with the escape character.  If you don't specify the @code{ESCAPE} character,
@samp{\} is assumed:

@multitable @columnfractions .1 .9
@item @code{\%} @tab Matches one @code{%} character
@item @code{\_} @tab Matches one @code{_} character
@end multitable

@example
mysql> select 'David!' LIKE 'David\_';
        -> 0
mysql> select 'David_' LIKE 'David\_';
        -> 1
@end example

To specify a different escape character, use the @code{ESCAPE} clause:

@example
mysql> select 'David_' LIKE 'David|_' ESCAPE '|';
        -> 1
@end example

@code{LIKE} is allowed on numeric expressions! (This is a @strong{MySQL}
extension to the ANSI SQL @code{LIKE}.)

@example
mysql> select 10 LIKE '1%';
        -> 1
@end example

Note: Because @strong{MySQL} uses the C escape syntax in strings (e.g.,
@samp{\n}), you must double any @samp{\} that you use in your @code{LIKE}
strings.  For example, to search for @samp{\n}, specify it as @samp{\\n}.  To
search for @samp{\}, specify it as @samp{\\\\} (the backslashes are stripped
once by the parser, and another time when the pattern match is done, leaving
a single backslash to be matched).

@findex NOT LIKE
@item expr1 NOT LIKE expr2 [ESCAPE 'escape-char']
Same as @code{NOT (expr1 LIKE expr2 [ESCAPE 'escape-char'])}.

@cindex mSQL compatibility
@cindex Compatibility, with mSQL
@findex REGEXP
@findex RLIKE
@item expr REGEXP pat
@itemx expr RLIKE pat
Performs a pattern match of a string expression @code{expr} against a pattern
@code{pat}.  The pattern can be an extended regular expression.
@xref{Regexp}.  Returns @code{1} if @code{expr} matches @code{pat}, otherwise
returns @code{0}.  @code{RLIKE} is a synonym for @code{REGEXP}, provided for
@code{mSQL} compatibility. Note: Because @strong{MySQL} uses the C escape
syntax in strings (e.g., @samp{\n}), you must double any @samp{\} that you
use in your @code{REGEXP} strings.

@example
mysql> select 'Monty!' REGEXP 'm%y%%';
        -> 0
mysql> select 'Monty!' REGEXP '.*';
        -> 1
mysql> select 'new*\n*line' REGEXP 'new\\*.\\*line';
        -> 1
@end example

@item
@code{REGEXP} and @code{RLIKE} use the current character set (ISO-8859-1
Latin1 by default) when deciding the type of a character.

@findex NOT REGEXP
@item expr NOT REGEXP expr
Same as @code{NOT (expr REGEXP expr)}.

@findex STRCMP()
@item STRCMP(expr1,expr2)
@code{STRCMP()}
returns @code{0} if the strings are the same, @code{-1} if the first
argument is smaller than the second according to the current sort order,
and @code{1} otherwise.

@example
mysql> select STRCMP('text', 'text2');
        -> -1
mysql> select STRCMP('text2', 'text');
        -> 1
mysql> select STRCMP('text', 'text');
        -> 0
@end example
@end table

@findex Casts
@node Casts, Control flow functions, String comparison functions, Functions
@subsection Cast operators

@table @code
@findex BINARY
@item @code{BINARY}
The @code{BINARY} operator casts the string following it to a binary string.  This is
an easy way to force a column comparison to be case independent even if
the column isn't defined as @code{BINARY} or @code{BLOB}.
@example
mysql> select "a" = "A";
        -> 1
mysql> select BINARY "a" = "A";
        -> 0
@end example

@code{BINARY} was introduced in @strong{MySQL} 3.23.0
@end table

@findex Control flow functions
@findex Functions, control flow
@node Control flow functions, Mathematical functions, Casts, Functions
@subsection Control flow functions

@table @code
@findex IFNULL()
@item IFNULL(expr1,expr2)
If @code{expr1} is not @code{NULL}, @code{IFNULL()} returns @code{expr1},
else it returns @code{expr2}.  @code{IFNULL()} returns a numeric or string
value, depending on the context in which it is used.
@example
mysql> select IFNULL(1,0);
        -> 1
mysql> select IFNULL(0,10);
        -> 0
mysql> select IFNULL(1/0,10);
        -> 10
mysql> select IFNULL(1/0,'yes');
        -> 'yes'
@end example

@findex IF()
@item IF(expr1,expr2,expr3)
If @code{expr1} is TRUE (@code{expr1 <> 0} and @code{expr1 <> NULL}) then
@code{IF()} returns @code{expr2}, else it returns @code{expr3}.
@code{IFNULL()} returns a numeric or string value, depending on the context
in which it is used.

@example
mysql> select IF(1>2,2,3);
        -> 3
mysql> select IF(1<2,'yes','no');
        -> 'yes'
mysql> select IF(strcmp('test','test1'),'yes','no');
        -> 'no'
@end example

@code{expr1} is evaluated as an integer value, which means that if you are
testing floating-point or string values, you should do so using a comparison
operation.

@example
mysql> select IF(0.1,1,0);
        -> 0
mysql> select IF(0.1<>0,1,0);
        -> 1
@end example

In the first case above, @code{IF(0.1)} returns @code{0} because @code{0.1}
is converted to an integer value, resulting in a test of @code{IF(0)}.  This
may not be what you expect.  In the second case, the comparison tests the
original floating-point value to see whether it is non-zero.  The result
of the comparison is used as an integer.
@end table

@findex Mathematical functions
@findex Functions, mathematical
@node Mathematical functions, String functions, Control flow functions, Functions
@subsection Mathematical functions
All mathematical functions return @code{NULL} in case of an error.

@table @code
@findex - (unary minus)
@findex minus, unary (-)
@findex unary minus (-)
@item -
Unary minus. Changes the sign of the argument.
@example
mysql> select - 2;
        -> -2
@end example

Note that if this operator is used with a @code{BIGINT}, the return value is a
@code{BIGINT}!  This means that you should avoid using @code{-} on integers that
may have the value of @code{-2^63}!

@findex ABS()
@item ABS(X)
Returns the absolute value of @code{X}.
@example
mysql> select ABS(2);
        -> 2
mysql> select ABS(-32);
        -> 32
@end example

This function is safe to use with @code{BIGINT} values.

@findex SIGN()
@item SIGN(X)
Returns the sign of the argument as @code{-1}, @code{0} or @code{1}, depending
on whether @code{X} is negative, zero, or positive.
@example
mysql> select SIGN(-32);
        -> -1
mysql> select SIGN(0);
        -> 0
mysql> select SIGN(234);
        -> 1
@end example

@findex MOD()
@findex % (modulo)
@findex modulo (%)
@item MOD(N,M)
@itemx %
Modulo (like the @code{%} operator in C).
Returns the remainder of @code{N} divided by @code{M}.
@example
mysql> select MOD(234, 10);
        -> 4
mysql> select 253 % 7;
        -> 1
mysql> select MOD(29,9);
        -> 2
@end example

This function is safe to use with @code{BIGINT} values.

@findex FLOOR()
@item FLOOR(X)
Returns the largest integer value not greater than @code{X}.
@example
mysql> select FLOOR(1.23);
        -> 1
mysql> select FLOOR(-1.23);
        -> -2
@end example

Note that the return value is converted to a @code{BIGINT}!

@findex CEILING()
@item CEILING(X)
Returns the smallest integer value not less than @code{X}.
@example
mysql> select CEILING(1.23);
        -> 2
mysql> select CEILING(-1.23);
        -> -1
@end example

Note that the return value is converted to a @code{BIGINT}!

@findex ROUND()
@item ROUND(X)
Returns the argument @code{X}, rounded to an integer.
@example
mysql> select ROUND(-1.23);
        -> -1
mysql> select ROUND(-1.58);
        -> -2
mysql> select ROUND(1.58);
        -> 2
@end example

Note that the return value is converted to a @code{BIGINT}!

@findex ROUND()
@item ROUND(X,D)
Returns the argument @code{X}, rounded to a number with @code{D} decimals.
If @code{D} is @code{0}, the result will have no decimal point or fractional
part.

@example
mysql> select ROUND(1.298, 1);
        -> 1.3
mysql> select ROUND(1.298, 0);
        -> 1
@end example

Note that the return value is converted to a @code{BIGINT}!

@findex EXP()
@item EXP(X)
Returns the value of @code{e} (the base of natural logarithms) raised to
the power of @code{X}.
@example
mysql> select EXP(2);
        -> 7.389056
mysql> select EXP(-2);
        -> 0.135335
@end example
@findex LOG()
@item LOG(X)
Returns the natural logarithm of @code{X}.
@example
mysql> select LOG(2);
        -> 0.693147
mysql> select LOG(-2);
        -> NULL
@end example
If you want the log of a number @code{X} to some arbitary base @code{B}, use
the formula @code{LOG(X)/LOG(B)}.

@findex LOG10()
@item LOG10(X)
Returns the base-10 logarithm of @code{X}.
@example
mysql> select LOG10(2);
        -> 0.301030
mysql> select LOG10(100);
        -> 2.000000
mysql> select LOG10(-100);
        -> NULL
@end example

@findex POW()
@findex POWER()
@item POW(X,Y)
@itemx POWER(X,Y)
Returns the value of @code{X} raised to the power of @code{Y}.
@example
mysql> select POW(2,2);
        -> 4.000000
mysql> select POW(2,-2);
        -> 0.250000
@end example

@findex SQRT()
@item SQRT(X)
Returns the non-negative square root of @code{X}.
@example
mysql> select SQRT(4);
        -> 2.000000
mysql> select SQRT(20);
        -> 4.472136
@end example

@findex PI()
@item PI()
Returns the value of PI.
@example
mysql> select PI();
        -> 3.141593
@end example

@findex COS()
@item COS(X)
Returns the cosine of @code{X}, where @code{X} is given in radians.
@example
mysql> select COS(PI());
        -> -1.000000
@end example

@findex SIN()
@item SIN(X)
Returns the sine of @code{X}, where @code{X} is given in radians.
@example
mysql> select SIN(PI());
        -> 0.000000
@end example

@findex TAN()
@item TAN(X)
Returns the tangent of @code{X}, where @code{X} is given in radians.
@example
mysql> select TAN(PI()+1);
        -> 1.557408
@end example

@findex ACOS()
@item ACOS(X)
Returns the arc cosine of @code{X}, that is, the value whose cosine is
@code{X}. Returns @code{NULL} if @code{X} is not in the range @code{-1} to
@code{1}.
@example
mysql> select ACOS(1);
        -> 0.000000
mysql> select ACOS(1.0001);
        -> NULL
mysql> select ACOS(0);
        -> 1.570796
@end example

@findex ASIN()
@item ASIN(X)
Returns the arc sine of @code{X}, that is, the value whose sine is
@code{X}. Returns @code{NULL} if @code{X} is not in the range @code{-1} to
@code{1}.
@example
mysql> select ASIN(0.2);
        -> 0.201358
mysql> select ASIN('foo');
        -> 0.000000
@end example

@findex ATAN()
@item ATAN(X)
Returns the arc tangent of @code{X}, that is, the value whose tangent is
@code{X}.
@example
mysql> select ATAN(2);
        -> 1.107149
mysql> select ATAN(-2);
        -> -1.107149
@end example

@findex ATAN2()
@item ATAN2(X,Y)
Returns the arc tangent of the two variables @code{X} and @code{Y}. It is
similar to calculating the arc tangent of @code{Y / X}, except that the
signs of both arguments are used to determine the quadrant of the
result.
@example
mysql> select ATAN(-2,2);
        -> -0.785398
mysql> select ATAN(PI(),0);
        -> 1.570796
@end example

@findex COT()
@item COT(X)
Returns the cotangent of @code{X}.
@example
mysql> select COT(12);
        -> -1.57267341
mysql> select COT(0);
        -> NULL
@end example

@findex RAND()
@item RAND()
@itemx RAND(N)
Returns a random floating-point value in the range @code{0} to @code{1.0}.
If an integer argument @code{N} is specified, it is used as the seed value.
@example
mysql> select RAND();
        -> 0.5925
mysql> select RAND(20);
        -> 0.1811
mysql> select RAND(20);
        -> 0.1811
mysql> select RAND();
        -> 0.2079
mysql> select RAND();
        -> 0.7888
@end example
You can't use a column with @code{RAND()} values in an @code{ORDER BY}
clause, because @code{ORDER BY} would evaluate the column multiple times.

@findex LEAST()
@item LEAST(X,Y,...)
With two or more arguments, returns the smallest (minimum-valued) argument.
The arguments are compared using the following rules:

@itemize @bullet
@item
If the return value is used in an @code{INTEGER} context, or all arguments
are integer-valued, they are compared as integers.

@item
If the return value is used in a @code{REAL} context, or all arguments are
real-valued, they are compared as reals.

@item
If any argument is a case-sensitive string, the arguments are compared
as case-sensitive strings.

@item
In other cases, the arguments are compared as case-insensitive strings.
@end itemize

@example
mysql> select LEAST(2,0);
        -> 0
mysql> select LEAST(34.0,3.0,5.0,767.0);
        -> 3.0
mysql> select LEAST("B","A","C");
        -> "A"
@end example
In @strong{MySQL} versions prior to 3.22.5, you can use @code{MIN()} instead
of @code{LEAST}.

@findex GREATEST()
@item GREATEST(X,Y,...)
Returns the largest (maximum-valued) argument.
The arguments are compared using the same rules as for @code{LEAST}.
@example
mysql> select GREATEST(2,0);
        -> 2
mysql> select GREATEST(34.0,3.0,5.0,767.0);
        -> 767.0
mysql> select GREATEST("B","A","C");
        -> "C"
@end example
In @strong{MySQL} versions prior to 3.22.5, you can use @code{MAX()} instead
of @code{GREATEST}.

@findex DEGREES()
@item DEGREES(X)
Returns the argument @code{X}, converted from radians to degrees.
@example
mysql> select DEGREES(PI());
        -> 180.000000
@end example

@findex RADIANS()
@item RADIANS(X)
Returns the argument @code{X}, converted from degrees to radians.
@example
mysql> select RADIANS(90);
        -> 1.570796
@end example

@findex TRUNCATE()
@item TRUNCATE(X,D)
Returns the number @code{X}, truncated to @code{D} decimals.
@example
mysql> select TRUNCATE(1.223,1);
        -> 1.2
mysql> select TRUNCATE(1.999,1);
        -> 1.9
mysql> select TRUNCATE(1.999,0);
        -> 1
@end example
@end table

@findex String functions
@findex Functions, string
@node String functions, Date and time functions, Mathematical functions, Functions
@subsection String functions

String-valued functions return @code{NULL} if the length of the result would
be greater than the @code{max_allowed_packet} server parameter.  @xref{Server
parameters}.

For functions that operate on string positions,
the first position is numbered 1.

@table @code
@findex ASCII()
@item ASCII(str)
Returns the ASCII code value of the leftmost character of the string
@code{str}. Returns @code{0} if @code{str} is the empty string.  Returns
@code{NULL} if @code{str} is @code{NULL}.

@example
mysql> select ASCII('2');
        -> 50
mysql> select ASCII(2);
        -> 50
mysql> select ASCII('dx');
        -> 100
@end example

@findex CONV()
@item CONV(N,from_base,to_base)
Converts numbers between different number bases.  Returns a string
representation of the number @code{N}, converted from base @code{from_base}
to base @code{to_base}.  Returns @code{NULL} if any argument is @code{NULL}.
The argument @code{N} is interpreted as an integer, but may be specified as
an integer or a string.  The minimum base is @code{2} and the maximum base is
@code{36}.  If @code{to_base} is a negative number, @code{N} is regarded as a
signed number.  Otherwise, @code{N} is treated as unsigned.  @code{CONV} works
with 64-bit precision.

@example
mysql> select CONV("a",16,2);
        -> '1010'
mysql> select CONV("6E",18,8);
        -> '172'
mysql> select CONV(-17,10,-18);
        -> '-H'
mysql> select CONV(10+"10"+'10'+0xa,10,10);
        -> '40'
@end example

@findex BIN()
@item BIN(N)
Returns a string representation of the binary value of @code{N}, where
@code{N} is a longlong (@code{BIGINT}) number.  This is equivalent to
@code{CONV(N,10,2)}.  Returns @code{NULL} if @code{N} is @code{NULL}.

@example
mysql> select BIN(12);
        -> '1100'
@end example

@findex OCT()
@item OCT(N)
Returns a string representation of the octal value of @code{N}, where
@code{N} is a longlong number.  This is equivalent to @code{CONV(N,10,8)}.
Returns @code{NULL} if @code{N} is @code{NULL}.

@example
mysql> select OCT(12);
        -> '14'
@end example

@findex HEX()
@item HEX(N)
Returns a string representation of the hexadecimal value of @code{N}, where
@code{N} is a longlong (@code{BIGINT}) number.  This is equivalent to
@code{CONV(N,10,16)}.  Returns @code{NULL} if @code{N} is @code{NULL}.

@example
mysql> select HEX(255);
        -> 'FF'
@end example

@findex CHAR()
@item CHAR(N,...)
@code{CHAR()} interprets the arguments as integers and returns a string
consisting of the characters given by the ASCII code values of those
integers. @code{NULL} values are skipped.

@example
mysql> select CHAR(77,121,83,81,'76');
        -> 'MySQL'
mysql> select CHAR(77,77.3,'77.3');
        -> 'MMM'
@end example

@findex CONCAT()
@item CONCAT(X,Y,...)
Returns the string that results from concatenating the arguments.  Returns
@code{NULL} if any argument is @code{NULL}.  May have more than 2 arguments.
@example
mysql> select CONCAT('My', 'S', 'QL');
        -> 'MySQL'
mysql> select CONCAT('My', NULL, 'QL');
        -> NULL
@end example

@findex LENGTH()
@findex OCTET_LENGTH()
@findex CHAR_LENGTH()
@findex CHARACTER_LENGTH()
@item LENGTH(str)
@itemx OCTET_LENGTH(str)
@itemx CHAR_LENGTH(str)
@itemx CHARACTER_LENGTH(str)
Returns the length of the string @code{str}.
@example
mysql> select LENGTH('text');
        -> 4
mysql> select OCTET_LENGTH('text');
        -> 4
@end example

@findex LOCATE()
@findex POSITION()
@item LOCATE(substr,str)
@itemx POSITION(substr IN str)
Returns the position of the first occurrence of substring @code{substr}
in string @code{str}. Returns @code{0} if @code{substr} is not in @code{str}.
@example
mysql> select LOCATE('bar', 'foobarbar');
        -> 4
mysql> select LOCATE('xbar', 'foobar');
        -> 0
@end example

@findex LOCATE()
@item LOCATE(substr,str,pos)
Returns the position of the first occurrence of substring @code{substr} in
string @code{str}, starting at position @code{pos}.
Returns @code{0} if @code{substr} is not in @code{str}.
@example
mysql> select LOCATE('bar', 'foobarbar',5);
        -> 7
@end example

@findex INSTR()
@item INSTR(str,substr)
Returns the position of the first occurrence of substring @code{substr} in
string @code{str}. This is the same as the two-argument form of
@code{LOCATE()}, except that the arguments are swapped.

@example
mysql> select INSTR('foobarbar', 'bar');
        -> 4
mysql> select INSTR('xbar', 'foobar');
        -> 0
@end example

@findex LPAD()
@item LPAD(str,len,padstr)
Returns the string @code{str}, left-padded with the string
@code{padstr} until @code{str} is @code{len} characters long.
@example
mysql> select LPAD('hi',4,'??');
        -> '??hi'
@end example

@findex RPAD()
@item RPAD(str,len,padstr)
Returns the string @code{str}, right-padded with the string
@code{padstr} until @code{str} is @code{len} characters long.
@example
mysql> select RPAD('hi',5,'?');
        -> 'hi???'
@end example

@findex LEFT()
@item LEFT(str,len)
Returns the leftmost @code{len} characters from the string @code{str}.
@example
mysql> select LEFT('foobarbar', 5);
        -> 'fooba'
@end example

@findex RIGHT()
@findex SUBSTRING()
@item RIGHT(str,len)
@itemx SUBSTRING(str FROM len)
Returns the rightmost @code{len} characters from the string @code{str}.
@example
mysql> select RIGHT('foobarbar', 4);
        -> 'rbar'
mysql> select SUBSTRING('foobarbar' FROM 4);
        -> 'rbar'
@end example

@findex SUBSTRING()
@findex MID()
@item SUBSTRING(str,pos,len)
@itemx SUBSTRING(str FROM pos FOR len)
@itemx MID(str,pos,len)
Returns a substring @code{len} characters long from string @code{str},
starting at position @code{pos}.
The variant form that uses @code{FROM} is ANSI SQL92 syntax.
@example
mysql> select SUBSTRING('Quadratically',5,6);
        -> 'ratica'
@end example

@findex SUBSTRING()
@item SUBSTRING(str,pos)
Returns a substring from string @code{str} starting at position @code{pos}.
@example
mysql> select SUBSTRING('Quadratically',5);
        -> 'ratically'
@end example

@findex SUBSTRING_INDEX()
@item SUBSTRING_INDEX(str,delim,count)
Returns the substring from string @code{str} after @code{count}
occurrences of the delimiter @code{delim}.
If @code{count} is positive, everything to the left of the final delimiter
(counting from the left) is returned.
If @code{count} is negative, everything to the right of the final delimiter
(counting from the right) is returned.
@example
mysql> select SUBSTRING_INDEX('www.mysql.com', '.', 2);
        -> 'www.mysql'
mysql> select SUBSTRING_INDEX('www.mysql.com', '.', -2);
        -> 'mysql.com'
@end example

@findex LTRIM()
@item LTRIM(str)
Returns the string @code{str} with leading space characters removed.
@example
mysql> select LTRIM('  barbar');
        -> 'barbar'
@end example

@findex RTRIM()
@item RTRIM(str)
Returns the string @code{str} with trailing space characters removed.
@example
mysql> select RTRIM('barbar   ');
        -> 'barbar'
@end example

@findex TRIM()
@item TRIM([[BOTH | LEADING | TRAILING] [remstr] FROM] str)
Returns the string @code{str} with all @code{remstr} prefixes and/or suffixes
removed. If none of the specifiers @code{BOTH}, @code{LEADING} or
@code{TRAILING} are given, @code{BOTH} is assumed. If @code{remstr} is not
specified, spaces are removed.
@example
mysql> select TRIM('  bar   ');
        -> 'bar'
mysql> select TRIM(LEADING 'x' FROM 'xxxbarxxx');
        -> 'barxxx'
mysql> select TRIM(BOTH 'x' FROM 'xxxbarxxx');
        -> 'bar'
mysql> select TRIM(TRAILING 'xyz' FROM 'barxxyz');
        -> 'barx'
@end example

@findex SOUNDEX()
@item SOUNDEX(str)
Returns a soundex string from @code{str}. Two strings that sound ``about the
same'' should have identical soundex strings. A ``standard'' soundex string
is 4 characters long, but the @code{SOUNDEX()} function returns an
arbitrarily long string. You can use @code{SUBSTRING()} on the result to get
a ``standard'' soundex string.  All non-alphanumeric characters are ignored
in the given string. All international alpha characters outside the A-Z range
are treated as vowels.

@example
mysql> select SOUNDEX('Hello');
        -> 'H400'
mysql> select SOUNDEX('Quadratically');
        -> 'Q36324'
@end example

@findex SPACE()
@item SPACE(N)
Returns a string consisting of @code{N} space characters.
@example
mysql> select SPACE(6);
        -> '      '
@end example

@findex REPLACE()
@item REPLACE(str,from_str,to_str)
Returns the string @code{str} with all all occurrences of the string
@code{from_str} replaced by the string @code{to_str}.

@example
mysql> select REPLACE('www.mysql.com', 'w', 'Ww');
        -> 'WwWwww.mysql.com'
@end example

@findex REPEAT()
@item REPEAT(str,count)
Returns a string consisting of the string @code{str} repeated @code{count}
times. If @code{count <= 0}, returns an empty string. Returns @code{NULL} if
@code{str} or @code{count} are @code{NULL}.

@example
mysql> select REPEAT('MySQL', 3);
        -> 'MySQLMySQLMySQL'
@end example

@findex REVERSE()
@item REVERSE(str)
Returns the string @code{str} with the order of the characters reversed.
@example
mysql> select REVERSE('abc');
        -> 'cba'
@end example

@findex INSERT()
@item INSERT(str,pos,len,newstr)
Returns the string @code{str}, with the substring beginning at position
@code{pos} and @code{len} characters long replaced by the string
@code{newstr}.

@example
mysql> select INSERT('Quadratic', 3, 4, 'What');
        -> 'QuWhattic'
@end example

@findex ELT()
@item ELT(N,str1,str2,str3,...)
Returns @code{str1} if @code{N} = @code{1}, @code{str2} if @code{N} =
@code{2}, and so on.  Returns @code{NULL} if @code{N} is less than @code{1}
or greater than the number of arguments.  @code{ELT()} is the complement of
@code{FIELD()}.

@example
mysql> select ELT(1, 'ej', 'Heja', 'hej', 'foo');
        -> 'ej'
mysql> select ELT(4, 'ej', 'Heja', 'hej', 'foo');
        -> 'foo'
@end example

@findex FIELD()
@item FIELD(str,str1,str2,str3,...)
Returns the index of @code{str} in the @code{str1}, @code{str2},
@code{str3}, @code{...} list.
Returns @code{0} if @code{str} is not found.
@code{FIELD()} is the complement of @code{ELT()}.

@example
mysql> select FIELD('ej', 'Hej', 'ej', 'Heja', 'hej', 'foo');
        -> 2
mysql> select FIELD('fo', 'Hej', 'ej', 'Heja', 'hej', 'foo');
        -> 0
@end example

@findex FIND_IN_SET()
@item FIND_IN_SET(str,strlist)
Returns a value @code{1} to @code{N} if the string @code{str} is in the list
@code{strlist} consisting of @code{N} substrings. A string list is a string
composed of substrings separated by @samp{,} characters. If the first
argument is a constant string and the second is a column of type @code{SET},
the @code{FIND_IN_SET()} function is optimized to use bit arithmetic!
Returns @code{0} if @code{str} is not in @code{strlist} or if @code{strlist}
is the empty string.  Returns @code{NULL} if either argument is @code{NULL}.
This function will not work properly if the first argument contains a
@samp{,}.

@example
mysql> SELECT FIND_IN_SET('b','a,b,c,d');
        -> 2
@end example

@findex MAKE_SET()
@item MAKE_SET(bits,str1,str2,...)
Returns a set (a string containing substrings separated by @samp{,}
characters) consisting of the strings that have the corresponding bit in
@code{bits} set.  @code{str1} corresponds to bit 0, @code{str2} to bit 1,
etc.  @code{NULL} strings in @code{str1}, @code{str2}, @code{...}
are not appended to the result.

@example
mysql> SELECT MAKE_SET(1,'a','b','c');
        -> 'a'
mysql> SELECT MAKE_SET(1 | 4,'hello','nice','world');
        -> 'hello,world'
mysql> SELECT MAKE_SET(0,'a','b','c');
        -> ''
@end example

@findex LCASE()
@findex LOWER()
@item LCASE(str)
@itemx LOWER(str)
Returns the string @code{str} with all characters changed to lowercase
according to the current character set mapping (the default is ISO-8859-1
Latin1).

@example
mysql> select LCASE('QUADRATICALLY');
        -> 'quadratically'
@end example

@findex UCASE()
@findex UPPER()
@item UCASE(str)
@itemx UPPER(str)
Returns the string @code{str} with all characters changed to uppercase
according to the current character set mapping (the default is ISO-8859-1
Latin1).

@example
mysql> select UCASE('Hej');
        -> 'HEJ'
@end example

@findex FILE
@item LOAD_FILE(file_name)
Reads the file and returns the file contents as a string.  The file
must be on the server and you must specify the full pathname to the
file.  The file must be readable by all and be smaller than
@code{max_allowed_packet}.

If the file doesn't exist or can't be read due to one of the above reasons,
the function returns @code{NULL}.

@example
mysql> UPDATE table_name SET blob_column=LOAD_FILE("/tmp/picture") WHERE id=1;
@end example
@end table

There is no string function to convert a number to a char.  There is no need
for one, because @strong{MySQL} automatically converts numbers to strings as
necessary, and vice versa:

@example
mysql> SELECT 1+"1";
        -> 2
mysql> SELECT CONCAT(2,' test');
        -> '2 test'
@end example

If a string function is given a binary string as an argument, the resulting
string is also a binary string.  A number converted to a string is treated as
a binary string.  This only affects comparisons.

@findex Date and time functions
@findex Functions, date and time
@node Date and time functions, Miscellaneous functions, String functions, Functions
@subsection Date and time functions

See @ref{Date and time types} for a description of the range of values
each type has, and the valid formats in which date and time values may be
specified.

Here is an example that uses date functions.  The query below selects
all records with a @code{date_col} value from within the last 30 days:

@example
mysql> SELECT something FROM table
           WHERE TO_DAYS(NOW()) - TO_DAYS(date_col) <= 30;
@end example

@table @code
@findex DAYOFWEEK()
@item DAYOFWEEK(date)
Returns the weekday index
for @code{date} (@code{1} = Sunday, @code{2} = Monday, ... @code{7} = Saturday).
These index values correspond to the ODBC standard.
@example
mysql> select DAYOFWEEK('1998-02-03');
        -> 3
@end example

@findex WEEKDAY()
@item WEEKDAY(date)
Returns the weekday index for
@code{date} (@code{0} = Monday, @code{1} = Tuesday, ... @code{6} = Sunday).
@example
mysql> select WEEKDAY('1997-10-04 22:23:00');
        -> 5
mysql> select WEEKDAY('1997-11-05');
        -> 2
@end example

@findex DAYOFMONTH()
@item DAYOFMONTH(date)
Returns the day of the month for @code{date}, in the range @code{1} to
@code{31}.
@example
mysql> select DAYOFMONTH('1998-02-03');
        -> 3
@end example

@findex DAYOFYEAR()
@item DAYOFYEAR(date)
Returns the day of the year for @code{date}, in the range @code{1} to
@code{366}.
@example
mysql> select DAYOFYEAR('1998-02-03');
        -> 34
@end example

@findex MONTH()
@item MONTH(date)
Returns the month for @code{date}, in the range @code{1} to @code{12}.
@example
mysql> select MONTH('1998-02-03');
        -> 2
@end example

@findex DAYNAME()
@item DAYNAME(date)
Returns the name of the weekday for @code{date}.
@example
mysql> select DAYNAME("1998-02-05");
        -> 'Thursday'
@end example

@findex MONTHNAME()
@item MONTHNAME(date)
Returns the name of the month for @code{date}.
@example
mysql> select MONTHNAME("1998-02-05");
        -> 'February'
@end example

@findex QUARTER()
@item QUARTER(date)
Returns the quarter of the year for @code{date}, in the range @code{1}
to @code{4}.
@example
mysql> select QUARTER('98-04-01');
        -> 2
@end example

@findex WEEK()
@item WEEK(date)
@itemx WEEK(date,first)
With a single argument, returns the week for @code{date}, in the range
@code{0} to @code{52}, for locations where Sunday is the first day of the week.
The two-argument form of @code{WEEK()} allows you to specify whether the
week starts on Sunday or Monday.  The week starts on Sunday if the second
argument is @code{0}, on Monday if the second argument is @code{1}.
@example
mysql> select WEEK('1998-02-20');
        -> 7
mysql> select WEEK('1998-02-20',0);
        -> 7
mysql> select WEEK('1998-02-20',1);
        -> 8
@end example

@findex YEAR()
@item YEAR(date)
Returns the year for @code{date}, in the range @code{1000} to @code{9999}.
@example
mysql> select YEAR('98-02-03');
        -> 1998
@end example

@findex HOUR()
@item HOUR(time)
Returns the hour for @code{time}, in the range @code{0} to @code{23}.
@example
mysql> select HOUR('10:05:03');
        -> 10
@end example

@findex MINUTE()
@item MINUTE(time)
Returns the minute for @code{time}, in the range @code{0} to @code{59}.
@example
mysql> select MINUTE('98-02-03 10:05:03');
        -> 5
@end example

@findex SECOND()
@item SECOND(time)
Returns the second for @code{time}, in the range @code{0} to @code{59}.
@example
mysql> select SECOND('10:05:03');
        -> 3
@end example

@findex PERIOD_ADD()
@item PERIOD_ADD(P,N)
Adds @code{N} months to period @code{P} (in the format @code{YYMM} or
@code{YYYYMM}). Returns a value in the format @code{YYYYMM}.

Note that the period argument @code{P} is @emph{not} a date value.

@example
mysql> select PERIOD_ADD(9801,2);
        -> 199803
@end example

@findex PERIOD_DIFF()
@item PERIOD_DIFF(P1,P2)
Returns the number of months between periods @code{P1} and @code{P2}.
@code{P1} and @code{P2} should be in the format @code{YYMM} or @code{YYYYMM}.

Note that the period arguments @code{P1} and @code{P2} are @emph{not}
date values.

@example
mysql> select PERIOD_DIFF(9802,199703);
        -> 11
@end example

@findex DATE_ADD()
@findex DATE_SUB()
@findex ADDDATE()
@findex SUBDATE()
@item DATE_ADD(date,INTERVAL expr type)
@itemx DATE_SUB(date,INTERVAL expr type)
@itemx ADDDATE(date,INTERVAL expr type)
@itemx SUBDATE(date,INTERVAL expr type)

These functions perform date arithmetic.  They are new for @strong{MySQL}
3.22.  @code{ADDDATE()} and @code{SUBDATE()} are synonyms for
@code{DATE_ADD()} and @code{DATE_SUB()}.

@code{date} is a @code{DATETIME} or @code{DATE} value specifying the starting
date.  @code{expr} is an expression specifying the interval value to be added
or substracted from the starting date.  @code{expr} is a string; it may start
with a @samp{-} for negative intervals.  @code{type} is a keyword indicating
how the expression should be interpreted.

The following table shows how the @code{type} and @code{expr} arguments
are related:

@multitable @columnfractions .18 .3 .42
@item @code{type} @strong{value} @tab @strong{Meaning} @tab @strong{Expected} @code{expr} @strong{format}
@item @code{SECOND}        @tab Seconds             @tab @code{SECONDS}
@item @code{MINUTE}        @tab Minutes             @tab @code{MINUTES}
@item @code{HOUR}          @tab Hours               @tab @code{HOURS}
@item @code{DAY}           @tab Days                @tab @code{DAYS}
@item @code{MONTH}         @tab Months              @tab @code{MONTHS}
@item @code{YEAR}          @tab Years               @tab @code{YEARS}
@item @code{MINUTE_SECOND} @tab Minutes and seconds @tab @code{"MINUTES:SECONDS"}
@item @code{HOUR_MINUTE}   @tab Hours and minutes   @tab @code{"HOURS:MINUTES"}
@item @code{DAY_HOUR}      @tab Days and hours      @tab @code{"DAYS HOURS"}
@item @code{YEAR_MONTH}    @tab Years and months    @tab @code{"YEARS-MONTHS"}
@item @code{HOUR_SECOND}   @tab Hours, minutes,     @tab @code{"HOURS:MINUTES:SECONDS"}
@item @code{DAY_MINUTE}    @tab Days, hours, minutes @tab @code{"DAYS HOURS:MINUTES"}
@item @code{DAY_SECOND}    @tab Days, hours, minutes, seconds @tab @code{"DAYS HOURS:MINUTES:SECONDS"}
@end multitable

@strong{MySQL} allows any non-numeric delimiter in the @code{expr} format.
The ones shown in the table are the suggested delimiters.  If the @code{date}
argument is a @code{DATE} value and your calculations involve only
@code{YEAR}, @code{MONTH} and @code{DAY} parts (that is, no time parts), the
result is a @code{DATE} value.  Otherwise the result is a @code{DATETIME}
value.

@example
mysql> select DATE_ADD("1997-12-31 23:59:59",
                       INTERVAL 1 SECOND);
        -> 1998-01-01 00:00:00
mysql> select DATE_ADD("1997-12-31 23:59:59",
                       INTERVAL 1 DAY);
        -> 1998-01-01 23:59:59
mysql> select DATE_ADD("1997-12-31 23:59:59",
                       INTERVAL "1:1" MINUTE_SECOND);
        -> 1998-01-01 00:01:00
mysql> select DATE_SUB("1998-01-01 00:00:00",
                       INTERVAL "1 1:1:1" DAY_SECOND);
        -> 1997-12-30 22:58:59
mysql> select DATE_ADD("1998-01-01 00:00:00",
                       INTERVAL "-1 10" DAY_HOUR);
        -> 1997-12-30 14:00:00
mysql> select DATE_SUB("1998-01-02", INTERVAL 31 DAY);
        -> 1997-12-02
@end example

If you specify an interval value that is too short (does not include all the
interval parts that would be expected from the @code{type} keyword),
@strong{MySQL} assumes you have left out the leftmost parts of the interval
value.  For example, if you specify a @code{type} of @code{DAY_SECOND}, the
value of @code{expr} is expected to have days, hours, minutes and seconds
parts.  If you specify a value like @code{"1:10"}, @strong{MySQL} assumes
that the days and hours parts are missing and the value represents minutes
and seconds.  In other words, @code{"1:10" DAY_SECOND} is interpreted in such
a way that it is equivalent to @code{"1:10" MINUTE_SECOND}.  This is
analogous to the way that @strong{MySQL} interprets @code{TIME} values
as representing elapsed time rather than as time of day.

If you use incorrect dates, the result is @code{NULL}. If you add
@code{MONTH}, @code{YEAR_MONTH} or @code{YEAR} and the resulting date
has a day that is larger than the maximum day for the new month, the day is
adjusted to the maximum days in the new month.

@example
mysql> select DATE_ADD('1998-01-30', Interval 1 month);
        -> 1998-02-28
@end example

Note from the preceding example that the word @code{INTERVAL} and the
@code{type} keyword are not case sensitive.

@findex TO_DAYS()
@item TO_DAYS(date)
Given a date @code{date}, returns a daynumber (the number of days since year
0).

@example
mysql> select TO_DAYS(950501);
        -> 728779
mysql> select TO_DAYS('1997-10-07');
        -> 729669
@end example

@code{TO_DAYS()} is not intended for use with values that precede the advent
of the Gregorian calendar (1582).

@findex FROM_DAYS()
@item FROM_DAYS(N)
Given a daynumber @code{N}, returns a @code{DATE} value.

@example
mysql> select FROM_DAYS(729669);
        -> '1997-10-07'
@end example

@code{FROM_DAYS()} is not intended for use with values that precede the
advent of the Gregorian calendar (1582).

@findex DATE_FORMAT()
@item DATE_FORMAT(date,format)
Formats the @code{date} value according to the @code{format} string. The
following specifiers may be used in the @code{format} string:
@multitable @columnfractions .1 .9
@item @code{%M} @tab Month name (@code{January}..@code{December})
@item @code{%W} @tab Weekday name (@code{Sunday}..@code{Saturday})
@item @code{%D} @tab Day of the month with english suffix (@code{1st}, @code{2nd}, @code{3rd}, etc.)
@item @code{%Y} @tab Year, numeric, 4 digits
@item @code{%y} @tab Year, numeric, 2 digits
@item @code{%a} @tab Abbreviated weekday name (@code{Sun}..@code{Sat})
@item @code{%d} @tab Day of the month, numeric (@code{00}..@code{31})
@item @code{%e} @tab Day of the month, numeric (@code{0}..@code{31})
@item @code{%m} @tab Month, numeric (@code{01}..@code{12})
@item @code{%c} @tab Month, numeric (@code{1}..@code{12})
@item @code{%b} @tab Abbreviated month name (@code{Jan}..@code{Dec})
@item @code{%j} @tab Day of year (@code{001}..@code{366})
@item @code{%H} @tab Hour (@code{00}..@code{23})
@item @code{%k} @tab Hour (@code{0}..@code{23})
@item @code{%h} @tab Hour (@code{01}..@code{12})
@item @code{%I} @tab Hour (@code{01}..@code{12})
@item @code{%l} @tab Hour (@code{1}..@code{12})
@item @code{%i} @tab Minutes, numeric (@code{00}..@code{59})
@item @code{%r} @tab Time, 12-hour (@code{hh:mm:ss [AP]M})
@item @code{%T} @tab Time, 24-hour (@code{hh:mm:ss})
@item @code{%S} @tab Seconds (@code{00}..@code{59})
@item @code{%s} @tab Seconds (@code{00}..@code{59})
@item @code{%p} @tab @code{AM} or @code{PM}
@item @code{%w} @tab Day of the week (@code{0}=Sunday..@code{6}=Saturday)
@item @code{%U} @tab Week (@code{0}..@code{52}), where Sunday is the first day of the week.
@item @code{%u} @tab Week (@code{0}..@code{52}), where Monday is the first day of the week.
@item @code{%%} @tab Use @code{%%} to produce a literal @samp{%}.
@end multitable

All other characters are just copied to the result without interpretation.

@example
mysql> select DATE_FORMAT('1997-10-04 22:23:00', '%W %M %Y');
        -> 'Saturday October 1997'
mysql> select DATE_FORMAT('1997-10-04 22:23:00', '%H:%i:%s');
        -> '22:23:00'
mysql> select DATE_FORMAT('1997-10-04 22:23:00',
                          '%D %y %a %d %m %b %j');
        -> '4th 97 Sat 04 10 Oct 277'
mysql> select DATE_FORMAT('1997-10-04 22:23:00',
                          '%H %k %I %r %T %S %w');
        -> '22 22 10 10:23:00 PM 22:23:00 00 6'
@end example

As of @strong{MySQL} 3.23, the @code{%} is required before a format specifier
characters.  In earlier versions of @strong{MySQL}, @code{%} was optional.

@findex TIME_FORMAT()
@item TIME_FORMAT(time,format)
This is used like the @code{DATE_FORMAT()} function above, but the
@code{format} string may contain only those format specifiers that handle
hours, minutes and seconds.  Other specifiers produce a @code{NULL} value or
@code{0}.

@findex CURDATE()
@findex CURRENT_DATE
@item CURDATE()
@itemx CURRENT_DATE
Returns today's date as a value in @code{'YYYY-MM-DD'} or @code{YYYYMMDD}
format, depending on whether the function is used in a string or numeric
context.

@example
mysql> select CURDATE();
        -> '1997-12-15'
mysql> select CURDATE() + 0;
        -> 19971215
@end example

@findex CURTIME()
@findex CURRENT_TIME
@item CURTIME()
@itemx CURRENT_TIME
Returns the current time as a value in @code{'HH:MM:SS'} or @code{HHMMSS}
format, depending on whether the function is used in a string or numeric
context.

@example
mysql> select CURTIME();
        -> '23:50:26'
mysql> select CURTIME() + 0;
        -> 235026
@end example

@findex NOW()
@findex SYSDATE()
@findex CURRENT_TIMESTAMP
@item NOW()
@itemx SYSDATE()
@itemx CURRENT_TIMESTAMP
Returns the current date and time as a value in @code{'YYYY-MM-DD HH:MM:SS'}
or @code{YYYYMMDDHHMMSS} format, depending on whether the function is used in
a string or numeric context.

@example
mysql> select NOW();
        -> '1997-12-15 23:50:26'
mysql> select NOW() + 0;
        -> 19971215235026
@end example

@findex UNIX_TIMESTAMP()
@item UNIX_TIMESTAMP()
@itemx UNIX_TIMESTAMP(date)
If called with no argument, returns a Unix timestamp (seconds since
@code{'1970-01-01 00:00:00'} GMT). If @code{UNIX_TIMESTAMP()} is called with
a @code{date} argument, it returns the value of the argument as seconds since
@code{'1970-01-01 00:00:00'} GMT.  @code{date} may be a @code{DATE} string,
a @code{DATETIME} string, a @code{TIMESTAMP}, or a number in the format
@code{YYMMDD} or @code{YYYYMMDD} in local time.

@example
mysql> select UNIX_TIMESTAMP();
        -> 882226357
mysql> select UNIX_TIMESTAMP('1997-10-04 22:23:00');
        -> 875996580
@end example

When @code{UNIX_TIMESTAMP} is used on a @code{TIMESTAMP} column, the function
will receive the value directly, with no implicit
``string-to-unix-timestamp'' conversion.

@findex FROM_UNIXTIME()
@item FROM_UNIXTIME(unix_timestamp)
Returns a representation of the @code{unix_timestamp} argument as a value in
@code{'YYYY-MM-DD HH:MM:SS'} or @code{YYYYMMDDHHMMSS} format, depending on
whether the function is used in a string or numeric context.

@example
mysql> select FROM_UNIXTIME(875996580);
        -> '1997-10-04 22:23:00'
mysql> select FROM_UNIXTIME(875996580) + 0;
        -> 19971004222300
@end example

@findex FROM_UNIXTIME()
@item FROM_UNIXTIME(unix_timestamp,format)
Returns a string representation of the Unix timestamp, formatted according to
the @code{format} string. @code{format} may contain the same specifiers as
those listed in the entry for the @code{DATE_FORMAT()} function.

@example
mysql> select FROM_UNIXTIME(UNIX_TIMESTAMP(),
                            '%Y %D %M %h:%i:%s %x');
        -> '1997 23rd December 03:43:30 x'
@end example

@findex SEC_TO_TIME()
@item SEC_TO_TIME(seconds)
Returns the @code{seconds} argument, converted to hours, minutes and seconds,
as a value in @code{'HH:MM:SS'} or @code{HHMMSS} format, depending on whether
the function is used in a string or numeric context.

@example
mysql> select SEC_TO_TIME(2378);
        -> '00:39:38'
mysql> select SEC_TO_TIME(2378) + 0;
        -> 3938
@end example

@findex TIME_TO_SEC()
@item TIME_TO_SEC(time)
Returns the @code{time} argument, converted to seconds.
@example
mysql> select TIME_TO_SEC('22:23:00');
        -> 80580
mysql> select TIME_TO_SEC('00:39:38');
        -> 2378
@end example
@end table

@findex Miscellaneous functions
@findex Functions, miscellaneous
@node Miscellaneous functions, Group by functions, Date and time functions, Functions
@subsection Miscellaneous functions

@table @code
@findex DATABASE()
@item DATABASE()
Returns the current database name.
@example
mysql> select DATABASE();
        -> 'test'
@end example

If there is no current database, @code{DATABASE()} returns the empty string.

@findex USER()
@findex SYSTEM_USER()
@findex SESSION_USER()
@item USER()
@itemx SYSTEM_USER()
@itemx SESSION_USER()
Returns the current @strong{MySQL} user name.
@example
mysql> select USER();
        -> 'davida@@localhost'
@end example

In MySQL 3.22.11 or later, this includes the client hostname as well as the
username.  You can extract just the username part like this:

@example
mysql> select left(USER(),instr(USER(),"@")-1);
        -> 'davida'
@end example

@findex PASSWORD()
@item PASSWORD(str)
Calculates a password string from the plaintext password @code{str}. This is
the function that is used for encrypting @strong{MySQL} passwords for storage
in the @code{Password} column of the @code{user} grant table.

@example
mysql> select PASSWORD('badpwd');
        -> '7f84554057dd964b'
@end example

@cindex Password encryption, reversibility of
@code{PASSWORD()} encryption is non-reversible.

@code{PASSWORD()} does not perform password encryption in the same way that
Unix passwords are encrypted.  You should not assume that if your Unix
password and your @strong{MySQL} password are the same, @code{PASSWORD()}
will result in the same encrypted value as is stored in the Unix password
file.  See @code{ENCRYPT()}.

@findex ENCRYPT()
@item ENCRYPT(str[,salt])
Encrypt @code{str} using the Unix @code{crypt()} system call. The
@code{salt} argument should be a string with 2 characters.

@example
mysql> select ENCRYPT("hello");
        -> 'VxuFAJXVARROc'
@end example

If @code{crypt()} is not available on your system, @code{ENCRYPT()} always
returns @code{NULL}.

@code{ENCRYPT()} ignores all but the first 8 characters of @code{str}, at
least on some systems.  This will be determined by the behavior of the
underlying @code{crypt()} system call.

@findex ENCODE()
@item ENCODE(str,pass_str)
Encrypt @code{str} using @code{pass_str} as the password.
To decrypt the result, use @code{DECODE()}.

The results is a binary string.  If you want to save it in a column,
use a @code{BLOB} column type.

@findex DECODE()
@item DECODE(crypt_str,pass_str)
Descrypts the encrypted string @code{crypt_str} using @code{pass_str} as the
password.  @code{crypt_str} should be a string returned from
@code{ENCODE()}.

@findex LAST_INSERT_ID([expr])
@item LAST_INSERT_ID([expr])
Returns the last automatically-generated value that was inserted into an
@code{AUTO_INCREMENT} column.
@xref{mysql_insert_id,, @code{mysql_insert_id()}}.

@example
mysql> select LAST_INSERT_ID();
        -> 195
@end example

The last ID that was generated is maintained in the server on a
per-connection basis.  It will not be changed by another client. It will not
even be changed if you update another @code{AUTO_INCREMENT} column with a
non-magic value (that is, a value that is not @code{NULL} and not @code{0}).

If @code{expr} is given as an argument to @code{LAST_INSERT_ID()} in an
@code{UPDATE} clause, then the value of the argument is returned as a
@code{LAST_INSERT_ID()} value.  This can be used to simulate sequences:

First create the table:

@example
mysql> create table sequence (id int not null);
mysql> insert into sequence values (0);
@end example

Then the table can be used to generate sequence numbers like this:

@example
mysql> update sequence set id=LAST_INSERT_ID(id+1);
@end example

You can generate sequences without calling @code{LAST_INSERT_ID()}, but the
utility of using the function this way is that the ID value is maintained in
the server as the last automatically-generated value.  You can retrieve the
new ID as you would read any normal @code{AUTO_INCREMENT} value in
@strong{MySQL}.  For example, @code{LAST_INSERT_ID()} (without an argument)
will return the new ID.  The C API function @code{mysql_insert_id()}
can also be used to get the value.

@findex FORMAT()
@item FORMAT(X,D)
Formats the number @code{X} to a format like @code{'#,###,###.##'} with
@code{D} decimals.  If @code{D} is @code{0}, the result will have no
decimal point or fractional part.

@example
mysql> select FORMAT(12332.1234, 2);
        -> '12,332.12'
mysql> select FORMAT(12332.1,4);
        -> '12,332.1000'
mysql> select FORMAT(12332.2,0);
        -> '12,332'
@end example

@findex VERSION()
@item VERSION()
Returns a string indicating the @strong{MySQL} server version.
@example
mysql> select VERSION();
        -> '3.22.19b-log'
@end example

@findex GET_LOCK()
@item GET_LOCK(str,timeout)
Tries to obtain a lock with a name given by the string @code{str}, with a
timeout of @code{timeout} seconds.  Returns @code{1} if the lock was obtained
successfully, @code{0} if the attempt timed out, or @code{NULL} if an error
occurred (such as running out of memory or the thread was killed with
@code{mysqladmin kill}).  A lock is released when you execute
@code{RELEASE_LOCK()}, execute a new @code{GET_LOCK()} or the thread
terminates.  This function can be used to implement application locks or to
simulate record locks.

@example
mysql> select GET_LOCK("lock1",10);
        -> 1
mysql> select GET_LOCK("lock2",10);
        -> 1
mysql> select RELEASE_LOCK("lock2");
        -> 1
mysql> select RELEASE_LOCK("lock1");
        -> NULL
@end example

Note that the second @code{RELEASE_LOCK()} call returns @code{NULL} because
the lock @code{"lock1"} was automatically released by the second
@code{GET_LOCK()} call.

@findex RELEASE_LOCK()
@item RELEASE_LOCK(str)
Releases the lock named by the string @code{str} that was obtained with
@code{GET_LOCK()}. Returns @code{1} if the lock was released, @code{0} if the
lock wasn't locked by this thread (in which case the lock is not released)
and @code{NULL} if the named lock didn't exist.  The lock will not exist if
it was never obtained by a call to @code{GET_LOCK()} or if it already has
been released.

@findex BENCHMARK()
@item BENCHMARK(count,expr)
The @code{BENCHMARK()} function executes the expression @code{expr}
repeatedly @code{count} times.  It may be used to time how fast @strong{MySQL}
processes the expression.  The result value is always @code{0}.  The intended
use is in the @code{mysql} client, which reports query execution times.

@example
mysql> select BENCHMARK(1000000,encode("hello","goodbye"));
+----------------------------------------------+
| BENCHMARK(1000000,encode("hello","goodbye")) |
+----------------------------------------------+
|                                            0 |
+----------------------------------------------+
1 row in set (4.74 sec)
@end example
@end table

The time reported is elapsed time on the client end, not CPU time on the
server end.  It may be advisable to execute @code{BENCHMARK()} several
times, and interpret the result with regard to how heavily loaded the
server machine is.

@findex GROUP BY functions
@findex Functions, GROUP BY
@node Group by functions,  , Miscellaneous functions, Functions
@subsection Functions for use with @code{GROUP BY} clauses

If you use a group function in a statement containing no @code{GROUP BY}
clause, it is equivalent to grouping on all rows.

@table @code
@findex COUNT()
@item COUNT(expr)
Returns a count of the number of non-@code{NULL} rows retrieved by a
@code{SELECT} statement.

@example
mysql> select student.student_name,COUNT(*)
           from student,course
           where student.student_id=course.student_id
           GROUP BY student_name;

@end example

@code{COUNT(*)} is optimized to
return very quickly if the @code{SELECT} retrieves from one table, no
other columns are retrieved and there is no @code{WHERE} clause.
For example:

@example
mysql> select COUNT(*) from student;
@end example

@findex AVG()
@item AVG(expr)
Returns the average value of @code{expr}.

@example
mysql> select student_name, AVG(test_score)
           from student
           GROUP BY student_name;
@end example

@findex MIN()
@findex MAX()
@item MIN(expr)
@itemx MAX(expr)
Returns the minimum or maximum value of @code{expr}.  @code{MIN()} and
@code{MAX()} may take a string argument; in such cases they return the
minimum or maximum string value.

@example
mysql> select student_name, MIN(test_score), MAX(test_score)
           from student
           GROUP BY student_name;
@end example

@findex SUM()
@item SUM(expr)
Returns the sum of @code{expr}.

@findex STD()
@findex STDDEV()
@cindex Oracle compatibility
@cindex Compatibility, with Oracle
@item STD(expr)
@itemx STDDEV(expr)
Returns the standard deviation of @code{expr}. This is an extension to
ANSI SQL.
The @code{STDDEV()} form of this function is provided for Oracle compatability.

@findex BIT_OR()
@item BIT_OR(expr)
Returns the bitwise @code{OR} of all bits in @code{expr}. The calculation is
performed with 64-bit (@code{BIGINT} precision.

@findex BIT_AND()
@item BIT_AND(expr)
Returns the bitwise @code{AND} of all bits in @code{expr}. The calculation is
performed with 64-bit (@code{BIGINT} precision.
@end table

@strong{MySQL} has extended the use of @code{GROUP BY}. You can use columns or
calculations in the @code{SELECT} expressions which don't appear in
the @code{GROUP BY} part. This stands for @emph{any possible value for this
group}.  You can use this to get better performance by avoiding sorting and
grouping on unnecessary items.  For example, you don't need to group on
@code{customer.name} in the following query:

@example
mysql> select order.custid,customer.name,max(payments)
       from order,customer
       where order.custid = customer.custid
       GROUP BY order.custid;
@end example

In ANSI SQL, you would have to add @code{customer.name} to the @code{GROUP
BY} clause.  In @strong{MySQL}, the name is redundant.

Don't use this feature if the columns you omit from the @code{GROUP BY} part
aren't unique in the group!

In some cases, you can use @code{MIN()} and @code{MAX()} to obtain a specific
column value even if it isn't unique. The following gives the value of
@code{column} from the row containing the smallest value in the @code{sort}
column:

@example
substr(MIN(concat(sort,space(6-length(sort)),column),7,length(column)))
@end example

@cindex @code{ORDER BY}, aliases in
@cindex Aliases, in @code{ORDER BY} clauses
@cindex @code{GROUP BY}, aliases in
@cindex Aliases, in @code{GROUP BY} clauses
@cindex Expressions, aliases for
@cindex Aliases, for expressions
Note that you can't yet use expressions in @code{GROUP BY} or
@code{ORDER BY} clauses.  You can work around this limitation by using
an alias for the expression:

@example
mysql> select id,floor(value/100) as val from tbl_name
           GROUP BY id,val ORDER BY val;
@end example

@findex CREATE DATABASE
@node CREATE DATABASE, DROP DATABASE, Functions, Reference
@section @code{CREATE DATABASE} syntax

@example
CREATE DATABASE db_name
@end example

@code{CREATE DATABASE} creates a database with the given name.  Rules for
allowable database names are given in @ref{Legal names}.  An error occurs if
the database already exists.

Databases in @strong{MySQL} are implemented as directories containing files
that correspond to tables in the database.  Since there are no tables in a
database when it is initially created, the @code{CREATE DATABASE} statement
only creates a directory under the @strong{MySQL} data directory.

@cindex @code{mysqladmin}
You can also create databases with @code{mysqladmin}.
@xref{Programs}.

@findex DROP DATABASE
@node DROP DATABASE, CREATE TABLE, CREATE DATABASE, Reference
@section @code{DROP DATABASE} syntax

@example
DROP DATABASE [IF EXISTS] db_name
@end example

@code{DROP DATABASE} drops all tables in the database and deletes the
database.  @strong{Be VERY careful with this command!}

@code{DROP DATABASE} returns the number of files that were removed from the
database directory.  Normally, this is three times the number of tables,
since each table corresponds to a @file{.ISD} file, a @file{.ISM} file and a
@file{.frm} file.

In @strong{MySQL} 3.22 or later, you can use the keywords @code{IF EXISTS} to
prevent an error from occurring if the database doesn't exist.

@cindex @code{mysqladmin}
You can also drop databases with @code{mysqladmin}.
@xref{Programs}.

@findex CREATE TABLE
@node CREATE TABLE, ALTER TABLE, DROP DATABASE, Reference
@section @code{CREATE TABLE} syntax

@menu
* Silent column changes::       Silent column changes
@end menu

@example
CREATE TABLE [IF NOT EXISTS] tbl_name (create_definition,...) [table_options] [select_statement]

create_definition:
  col_name type [NOT NULL | NULL] [DEFAULT default_value] [AUTO_INCREMENT]
            [PRIMARY KEY] [reference_definition]
  or    PRIMARY KEY (index_col_name,...)
  or    KEY [index_name] KEY(index_col_name,...)
  or    INDEX [index_name] (index_col_name,...)
  or    UNIQUE [INDEX] [index_name] (index_col_name,...)
  or    [CONSTRAINT symbol] FOREIGN KEY index_name (index_col_name,...)
            [reference_definition]
  or    CHECK (expr)

type:
        TINYINT[(length)] [UNSIGNED] [ZEROFILL]
  or    SMALLINT[(length)] [UNSIGNED] [ZEROFILL]
  or    MEDIUMINT[(length)] [UNSIGNED] [ZEROFILL]
  or    INT[(length)] [UNSIGNED] [ZEROFILL]
  or    INTEGER[(length)] [UNSIGNED] [ZEROFILL]
  or    BIGINT[(length)] [UNSIGNED] [ZEROFILL]
  or    REAL[(length,decimals)] [UNSIGNED] [ZEROFILL]
  or    DOUBLE[(length,decimals)] [UNSIGNED] [ZEROFILL]
  or    FLOAT[(length,decimals)] [UNSIGNED] [ZEROFILL]
  or    DECIMAL(length,decimals) [UNSIGNED] [ZEROFILL]
  or    NUMERIC(length,decimals) [UNSIGNED] [ZEROFILL]
  or    CHAR(length) [BINARY]
  or    VARCHAR(length) [BINARY]
  or    DATE
  or    TIME
  or    TIMESTAMP
  or    DATETIME
  or    TINYBLOB
  or    BLOB
  or    MEDIUMBLOB
  or    LONGBLOB
  or    TINYTEXT
  or    TEXT
  or    MEDIUMTEXT
  or    LONGTEXT
  or    ENUM(value1,value2,value3,...)
  or    SET(value1,value2,value3,...)

index_col_name:
        col_name [(length)]

reference_definition:
        REFERENCES tbl_name [(index_col_name,...)]
                   [MATCH FULL | MATCH PARTIAL]
                   [ON DELETE reference_option]
                   [ON UPDATE reference_option]

reference_option:
        RESTRICT | CASCADE | SET NULL | NO ACTION | SET DEFAULT

table_options:
	type = [ISAM | MYISAM | HEAP]
or	max_rows = #
or	min_rows = #
or	avg_row_length = #
or	comment = "string"
or	auto_increment = #

select_statement:
	[ | IGNORE | REPLACE] SELECT ...  (Some legal select statement)
@end example

@code{CREATE TABLE}
creates a table with the given name in the current database.  Rules for
allowable table names are given in @ref{Legal names}.  An error occurs if
there is no current database or if the table already exists.

In @strong{MySQL} 3.22 or later, the table name can be specified as
@code{db_name.tbl_name}.  This works whether or not there is a current
database.

In @strong{MySQL} 3.23 or later, you can use the keywords @code{IF NOT EXISTS}
so that an error does not occur if the table already exits.  Note that there
is no verification that the table structures are identical.

Each table @code{tbl_name} is represented by three files in the database
directory:

@multitable @columnfractions .2 .8
@item @strong{File} @tab @strong{Purpose}
@item @code{tbl_name.frm} @tab Table definition (form) file
@item @code{tbl_name.ISD} @tab Data file
@item @code{tbl_name.ISM} @tab Index file
@end multitable

For more information on the properties of the various column types, see
@ref{Column types}.

@itemize @bullet
@item
If neither @code{NULL} nor @code{NOT NULL} is specified, the column
is treated as though @code{NULL} had been specified.

@item
@cindex @code{NULL} values, and @code{BLOB} and @code{TEXT} columns
@cindex @code{BLOB} columns, and @code{NULL} values
@cindex @code{TEXT} columns, and @code{NULL} values
@code{BLOB} and @code{TEXT} columns are always @code{NULL} columns, even if
you specify @code{NOT NULL} in the column specification.

@item
An integer column may have the additional attribute @code{AUTO_INCREMENT}.
When you insert a value of @code{NULL} (recommended) or @code{0} into an
@code{AUTO_INCREMENT} column, the column is set to @code{value+1}, where
@code{value} is the largest value for the column currently in the table.
@code{AUTO_INCREMENT} sequences begin with @code{1}.
@xref{mysql_insert_id, , @code{mysql_insert_id()}}.

If you delete the row containing the maximum value for an @code{AUTO_INCREMENT}
column, the value will be reused.  If you delete all rows in the table, the
sequence starts over.

@strong{Note:} There can be only one @code{AUTO_INCREMENT} column per table,
and it must be indexed.

@cindex ODBC compatibility
@cindex Compatibility, with ODBC
To make @strong{MySQL} compatible with some ODBC applications, you can find
the last inserted row with the following query:

@example
SELECT * FROM tbl_name WHERE auto_col IS NULL
@end example

@item
@code{NULL} values are handled differently for @code{TIMESTAMP} columns than
for other column types.  You cannot store a literal @code{NULL} in a
@code{TIMESTAMP} column; setting the column to @code{NULL} sets it to the
current date and time.  Because @code{TIMESTAMP} columns behave this way, the
@code{NULL} and @code{NOT NULL} attributes do not apply in the normal way and
are ignored if you specify them.

On the other hand, to make it easier for @strong{MySQL} clients to use
@code{TIMESTAMP} columns, the server reports that such columns may be
assigned @code{NULL} values (which is true), even though @code{TIMESTAMP}
never actually will contain a @code{NULL} value.  You can see this when you
use @code{DESCRIBE tbl_name} to get a description of your table.

Note that setting a @code{TIMESTAMP} column to @code{0} is not the same
as setting it to @code{NULL}, because @code{0} is a valid @code{TIMESTAMP}
value.

@item
If no @code{DEFAULT} value is specified for a column, @strong{MySQL}
automatically assigns one.

If the column may take @code{NULL} as a value, the default value is
@code{NULL}.

If the column is declared as @code{NOT NULL}, the default value depends on
the column type:

@itemize @minus
@item
For numeric types other than those declared with the @code{AUTO_INCREMENT}
attribute, the default is @code{0}.  For an @code{AUTO_INCREMENT} column, the
default value is the next value in the sequence.

@item
For date and time types other than @code{TIMESTAMP}, the default is the
appropriate ``zero'' value for the type.  For the first @code{TIMESTAMP}
column in a table, the default value is the current date and time.
@xref{Date and time types}.

@item
For string types other than @code{ENUM}, the default is the empty string.
For @code{ENUM}, the default is the first enumeration value.
@end itemize

@item
@code{KEY} is a synonym for @code{INDEX}.

@item
In @strong{MySQL}, a @code{UNIQUE} key can have only distinct values. An
error occurs if you try to add a new row with a key that matches an existing
row.

@item
In @strong{MySQL} a @code{PRIMARY KEY} is the same thing as a unique @code{KEY}
that is named @code{PRIMARY}   A table can have only one @code{PRIMARY KEY}.
If you don't have a @code{PRIMARY KEY} and some applications ask for the
@code{PRIMARY KEY} in your tables, @strong{MySQL} will return the first
@code{UNIQUE} key as the @code{PRIMARY KEY}.

@item
A @code{PRIMARY KEY} can be a multiple-column index.  However, you cannot
create a multiple-column index using the @code{PRIMARY KEY} key attibute in a
column specification.  Doing so will mark only that single column as primary.
You must use the @code{PRIMARY KEY(index_col_name, ...)} syntax.

@item
If you don't assign a name to an index, the index will be assigned the same
name as the first @code{index_col_name}, with an optional suffix (@code{_2},
@code{_3}, @code{...}) to make it unique.  You can see index names for a
table using @code{SHOW INDEX FROM tbl_name}.
@xref{SHOW, , @code{SHOW}}.

@item
@cindex @code{NULL} values, and indexes
@cindex Indexes, and @code{NULL} values
Columns that are indexed cannot have @code{NULL} values.  You must declare
such columns @code{NOT NULL} or an error results.

@item
@cindex @code{BLOB} columns, indexing
@cindex Indexes, and @code{BLOB} columns
@cindex @code{TEXT} columns, indexing
@cindex Indexes, and @code{TEXT} columns
@code{BLOB} and @code{TEXT} columns cannot be indexed.

@item
With @code{col_name(length)} syntax, you can specify an index which
uses only a part of a @code{CHAR} or @code{VARCHAR} column. This can
make the index file much smaller.
@xref{Indexes}.

@item
When you use @code{ORDER BY} or @code{GROUP BY} with a @code{TEXT} or
@code{BLOB} column, only the first @code{max_sort_length} bytes are used.
@xref{BLOB,  , @code{BLOB}}.

@item
The @code{FOREIGN KEY}, @code{CHECK} and @code{REFERENCES} clauses don't
actually do anything.  The syntax for them is provided only for compatibility,
to make it easier to port code from other SQL servers and to run applications
that create tables with references.
@xref{Missing functions}.

@item
Each @code{NULL} column takes one bit extra, rounded up to the nearest byte.

@item
The maximum record length in bytes can be calculated as follows:

@example
row length = 1
             + (sum of column lengths)
             + (number of NULL columns + 7)/8
             + (number of variable-length columns)
@end example

@item
The @code{table_options} and @code{SELECT} options is only implemented in
@strong{MySQL} 3.23 and above..

The different table types are:

@multitable @columnfractions .20 .80
@item ISAM @tab The original table handler
@item MYISAM @tab The new binary portable table handler
@item HEAP @tab The data for this table is only stored in memory
@end multitable
@xref{Table types}

The different table options are used to optimize the behavior of the
table. In most cases, you don't have to specify these:

@multitable @columnfractions .20 .80
@item max_rows @tab Max number of rows you plan to store in the table.
@item min_rows @tab Minimum number of rows you plan to store in the table.
@item avg_row_length @tab An approximation of the average row length for your table.
@item comment $tab A 60 character comment for your table
@item auto_increment @tab The next auto_increment value you want to set for your table.
@end multitable

When you use a @code{MYISAM} table, @strong{MySQL} uses the product of
@code{max_rows * avg_row_length} to decide how big the resulting table
will be.  If you don't specify any of the above options, the maximum size
for a table will be 4G (or 2G if your operating systems only supports 2G
tables).

@item
If you specify a @code{SELECT} after the @code{CREATE STATEMENT}, @strong{MySQL} will
create new fields for all elements in the @code{SELECT}.  For example:

@example
mysql> CREATE TABLE test (a int not null auto_increment, primary key (a), key(b))
TYPE=HEAP SELECT b,c from test2;
@end example

This will create a @code{HEAP} table with 3 columns.  Note that the table will
automatically be deleted if any errors occur while copying data
into the table.
@end itemize


@node Silent column changes,  , CREATE TABLE, CREATE TABLE
@subsection Silent column specification changes

In some cases, @strong{MySQL} silently changes a column specification from
that given in a @code{CREATE TABLE} statement.  (This may also occur with
@code{ALTER TABLE}.)

@itemize @bullet
@item
@code{VARCHAR} columns with a length less than four are changed to
@code{CHAR}.

@item
If any column in a table has a variable length, the entire row is
variable-length as a result.  Therefore, if a table contains any
variable-length columns (@code{VARCHAR}, @code{TEXT} or @code{BLOB}), all
@code{CHAR} columns longer than three characters are changed to
@code{VARCHAR} columnss.  This doesn't affect how you use the columns in any
way; in @strong{MySQL}, @code{VARCHAR} is just a different way to store
characters.  @strong{MySQL} performs this conversion because it saves space
and makes table operations faster.
@xref{Row format}.

@item
@code{TIMESTAMP} display sizes must be even and in the range from 2 to 14.
If you specify a display size of 0 or greater than 14, the size is coerced
to 14.  Odd-valued sizes in the range from 1 to 13 are coerced
to the next higher even number.

@item
You cannot store a literal @code{NULL} in a @code{TIMESTAMP} column; setting
it to @code{NULL} sets it to the current date and time.  Because
@code{TIMESTAMP} columns behave this way, the @code{NULL} and @code{NOT NULL}
attributes do not apply in the normal way and are ignored if you specify
them.  @code{DESCRIBE tbl_name} always reports that a @code{TIMESTAMP}
column may be assigned @code{NULL} values.

@item
@cindex @code{NULL} values, and @code{BLOB} and @code{TEXT} columns
@cindex @code{BLOB} columns, and @code{NULL} values
@cindex @code{TEXT} columns, and @code{NULL} values
@code{BLOB} and @code{TEXT} columns are always @code{NULL} columns, even if
you specify @code{NOT NULL} in the column specification.

@item
@strong{MySQL} maps certain column types used by other SQL database vendors
to @strong{MySQL} types.  @xref{Other-vendor column types}.
@end itemize

If you want to see whether or not @strong{MySQL} used a column type other
than the one you specified, issue a @code{DESCRIBE tbl_name} statement after
creating or altering your table.

@cindex @code{pack_isam}
Certain other column type changes may occur if you compress a table using
@code{pack_isam}.
@xref{Row format}.

@findex ALTER TABLE
@node ALTER TABLE, OPTIMIZE TABLE, CREATE TABLE, Reference
@section @code{ALTER TABLE} syntax

@example
ALTER [IGNORE] TABLE tbl_name alter_spec [, alter_spec ...]

alter_specification:
        ADD [COLUMN] create_definition [FIRST | AFTER column_name ]
  or    ADD INDEX [index_name] (index_col_name,...)
  or    ADD PRIMARY KEY (index_col_name,...)
  or    ADD UNIQUE [index_name] (index_col_name,...)
  or    ALTER [COLUMN] col_name @{SET DEFAULT literal | DROP DEFAULT@}
  or    CHANGE [COLUMN] old_col_name create_definition
  or    MODIFY [COLUMN] create_definition
  or    DROP [COLUMN] col_name
  or    DROP PRIMARY KEY
  or    DROP INDEX key_name
  or    RENAME [AS] new_tbl_name
  or    table_option
@end example

@code{ALTER TABLE} allows you to change the structure of an existing table.
For example, you can add or delete columns, create or destroy indexes, change
the type of existing columns, or rename columns or the table itself.  You can
also change the comment for the table and type of the table.
@xref{CREATE TABLE, , @code{CREATE TABLE}}.


If you use @code{ALTER TABLE} to change a column specification but
@code{DESCRIBE tbl_name} indicates that your column was not changed, it is
possible that @strong{MySQL} ignored your modification for one of the reasons
described in @ref{Silent column changes}.  For example, if you try to change
a @code{VARCHAR} column to @code{CHAR}, @strong{MySQL} will still use
@code{VARCHAR} if the table contains other variable-length columns.

@code{ALTER TABLE} works by making a temporary copy of the original table.
The alteration is performed on the copy, then the original table is
deleted and the new one is renamed. This is done in such a way that
all updates are automatically redirected to the new table without
any failed updates. While @code{ALTER TABLE} is executing, the original
table is readable by other clients. Updates and writes to the table
are stalled until the new table is ready.

@itemize @bullet
@item
To use @code{ALTER TABLE}, you need @strong{select}, @strong{insert},
@strong{delete}, @strong{update}, @strong{create} and @strong{drop}
privileges on the table.

@item
@code{IGNORE} is a @strong{MySQL} extension to ANSI SQL92.
It controls how @code{ALTER TABLE} works if there are duplicates on
unique keys in the new table.
If @code{IGNORE} isn't specified, the copy is aborted and rolled back.
If @code{IGNORE} is specified, then for rows with duplicates on a unique
key, only the first row is used; the others are deleted.

@item
You can issue multiple @code{ADD}, @code{ALTER}, @code{DROP} and
@code{CHANGE} clauses in a single @code{ALTER TABLE} statement. This is a
@strong{MySQL} extension to ANSI SQL92, which allows only one of each clause
per @code{ALTER TABLE} statement.

@item
@code{CHANGE col_name}, @code{DROP col_name} and @code{DROP
INDEX} are @strong{MySQL} extensions to ANSI SQL92.

@item
@code{MODIFY} is an Oracle extension to @code{ALTER TABLE}.

@item
The optional word @code{COLUMN} is a pure noise word and can be omitted.

@item
If you use @code{ALTER TABLE tbl_name RENAME AS new_name} without any other
options, @strong{MySQL} simply renames the files that correspond to the table
@code{tbl_name}.  There is no need to create the temporary table.

@item
@code{create_definition} clauses use the same syntax for @code{ADD} and
@code{CHANGE} as for @code{CREATE TABLE}.  Note that this syntax includes
the column name, not just the column type.
@xref{CREATE TABLE, , @code{CREATE TABLE}}.

@item
You can rename a column using a @code{CHANGE old_col_name create_definition}
clause.  To do so, specify the old and new column names and the type that
the column currently has.  For example, to rename an @code{INTEGER} column
from @code{a} to @code{b}, you can do this:

@example
mysql> ALTER TABLE t1 CHANGE a b INTEGER;
@end example

If you want to change a column's type but not the name, @code{CHANGE}
syntax still requires two column names even if they are the same.  For
example:

@example
mysql> ALTER TABLE t1 CHANGE b b BIGINT NOT NULL;
@end example

However, as of @strong{MySQL} 3.22.16a, you can also use @code{MODIFY} to
change a column's type without renaming it:

@example
mysql> ALTER TABLE t1 MODIFY b BIGINT NOT NULL;
@end example

@item
If you use @code{CHANGE} or @code{MODIFY} to shorten a column for which
an index exists on part of the column (for instance, if you have an index
on the first 10 characters of a @code{VARCHAR} column), you cannot make
the column shorter than the number of characters that are indexed.

@item
When you change a column type using @code{CHANGE} or @code{MODIFY},
@strong{MySQL} tries to convert data to the new type as well as possible.

@item
In @strong{MySQL} 3.22 or later, you can use @code{FIRST} or @code{ADD ...
AFTER col_name} to add a column at a specific position within a table row.
The default is to add the column last.

@item
@code{ALTER COLUMN} specifies a new default value for a column
or removes the old default value.
If the old default is removed and the column can be @code{NULL}, the new
default is @code{NULL}. If the column cannot be @code{NULL}, @strong{MySQL}
assigns a default value.
Default value assignment is described in
@ref{CREATE TABLE, , @code{CREATE TABLE}}.

@item
@code{DROP INDEX} removes an index. This is a @strong{MySQL} extension to
ANSI SQL92.

@item
If columns are dropped from a table, the columns are also removed from any
index of which they are a part.  If all columns that make up an index are
dropped, the index is dropped as well.

@item
@code{DROP PRIMARY KEY} drops the primary index. If no such
index exists, it drops the first @code{UNIQUE} index in the table.
(@strong{MySQL} marks the first @code{UNIQUE} key as the @code{PRIMARY KEY}
if no @code{PRIMARY KEY} was specified explicitly.)

@item
@findex mysql_info()
With the C API function @code{mysql_info()}, you can find out how many
records were copied, and (when @code{IGNORE} is used) how many records were
deleted due to duplication of unique key values.

@item
@cindex Foreign keys
@cindex References
The @code{FOREIGN KEY}, @code{CHECK} and @code{REFERENCES} clauses don't
actually do anything.  The syntax for them is provided only for compatibility,
to make it easier to port code from other SQL servers and to run applications
that create tables with references.
@xref{Missing functions}.
@end itemize

Here is an example that shows some of the uses of @code{ALTER TABLE}.  We
begin with a table @code{t1} that is created as shown below:

@example
mysql> CREATE TABLE t1 (a INTEGER,b CHAR(10));
@end example

To rename the table from @code{t1} to @code{t2}:

@example
mysql> ALTER TABLE t1 RENAME t2;
@end example

To change column @code{a} from @code{INTEGER} to @code{TINYINT NOT NULL}
(leaving the name the same), and to change column @code{b} from
@code{CHAR(10)} to @code{CHAR(20)} as well as renaming it from @code{b} to
@code{c}:

@example
mysql> ALTER TABLE t2 MODIFY a TINYINT NOT NULL, CHANGE b c CHAR(20);
@end example

To add a new @code{TIMESTAMP} column named @code{d}:

@example
mysql> ALTER TABLE t2 ADD d TIMESTAMP;
@end example

To add an index on column @code{d}, and make column @code{a} the primary key:

@example
mysql> ALTER TABLE t2 ADD INDEX (d), ADD PRIMARY KEY (a);
@end example

To remove column @code{c}:

@example
mysql> ALTER TABLE t2 DROP COLUMN c;
@end example

To add a new @code{AUTO_INCREMENT} integer column named @code{c}:

@example
mysql> ALTER TABLE t2 ADD c INT UNSIGNED NOT NULL AUTO_INCREMENT,
           ADD INDEX (c);
@end example

Note that we indexed @code{c}, because @code{AUTO_INCREMENT} columns must be
indexed, and also that we declare @code{c} as @code{NOT NULL}, because
indexed columns cannot be @code{NULL}.

@findex OPTIMIZE TABLE
@node OPTIMIZE TABLE, DROP TABLE, ALTER TABLE, Reference
@section @code{OPTIMIZE TABLE} syntax

@example
OPTIMIZE TABLE tbl_name
@end example

@code{OPTIMZE TABLE} should be used if you have deleted a large part of a
table or if you have made many changes to a table with variable-length rows
(tables that have @code{VARCHAR}, @code{BLOB} or @code{TEXT} columns).
Deleted records are maintained in a linked list and subsequent @code{INSERT}
operations reuse old record positions. You can use @code{OPTIMIZE TABLE} to
reclaim the unused space.

@code{OPTIMIZE TABLE} works by making a temporary copy of the original
table.  The old table is copied to the new table (without the unused rows),
then the original table is deleted and the new one is renamed. This is done
in such a way that all updates are automatically redirected to the new table
without any failed updates. While @code{OPTIMIZE TABLE} is executing, the
original table is readable by other clients. Updates and writes to the table
are stalled until the new table is ready.

@findex DROP TABLE
@node DROP TABLE, DELETE, OPTIMIZE TABLE, Reference
@section @code{DROP TABLE} syntax

@example
DROP TABLE [IF EXISTS] tbl_name [, tbl_name,...]
@end example

@code{DROP TABLE} removes one or more tables. All table data and the table
definition are @emph{removed}, so @strong{be careful} with this command!

In @strong{MySQL} 3.22 or later, you can use the keywords @code{IF EXISTS} to
prevent an error from occurring for tables that don't exist.

@findex DELETE
@node DELETE, SELECT, DROP TABLE, Reference
@section @code{DELETE} syntax

@example
DELETE [LOW_PRIORITY] FROM tbl_name
    [WHERE where_definition] [LIMIT rows]
@end example

@code{DELETE} deletes rows from @code{tbl_name} that satisfy the condition
given by @code{where_definition}, and returns the number of records deleted.

If you issue a @code{DELETE} with no @code{WHERE} clause, all rows are
deleted.  @strong{MySQL} does this by recreating the table as an empty table,
which is much faster than deleting each row.  In this case, @code{DELETE}
returns zero as the number of affected records. (@strong{MySQL} can't return
the number of rows that were actually deleted, since the recreate is done
without opening the data files. As long as the table definition file
@file{tbl_name.frm} is valid, the table can be recreated this way, even if
the data or index files have become corrupted.).

If you really want to know how many records are deleted when you are deleting
all rows, and are willing to suffer a speed penalty, you can use a
@code{DELETE} statement of this form:

@example
mysql> DELETE FROM tbl_name WHERE 1>0;
@end example

Note that this is MUCH slower than @code{DELETE FROM tbl_name} with no
@code{WHERE} clause, because it deletes rows one at a time.

If you specify the keyword @code{LOW_PRIORITY}, execution of the
@code{DELETE} is delayed until no other clients are reading from the table.

Deleted records are maintained in a linked list and subsequent @code{INSERT}
operations reuse old record positions. To reclaim unused space and reduce
file sizes, use the @code{OPTIMIZE TABLE} statement or the @code{isamchk}
utility to reorganize tables.  @code{OPTIMIZE TABLE} is easier, but
@code{isamchk} is faster.
@xref{OPTIMIZE TABLE, , @code{OPTIMIZE TABLE}}, and
@ref{Optimization}.

The @strong{MySQL}-specific @code{LIMIT rows} option to @code{DELETE} tells
the server the maximum number of rows to be deleted before control is
returned to the client.  This can be used to ensure that a specific
@code{DELETE} command doesn't take too much time.  You can simply repeat
the @code{DELETE} command until the number of affected rows is less than
the @code{LIMIT} value.

@findex SELECT
@node SELECT, JOIN, DELETE, Reference
@section @code{SELECT} syntax

@example
SELECT [STRAIGHT_JOIN] [SQL_SMALL_RESULT] [DISTINCT | ALL]
    select_expression,...
    [INTO OUTFILE 'file_name' export_options]
    [FROM table_references
        [WHERE where_definition]
        [GROUP BY col_name,...]
        [HAVING where_definition]
        [ORDER BY @{unsigned_integer | col_name@} [ASC | DESC] ,...]
        [LIMIT [offset,] rows]
        [PROCEDURE procedure_name] ]
@end example

@code{SELECT} is used to retrieve rows selected from one or more tables.
@code{select_expression} indicates the columns you want to retrieve.
@code{SELECT} may also be used to retrieve rows computed without reference to
any table.  For example:

@example
mysql> SELECT 1 + 1;
         -> 2
@end example

All keywords used must be given in exactly the order shown above. For example,
a @code{HAVING} clause must come after any @code{GROUP BY} clause and before
any @code{ORDER BY} clause.

@itemize @bullet

@item
@cindex Aliases, on expressions
@cindex Expression aliases
A @code{SELECT} expression may be given an alias using @code{AS}. The alias
is used as the expression's column name and can be used with
@code{ORDER BY} or @code{HAVING} clauses.  For example:

@example
mysql> select concat(last_name,', ',first_name) AS full_name
    from mytable ORDER BY full_name;
@end example

@item
The @code{FROM table_references} clause indicates the tables from which to
retrieve rows.  If you name more than one table, you are performing a
join.  For information on join syntax, see @ref{JOIN, , @code{JOIN}}.

@item
You can refer to a column as @code{col_name}, @code{tbl_name.col_name} or
@code{db_name.tbl_name.col_name}.  You need not specify a @code{tbl_name} or
@code{db_name.tbl_name} prefix for a column reference in a @code{SELECT}
statement unless the reference would be ambiguous.  See @ref{Legal names},
for examples of ambiguity that require the more explicit column reference
forms.

@item
@cindex Aliases, for tables
@cindex Table aliases
A table reference may be aliased using @code{tbl_name [AS] alias_name}.

@example
mysql> select t1.name, t2.salary from employee AS t1, info AS t2
           where t1.name = t2.name;
mysql> select t1.name, t2.salary from employee t1, info t2
           where t1.name = t2.name;
@end example

@item
Columns selected for output may be referred to in @code{ORDER BY} and
@code{GROUP BY} clauses using column names, column aliases or column
positions.  Column positions begin with 1.

@example
mysql> select college, region, seed from tournament
           ORDER BY region, seed;
mysql> select college, region AS r, seed AS s from tournament
           ORDER BY r, s;
mysql> select college, region, seed from tournament
           ORDER BY 2, 3;
@end example

To sort in reverse order, add the @code{DESC} (descending) keyword to the
name of the column in the @code{ORDER BY} clause that you are sorting by.
The default is ascending order; this may be specified explicitly using
the @code{ASC} keyword.

@item
The @code{HAVING} clause can refer to any column or alias named in the
@code{select_expression}. It is applied last, just before items are sent to
the client, with no optimization. Don't use @code{HAVING} for items that
should be in the @code{WHERE} clause.  For example, do not write this:

@example
mysql> select col_name from tbl_name HAVING col_name > 0;
@end example

Write this instead:

@example
mysql> select col_name from tbl_name WHERE col_name > 0;
@end example

In @strong{MySQL} 3.22.5 or later, you can also write queries like this:

@example
mysql> select user,max(salary) from users
           group by user HAVING max(salary)>10;
@end example

In older @strong{MySQL} versions, you can write this instead:

@example
mysql> select user,max(salary) AS sum from users
           group by user HAVING sum>10;
@end example

@item
@code{STRAIGHT_JOIN} forces the optimizer to join the tables in the order in
which they are listed in the @code{FROM} clause. You can use this to speed up
a query if the optimizer joins the tables in non-optimal order.
@xref{EXPLAIN, , @code{EXPLAIN}}.

@item
@code{SQL_SMALL_RESULT} can be used with @code{GROUP BY} or @code{DISTINCT}
to tell the optimizer that the result set will be small.  In this case,
@strong{MySQL} will use fast temporary tables to store the resulting table
instead of using sorting.  @code{SQL_SMALL_RESULT} is a @strong{MySQL}
extension to ANSI SQL92.

@item
The @code{LIMIT} clause can be used to constrain the number of rows returned
by the @code{SELECT} statement.  @code{LIMIT} takes one or two numeric
arguments.

If two arguments are given, the first specifies the offset of the first row to
return, the second specifies the maximum number of rows to return.
The offset of the initial row is 0 (not 1).

@example
mysql> select * from table LIMIT 5,10;  # Retrieve rows 6-15
@end example

If one argument is given, it indicates the maximum number of rows to return.

@example
mysql> select * from table LIMIT 5;     # Retrieve first 5 rows
@end example

In other words, @code{LIMIT n} is equivalent to @code{LIMIT 0,n}.

@item
@tindex /etc/passwd
The @code{SELECT ... INTO OUTFILE 'file_name'} form of @code{SELECT} writes
the selected rows to a file. The file is created on the server host, and
cannot already exist (among other things, this prevents database tables and
files such as @file{/etc/passwd} from being destroyed).  You must have the
@strong{file} privilege on the server host to use this form of @code{SELECT}.

@code{SELECT ...  INTO OUTFILE} is the complement of @code{LOAD DATA
INFILE}; the syntax for the @code{export_options} part of the statement
consists of the same @code{FIELDS} and @code{LINES} clauses that are used
with the @code{LOAD DATA INFILE} statement.
@xref{LOAD DATA, , @code{LOAD DATA}}.

In the resulting text file, only the following characters are escaped by
the @code{ESCAPED BY} character:

@itemize @bullet
@item The @code{ESCAPED BY} character
@item The first character in @code{FIELDS TERMINATED BY}
@item The first character in @code{LINES TERMINATED BY}
@end itemize

Additionally @code{ASCII 0} is converted to @code{ESCAPED BY} followed by 0
(@code{ASCII 48}).

The reason for the above is that one MUST escape any @code{FIELDS
TERMINATED BY}, @code{ESCAPED BY} or @code{LINES TERMINATED BY}
characters to be able to reliable be able to read the file
back. @code{ASCII 0} is escaped to make it easier to view with some
pages.  As the above file doesn't have to conform to any SQL syntax
nothing else needs to be escaped.

As the resulting file doesn't have to conform to the SQL syntax nothing
else needs to be escaped.
@end itemize

@findex JOIN
@findex CROSS JOIN
@findex LEFT JOIN
@findex LEFT OUTER JOIN
@findex NATURAL LEFT JOIN
@findex NATURAL LEFT OUTER JOIN
@findex STRAIGHT_JOIN
@node JOIN, INSERT, SELECT, Reference
@section @code{JOIN} syntax

@strong{MySQL} supports the following @code{JOIN} syntaxes for use in
@code{SELECT} statements:

@example
table_reference, table_reference
table_reference [CROSS] JOIN table_reference
table_reference STRAIGHT_JOIN table_reference
table_reference LEFT [OUTER] JOIN table_reference ON conditional_expr
table_reference LEFT [OUTER] JOIN table_reference USING (column_list)
table_reference NATURAL LEFT [OUTER] JOIN table_reference
@{ oj table_reference LEFT OUTER JOIN table_reference ON conditional_expr @}
@end example

@cindex ODBC compatibility
@cindex Compatibility, with ODBC
The last @code{LEFT OUTER JOIN} syntax shown above exists only for
compatibility with ODBC.

@itemize @bullet
@item
A table reference may be aliased using @code{tbl_name AS alias_name} or
@code{tbl_name alias_name}.

@example
mysql> select t1.name, t2.salary from employee AS t1, info AS t2
           where t1.name = t2.name;
@end example

@item
@code{JOIN} and @code{,} (comma) are semantically equivalent.  Both do a full
join between the tables used.  Normally, you specify how the tables should be
linked in the @code{WHERE} condition.

@item
The @code{ON} conditional is any conditional of the form that may be used in
a @code{WHERE} clause.

@item
If there is no matching record for the right table in a @code{LEFT JOIN}, a
row with all columns set to @code{NULL} is used for the right table.  You can
use this fact to find records in a table that have no counterpart in another
table:

@example
mysql> select table1.* from table1
           LEFT JOIN table2 ON table1.id=table2.id
           where table2.id is NULL;
@end example

This example finds all rows in @code{table1} with an @code{id} value that is
not present in @code{table2} (i.e., all rows in @code{table1} with no
corresponding row in @code{table2}).  This assumes that @code{table2.id} is
declared @code{NOT NULL}, of course.

@item
The @code{USING} @code{column_list} clause names a list of columns that must
exist in both tables.  A @code{USING} clause such as:

@example
A LEFT JOIN B USING (C1,C2,C3,...)
@end example

is defined to be semantically identical to an @code{ON} expression like
this:

@example
A.C1=B.C1 AND A.C2=B.C2 AND A.C3=B.C3,...
@end example

@item
The @code{NATURAL LEFT JOIN} of two tables is defined to be semantically
equivalent to a @code{LEFT JOIN} with a @code{USING} clause that names all
columns that exist in both tables.

@item
@code{STRAIGHT_JOIN} is identical to @code{JOIN}, except that the left table
is always read before the right table. This can be used for those (few)
cases where the join optimizer puts the tables in the wrong order.
@end itemize

Some examples:

@example
mysql> select * from table1,table2 where table1.id=table2.id;
mysql> select * from table1 LEFT JOIN table2 ON table1.id=table2.id;
mysql> select * from table1 LEFT JOIN table2 USING (id);
mysql> select * from table1 LEFT JOIN table2 ON table1.id=table2.id
           LEFT JOIN table3 ON table2.id=table3.id;
@end example

@xref{LEFT JOIN optimization, , @code{LEFT JOIN} optimization}.

@findex INSERT
@node INSERT, REPLACE, JOIN, Reference
@section @code{INSERT} syntax

@example
    INSERT [LOW_PRIORITY | DELAYED] [IGNORE]
        [INTO] tbl_name [(col_name,...)]
        VALUES (expression,...),(...),...
or  INSERT [LOW_PRIORITY | DELAYED] [IGNORE]
        [INTO] tbl_name [(col_name,...)]
        SELECT ...
or  INSERT [LOW_PRIORITY | DELAYED] [IGNORE]
        [INTO] tbl_name
        SET col_name=expression, col_name=expression, ...
@end example

@code{INSERT} inserts new rows into an existing table.  The @code{INSERT ...
VALUES} form of the statement inserts rows based on explicitly-specified
values.  The @code{INSERT ... SELECT} form inserts rows selected from another
table or tables.  The @code{INSERT ... VALUES} form with multiple value lists
is supported in @strong{MySQL} 3.22.5 or later.  The
@code{col_name=expression} syntax is supported in @strong{MySQL} 3.22.10 or
later.

@code{tbl_name} is the table into which rows should be inserted.  The column
name list or the @code{SET} clause indicates which columns the statement
specifies values for.

@itemize @bullet
@item
If you specify no column list for @code{INSERT ... VALUES} or @code{INSERT
... SELECT}, values for all columns must be provided in the
@code{VALUES()} list or by the @code{SELECT}.  If you don't know the order of
the columns in the table, use @code{DESCRIBE tbl_name} to find out.

@item
Any column not explicitly given a value is set to its default value.  For
example, if you specify a column list that doesn't name all the columns in
the table, unnamed columns are set to their default values.  Default value
assignment is described in @ref{CREATE TABLE, , @code{CREATE TABLE}}.

@item
An @code{expression} may refer to any column that was set earlier in a value
list.  For example, you can say this:

@example
mysql> INSERT INTO tbl_name (col1,col2) VALUES(15,col1*2);
@end example

But not this:

@example
mysql> INSERT INTO tbl_name (col1,col2) VALUES(col2*2,15);
@end example

@item
If you specify the keyword @code{LOW_PRIORITY}, execution of the
@code{INSERT} is delayed until no other clients are reading from the table.

@item
If you specify the keyword @code{IGNORE} in an @code{INSERT} with many value
rows, any rows which duplicate an existing @code{PRIMARY} or @code{UNIQUE}
key in the table are ignored and are not inserted.  If you do not specify
@code{IGNORE}, the insert is aborted if there is any row that duplicates an
existing key value.  You can check with the @code{mysql_info()} how many rows
were inserted into the table.

@item
If @strong{MySQL} was configured using the @code{DONT_USE_DEFAULT_FIELDS}
option, @code{INSERT} statements generate an error unless you explicitly
specify values for all columns that require a non-@code{NULL} value.
@xref{configure options,  , @code{configure} options}.

@item
The following conditions hold for a @code{INSERT INTO ... SELECT} statement:

@itemize @minus
@item
The query cannot contain an @code{ORDER BY} clause.

@item
The target table of the @code{INSERT} statement cannot appear in the
@code{FROM} clause of the @code{SELECT} part of the query, because it's
forbidden in ANSI SQL to @code{SELECT} from the same table into which you are
@code{INSERT}ing.  (The problem is that the @code{SELECT} possibly would
find records that were inserted earlier during the same run.  When using
sub-select clauses, the situation could easily be very confusing!)

@item
@code{AUTO_INCREMENT} columns work as usual.
@end itemize
@end itemize

@findex mysql_info()
If you use @code{INSERT ... SELECT} or a @code{INSERT ... VALUES}
statement with multiple value lists, you can use the C API function
@code{mysql_info()} to get information about the query.  The format of the
information string is shown below:

@example
Records: 100 Duplicates: 0 Warnings: 0
@end example

@code{Duplicates} indicates the number of rows that couldn't be inserted
because they would duplicate some existing unique index value.
@code{Warnings} indicates the number of attempts to insert column values that
were problematic in some way. Warnings can occur under any of the following
conditions:

@itemize @bullet
@item
Inserting @code{NULL} into a column that has been declared @code{NOT NULL}.
The column is set to its default value.

@item
Setting a numeric column to a value that lies outside the column's range.
The value is clipped to the appropriate endpoint of the range.

@item
Setting a numeric column to a value such as @code{'10.34 a'}.  The trailing
garbage is stripped and the remaining numeric part is inserted.  If the value
doesn't make sense as a number at all, the column is set to @code{0}.

@item
Inserting a string into a @code{CHAR}, @code{VARCHAR}, @code{TEXT} or
@code{BLOB} column that exceeds the column's maximum length.  The value is
truncated to the column's maximum length.

@item
Inserting a value into a date or time column that is illegal for the column
type.  The column is set to the appropriate ``zero'' value for the type.
@end itemize

@findex INSERT DELAYED
@findex DELAYED

The @code{DELAYED} option
for the
@code{INSERT} statement is a @strong{MySQL}-specific option that is very
useful if you have clients that can't wait for the @code{INSERT} to complete.
This is common when you use @strong{MySQL} for logging and you also
periodically run @code{SELECT} statements that take a long time to complete.
@code{DELAYED} was introduced in @strong{MySQL} 3.22.15.  It is a
@strong{MySQL} extension to ANSI SQL92.

Another major benefit of using @code{INSERT DELAYED} is that inserts
from many clients are bundled together and written in one block. This is much
faster than doing many separate inserts.

Note that currently the queued rows are only stored in memory until they are
inserted into the table.  This means that if you kill @code{mysqld}
the hard way (@code{kill -9}) or if @code{mysqld} dies unexpectedly, any
queued rows that weren't written to disk are lost!

The following happens when you use the @code{DELAYED} option to @code{INSERT}
or @code{REPLACE}.  In this description, the ``thread'' is the thread that
received an @code{INSERT DELAYED} command and ``handler'' is the thread that
handles all @code{INSERT DELAYED} statements for a particular table.

@itemize @bullet
@item
When a thread executes a @code{DELAYED} statement for a table, a handler
thread is created to handle all @code{DELAYED} statements for the table, if
no such handler already exists.

@item
The thread checks whether or not the handler has acquired a @code{DELAYED}
lock already; if not, it tells the handler thread to do so.  The
@code{DELAYED} lock can be obtained even if other threads have a @code{READ}
or @code{WRITE} lock on the table.  However, the handler will wait for all
@code{ALTER TABLE} locks or @code{FLUSH TABLES} to ensure that the table
structure is up to date.

@item
The thread executes the @code{INSERT} statement but instead of writing
the row to the table it puts a copy of the final row into a queue that
is managed by the handler thread. Any syntax errors are noticed by the
thread and reported the client program.

@item
The client can't report the number of duplicates or the @code{AUTO_INCREMENT}
value for the resulting row; it can't obtain them from the server, because
the @code{INSERT} returns before the insert operation has been completed.  If
you use the C API, the @code{mysql_info()} function doesn't return anything
meaningful, for the same reason.

@item
The update log is updated by the handler thread when the row is inserted into
the table.  In case of multiple-row inserts, the update log is updated when
the first row is inserted.

@item
After every @code{delayed_insert_limit} rows are written, the handler checks
whether or not any @code{SELECT} statements are still pending.  If so, it
allows these to execute before continuing.

@item
When the handler has no more rows in its queue, the table is unlocked.  If no
new @code{INSERT DELAYED} commands are received within
@code{delayed_insert_timeout} seconds, the handler terminates.

@item
If more than @code{delayed_queue_size} rows are pending already in a specific
handler queue, the thread waits until there is room in the queue.  This is
useful to ensure that the @code{mysqld} server doesn't use all memory for the
delayed memory queue.

@item
The handler thread will show up in the @strong{MySQL} process list
with @code{delayed_insert} in the @code{Command} column.  It will
be killed if you execute a @code{FLUSH TABLES} command or kill it with
@code{KILL thread_id}. However, it will first store all queued rows into the
table before exiting. During this time it will not accept any new
@code{INSERT} commands from another thread. If you execute an @code{INSERT
DELAYED} command after this, a new handler thread will be created.

@item
Note that the above means that @code{INSERT DELAYED} commands have higher
priority than normal @code{INSERT} commands if there is an @code{INSERT
DELAYED} handler already running!  Other update commands will have to wait
until the @code{INSERT DELAY} queue is empty, someone kills the handler
thread (with @code{KILL thread_id}) or someone executes @code{FLUSH TABLES}.

@item
The following status variables provide information about @code{INSERT
DELAYED} commands:

@multitable @columnfractions .35 .65
@item @code{Delayed_insert_threads} @tab Number of handler threads
@item @code{Delayed_writes} @tab Number of rows written with @code{INSERT DELAYED}
@item @code{Not_flushed_delayed_rows} @tab Number of rows waiting to be written
@end multitable

You can view these variables by issuing a @code{SHOW STATUS} statement or
by executing a @code{mysqladmin extended-status} command.
@end itemize

@findex REPLACE
@node REPLACE, LOAD DATA, INSERT, Reference
@section @code{REPLACE} syntax

@example
    REPLACE [LOW_PRIORITY | DELAYED]
        [INTO] tbl_name [(col_name,...)]
        VALUES (expression,...)
or  REPLACE [LOW_PRIORITY | DELAYED]
        [INTO] tbl_name [(col_name,...)]
        SELECT ...
or  REPLACE [LOW_PRIORITY | DELAYED]
        [INTO] tbl_name
        SET col_name=expression, col_name=expression,...
@end example

@code{REPLACE} works exactly like @code{INSERT}, except that if an old
record in the table has the same value as a new record on a unique index,
the old record is deleted before the new record is inserted.
@xref{INSERT, , @code{INSERT}}.

@findex LOAD DATA INFILE
@node LOAD DATA, UPDATE, REPLACE, Reference
@section @code{LOAD DATA INFILE} syntax

@example
LOAD DATA [LOCAL] INFILE 'file_name.txt' [REPLACE | IGNORE]
    INTO TABLE tbl_name
    [FIELDS
        [TERMINATED BY '\t']
        [OPTIONALLY] ENCLOSED BY '']
        [ESCAPED BY '\\' ]]
    [LINES TERMINATED BY '\n']
    [IGNORE number LINES]
    [(col_name,...)]
@end example

The @code{LOAD DATA INFILE} statement reads rows from a text file into a
table at a very high speed.  If the @code{LOCAL} keyword is specified, the
file is read from the client host.  If @code{LOCAL} is not specified, the
file must be located on the server.  (@code{LOCAL} is available in
@strong{MySQL} 3.22.6 or later.)

For security reasons, when reading text files located on the server, the
files must either reside in the database directory or be readable by all.
Also, to use @code{LOAD DATA INFILE} on server files, you must have the
@strong{file} privilege on the server host.
@xref{Privileges}.

Using @code{LOCAL} will be a bit slower than letting the server access the
files directly, since the contents of the file must travel from the client
host to the server host.  On the other hand, you do not need the
@strong{file} privilege to load local files.

@cindex @code{mysqlimport}
You can also load data files by using the @code{mysqlimport} utility; it
operates by sending a @code{LOAD DATA INFILE} command to the server.  The
@code{--local} option causes @code{mysqlimport} to read data files from the
client host.  You can specify the @code{--compress} option to get better
performance over slow networks if the client and server support the
compressed protocol.

When locating files on the server host, the server uses the following rules:

@itemize @bullet
@item
If an absolute pathname is given, the server uses the pathname as is.

@item
If a relative pathname with one or more leading components is given,
the server searches for the file relative to the server's data directory.

@item
If a filename with no leading components is given, the server looks for
the file in the database directory of the current database.
@end itemize

Note that these rules mean a file given as @file{./myfile.txt} is read from
the server's data directory, whereas a file given as @file{myfile.txt} is
read from the database directory of the current database.  Note also that
for statements such as those below, the file is read from the database
directory for @code{db1}, not @code{db2}:

@example
mysql> USE db1;
mysql> LOAD DATA INFILE "./data.txt" INTO TABLE db2.my_table; 
@end example

The @code{REPLACE} and @code{IGNORE} keywords control handling of input
records that duplicate existing records on unique key values.  If you specify
@code{REPLACE}, new rows replace existing rows that have the same unique key
value. If you specify @code{IGNORE}, input rows that duplicate an existing
row on a unique key value are skipped.  If you don't specify either option, an
error occurs when a duplicate key value is found, and the rest of the text
file is ignored.

If you load data from a local file using the @code{LOCAL} keyword, the server
has no way to stop transmission of the file in the middle of the operation,
so the default bahavior is the same as if @code{IGNORE} is specified.

@code{LOAD DATA INFILE} is the complement of @code{SELECT ... INTO OUTFILE}.
@xref{SELECT, , @code{SELECT}}.
To write data from a database to a file, use @code{SELECT ... INTO OUTFILE}.
To read the file back into the database, use @code{LOAD DATA INFILE}.
The syntax of the @code{FIELDS} and @code{LINES} clauses is the same for
both commands.  Both clauses are optional, but @code{FIELDS}
must precede @code{LINES} if both are specified.

If you specify a @code{FIELDS} clause,
each of its subclauses (@code{TERMINATED BY}, @code{[OPTIONALLY] ENCLOSED
BY} and @code{ESCAPED BY}) is also optional, except that you must
specify at least one of them.

If you don't specify a @code{FIELDS} clause, the defaults are the
same as if you had written this:

@example
FIELDS TERMINATED BY '\t' ENCLOSED BY '' ESCAPED BY '\\'
@end example

If you don't specify a @code{LINES} clause, the default
is the same as if you had written this:

@example
LINES TERMINATED BY '\n'
@end example

In other words, the defaults cause @code{LOAD DATA INFILE} to act as follows
when reading input:

@itemize @bullet
@item
Look for line boundaries at newlines

@item
Break lines into fields at tabs

@item
Do not expect fields to be enclosed within any quoting characters

@item
Interpret occurrences of tab, newline or @samp{\} preceded by
@samp{\} as literal characters that are part of field values
@end itemize

Conversely, the defaults cause @code{SELECT ... INTO OUTFILE} to act as
follows when writing output:

@itemize @bullet
@item
Write tabs between fields

@item
Do not enclose fields within any quoting characters

@item
Use @samp{\} to escape instances of tab, newline or @samp{\} that occur
within field values

@item
Write newlines at the ends of lines
@end itemize

Note that to write @code{FIELDS ESCAPED BY '\\'}, you must specify two
backslashes for the value to be read as a single backslash.

The @code{IGNORE number LINES} option can be used to ignore a header of
column names at the start of the file:

@example
mysql> LOAD DATA INFILE "/tmp/file_name" into table test IGNORE 1 LINES;
@end example

When you use @code{SELECT ... INTO OUTFILE} in tandem with @code{LOAD
DATA INFILE} to write data from a database into a file and then read
the file back into the database later, the field and line handling
options for both commands must match.  Otherwise, @code{LOAD DATA
INFILE} will not interpret the contents of the file properly.  Suppose
you use @code{SELECT ... INTO OUTFILE} to write a file with
fields delimited by commas:

@example
mysql> SELECT * FROM table1 INTO OUTFILE 'data.txt'
           FIELDS TERMINATED BY ','
           FROM ...
@end example

To read the comma-delimited file back in, the correct statement would be:

@example
mysql> LOAD DATA INFILE 'data.txt' INTO TABLE table2
           FIELDS TERMINATED BY ',';
@end example

If instead you tried to read in the file with the statement shown below, it
wouldn't work because it instructs @code{LOAD DATA INFILE} to look for
tabs between fields:

@example
mysql> LOAD DATA INFILE 'data.txt' INTO TABLE table2
           FIELDS TERMINATED BY '\t';
@end example

The likely result is that each input line would be interpreted as
a single field.

@code{LOAD DATA INFILE} can be used to read files obtained from
external sources, too. For example, a file in dBASE format will have
fields separated by commas and enclosed in double quotes.  If lines in
the file are terminated by newlines, the command shown below
illustrates the field and line handling options you would use to load
the file:

@example
mysql> LOAD DATA INFILE 'data.txt' INTO TABLE tbl_name
           FIELDS TERMINATED BY ',' ENCLOSED BY '"'
           LINES TERMINATED BY '\n';
@end example

Any of the field or line handling options may specify an empty string
(@code{''}).  If not empty, the @code{FIELDS [OPTIONALLY] ENCLOSED BY}
and @code{FIELDS ESCAPED BY} values must be a single character.  The
@code{FIELDS TERMINATED BY} and @code{LINES TERMINATED BY} values may
be more than one character.  For example, to write lines that are
terminated by carriage return-linefeed pairs, or to read a file
containing such lines, specify a @code{LINES TERMINATED BY '\r\n'}
clause.

@code{FIELDS [OPTIONALLY] ENCLOSED BY} controls quoting of fields.  For
output (@code{SELECT ... INTO OUTFILE}), if you omit the word
@code{OPTIONALLY}, all fields are enclosed by the @code{ENCLOSED BY}
character.  An example of such output (using a comma as the field
delimiter) is shown below:

@example
"1","a string","100.20"
"2","a string containing a , comma","102.20"
"3","a string containing a \" quote","102.20"
"4","a string containing a \", quote and comma","102.20"
@end example

If you specify @code{OPTIONALLY}, the @code{ENCLOSED BY} character is
used only to enclose @code{CHAR} and @code{VARCHAR} fields:

@example
1,"a string",100.20
2,"a string containing a , comma",102.20
3,"a string containing a \" quote",102.20
4,"a string containing a \", quote and comma",102.20
@end example

Note that occurrences of the @code{ENCLOSED BY} character within a
field value are escaped by prefixing them with the @code{ESCAPED BY}
character.  Also note that if you specify an empty @code{ESCAPED BY}
value, it is possible to generate output that cannot be read properly by
@code{LOAD DATA INFILE}. For example, the output just shown above would
appear as shown below if the escape character is empty.  Observe that the
second field in the fourth line contains a comma following the quote, which
(erroneously) appears to terminate the field:

@example
1,"a string",100.20
2,"a string containing a , comma",102.20
3,"a string containing a " quote",102.20
4,"a string containing a ", quote and comma",102.20
@end example

For input, the @code{ENCLOSED BY} character, if present, is stripped from the
ends of field values.  (This is true whether or not @code{OPTIONALLY} is
specified; @code{OPTIONALLY} has no effect on input interpretation.)
Occurrences of the @code{ENCLOSED BY} character preceded by the
@code{ESCAPED BY} character are interpreted as part of the current field
value.  In addition, duplicated @code{ENCLOSED BY} characters occurring
within fields are interpreted as single @code{ENCLOSED BY} characters if the
field itself starts with that character.  For example, if @code{ENCLOSED BY
'"'} is specified, quotes are handled as shown below:

@example
"The ""BIG"" boss"  -> The "BIG" boss
The "BIG" boss      -> The "BIG" boss
The ""BIG"" boss    -> The ""BIG"" boss
@end example

@code{FIELDS ESCAPED BY} controls how to write or read special characters.
If the @code{FIELDS ESCAPED BY} character is not empty, it is used to prefix
the following characters on output:
@itemize @bullet
@item
The @code{FIELDS ESCAPED BY} character
@item
The @code{FIELDS [OPTIONALLY] ENCLOSED BY} character
@item
The first character of the @code{FIELDS TERMINATED BY} and
@code{LINES TERMINATED BY} values
@item
ASCII @code{0} (what is actually written following the escape character is
ASCII @code{'0'}, not a zero-valued byte)
@end itemize

If the @code{FIELDS ESCAPED BY} character is empty, no characters are escaped.
It is probably not a good idea to specify an empty escape character,
particularly if field values in your data contain any of the characters in
the list just given.

For input, if the @code{FIELDS ESCAPED BY} character is not empty, occurrences
of that character are stripped and the following character is taken literally
as part of a field value.  The exceptions are an escaped @samp{0} or
@samp{N} (e.g., @code{\0} or @code{\N} if the escape character is
@samp{\}).  These sequences are interpreted as ASCII @code{0} (a zero-valued
byte) and @code{NULL}.  See below for the rules on @code{NULL} handling.

For more information about @samp{\}-escape syntax,
see @ref{Literals}.

In certain cases, field and line handling options interact:

@itemize @bullet
@item
If @code{LINES TERMINATED BY} is an empty string and @code{FIELDS
TERMINATED BY} is non-empty, lines are also terminated with
@code{FIELDS TERMINATED BY}.
@item
If the @code{FIELDS TERMINATED BY} and @code{FIELDS ENCLOSED BY} values are
both empty (@code{''}), a fixed-row (non-delimited) format is used.  With
fixed-row format, no delimiters are used between fields. Instead, column
values are written and read using the ``display'' widths of the columns.  For
example, if a column is declared as @code{INT(7)}, values for the column are
written using 7-character fields.  On input, values for the column are
obtained by reading 7 characters.  Fixed-row format also affects handling of
@code{NULL} values; see below.
@end itemize

Handling of @code{NULL} values varies, depending on the @code{FIELDS} and
@code{LINES} options you use:

@itemize @bullet
@item
For the default @code{FIELDS} and @code{LINES} values,
@code{NULL} is written as @code{\N} for output and @code{\N} is read
as @code{NULL} for input (assuming the @code{ESCAPED BY} character
is @samp{\}).

@item
If @code{FIELDS ENCLOSED BY} is not empty, a field containing the literal
word @code{NULL} as its value is read as a @code{NULL} value (this differs
from the word @code{NULL} enclosed within @code{FIELDS ENCLOSED BY}
characters, which is read as the string @code{'NULL'}).

@item
If @code{FIELDS ESCAPED BY} is empty, @code{NULL} is written as the word
@code{NULL}.

@item
With fixed-row format (which happens when @code{FIELDS TERMINATED BY} and
@code{FIELDS ENCLOSED BY} are both empty), @code{NULL} is written as an empty
string.  Note that this causes both @code{NULL} values and empty strings in
the table to be indistinguishable when written to the file since they are
both written as empty strings.  If you need to be able to tell the two apart
when reading the file back in, you should not use fixed-row format.
@end itemize

Some cases are not supported by @code{LOAD DATA INFILE}:
@itemize @bullet

@item
Fixed-size rows (@code{FIELDS TERMINATED BY} and @code{FIELDS ENCLOSED
BY} both empty) and @code{BLOB} or @code{TEXT} columns.

@item
If you specify one separator that is the same as or a prefix of another,
@code{LOAD DATA INFILE} won't be able to interpret the input properly.
For example, the following @code{FIELDS} clause would cause problems:

@example
FIELDS TERMINATED BY '"' ENCLOSED BY '"'
@end example

@item
If @code{FIELDS ESCAPED BY} is empty, a field value that contains an occurrence
of @code{FIELDS ENCLOSED BY} or @code{LINES TERMINATED BY}
followed by the @code{FIELDS TERMINATED BY} value will cause @code{LOAD
DATA INFILE} to stop reading a field or line too early.
This happens because @code{LOAD DATA INFILE} cannot properly determine
where the field or line value ends.
@end itemize

The following example loads all columns of the @code{persondata} table:

@example
mysql> LOAD DATA INFILE 'persondata.txt' INTO TABLE persondata;
@end example

No field list is specified, so @code{LOAD DATA INFILE} expects input rows
to contain a field for each table column.  The default @code{FIELDS} and
@code{LINES} values are used.

If you wish to load only some of a table's columns, specify a field list:

@example
mysql> LOAD DATA INFILE 'persondata.txt'
           INTO TABLE persondata (col1,col2,...);
@end example

You must also specify a field list if the order of the fields in the input
file differs from the order of the columns in the table.  Otherwise,
@strong{MySQL} cannot tell how to match up input fields with table columns.

If a row has too few fields, the columns for which no input field is present
are set to default values.  Default value assignment is described in
@ref{CREATE TABLE, , @code{CREATE TABLE}}.

An empty field value is interpreted differently than if the field value
is missing:

@itemize @bullet
@item
For string types, the column is set to the empty string.

@item
For numeric types, the column is set to @code{0}.

@item
For date and time types, the column is set to the appropriate ``zero''
value for the type.
@xref{Date and time types}.
@end itemize

@code{TIMESTAMP} columns are only set to the current date and time if there
is a @code{NULL} value for the column, or (for the first @code{TIMESTAMP}
column only) if the @code{TIMESTAMP} column is left out from the field list
when a field list is specified.

If an input row has too many fields, the extra fields are ignored and
the number of warnings is incremented.

@code{LOAD DATA INFILE} regards all input as strings, so you can't use
numeric values for @code{ENUM} or @code{SET} columns the way you can with
@code{INSERT} statements.  All @code{ENUM} and @code{SET} values must be
specified as strings!

@findex mysql_info()
If you are using the C API, you can get information about the query by
calling the API function @code{mysql_info()} when the @code{LOAD DATA INFILE}
query finishes.  The format of the information string is shown below:

@example
Records: 1  Deleted: 0  Skipped: 0  Warnings: 0
@end example

Warnings occur under the same circumstances as when values are inserted
via the @code{INSERT} statement (@pxref{INSERT, , @code{INSERT}}), except
that @code{LOAD DATA INFILE} also generates warnings when there are too few
or too many fields in the input row.  The warnings are not stored anywhere;
the number of warnings can only be used as an indication if everything went
well.  If you get warnings and want to know exactly why you got them, one way
to do this is to use @code{SELECT ... INTO OUTFILE} into another file and
compare this to your original input file.

For more information about the efficiency of @code{INSERT} versus
@code{LOAD DATA INFILE} and speeding up @code{LOAD DATA INFILE},
see @ref{Table efficiency}.

@findex UPDATE
@node UPDATE, USE, LOAD DATA, Reference
@section @code{UPDATE} syntax

@example
UPDATE [LOW_PRIORITY] tbl_name SET col_name1=expr1,col_name2=expr2,...
    [WHERE where_definition]
@end example

@code{UPDATE} updates columns in existing table rows with new values.  The
@code{SET} clause indicates which columns to modify and the values they
should be given.  The @code{WHERE} clause, if given, specifies which rows
should be updated.  Otherwise all rows are updated.

If you specify the keyword @code{LOW_PRIORITY}, execution of the
@code{UPDATE} is delayed until no other clients are reading from the table.

If you access a column from @code{tbl_name} in an expression, @code{UPDATE} uses
the current value of the column.  For example, the following statement sets
the @code{age} column to one more than its current value:

@example
mysql> UPDATE persondata SET age=age+1;
@end example

@code{UPDATE} assignments are evaluated from left to right.  For example, the
following statement doubles the @code{age} column, then increments it:

@example
mysql> UPDATE persondata SET age=age*2, age=age+1;
@end example

If you set a column to the value it currently has, @strong{MySQL} notices
this and doesn't update it.

@findex mysql_info()
@code{UPDATE} returns the number of rows that were actually changed.
In @strong{MySQL} 3.22 or later, the C API function @code{mysql_info()}
returns the number of rows that were matched and updated and the number of
warnings that occurred during the @code{UPDATE}.

@findex USE
@node USE, FLUSH, UPDATE, Reference
@section @code{USE} syntax

@example
USE db_name
@end example

The @code{USE db_name} statement tells @strong{MySQL} to use the @code{db_name}
database as the default database for subsequent queries.  The database remains
current until the end of the session, or until another @code{USE} statement
is issued:

@example
mysql> USE db1;
mysql> SELECT count(*) FROM mytable;      # selects from db1.mytable
mysql> USE db2;
mysql> SELECT count(*) FROM mytable;      # selects from db2.mytable
@end example

Making a particular database current by means of the @code{USE} statement
does not preclude you from accessing tables in other databases.  The example
below accesses the @code{author} table from the @code{db1} database and the
@code{editor} table from the @code{db2} database:

@example
mysql> USE db1;
mysql> SELECT author_name,editor_name FROM author,db2.editor
           WHERE author.editor_id = db2.editor.editor_id;
@end example

@cindex Sybase compatibility
@cindex Compatibility, with Sybase
The @code{USE} statement is provided for Sybase compatibility.

@cindex @code{mysqladmin}
@findex FLUSH
@node FLUSH, KILL, USE, Reference
@section @code{FLUSH} syntax (clearing caches)

@example
FLUSH flush_option [,flush_option]
@end example

You should use the @code{FLUSH} command if you want to clear some of the
internal caches @strong{MySQL} uses.  To execute @code{FLUSH}, you must have
the @strong{reload} privilege.

@code{flush_option} can be any of the following:

@multitable @columnfractions .15 .85
@item @code{HOSTS}  @tab Empties the host cache tables.  You should flush the
host tables if some of your hosts change IP number or if you get the
error message @code{Host ... is blocked}.  When more than
@code{max_connect_errors} errors occur in a row for a given host while
connection to the @strong{MySQL} server, @strong{MySQL} assumes
something is wrong and blocks the host from further connection requests.
Flushing the host tables allows the host to attempt to connect
again. @xref{Blocked host}.) You can start @code{mysqld} with
@code{-O max_connection_errors=999999999} to avoid this error message.

@item @code{LOGS}   @tab Closes and reopens the standard and update log
files.  If you have specified the update log file without an extension, the
extension number of the new update log file will be incremented by one
relative to the previous file.

@item @code{PRIVILEGES} @tab Reloads the privileges from the grant tables in
the @code{mysql} database.

@item @code{TABLES} @tab Closes all open tables.

@item @code{STATUS} @tab Resets most status variables to zero.
@end multitable

You can also access each of the commands shown above with the @code{mysqladmin}
utility, using the @code{flush-hosts}, @code{flush-logs}, @code{reload}
or @code{flush-tables} commands.

@cindex @code{mysqladmin}
@findex KILL
@node KILL, SHOW, FLUSH, Reference
@section @code{KILL} syntax

@example
KILL thread_id
@end example

Each connection to @code{mysqld} runs in a separate thread.  You can see
which threads are running with the @code{SHOW PROCESSLIST} command, and kill
a thread with the @code{KILL thread_id} command.

If you have the @strong{process} privilege, you can see and kill all threads.
Otherwise, you can see and kill only your own threads.

You can also use the @code{mysqladmin processlist} and @code{mysqladmin kill}
commands to examine and kill threads.

@findex SHOW DATABASES
@findex SHOW TABLES
@findex SHOW COLUMNS
@findex SHOW FIELDS
@findex SHOW INDEX
@findex SHOW KEYS
@findex SHOW STATUS
@findex SHOW VARIABLES
@findex SHOW PROCESSLIST
@findex SHOW TABLE STATUS
@node SHOW, EXPLAIN, KILL, Reference
@section @code{SHOW} syntax (Get information about tables, columns,...)

@example
   SHOW DATABASES [LIKE wild]
or SHOW TABLES [FROM db_name] [LIKE wild]
or SHOW COLUMNS FROM tbl_name [FROM db_name] [LIKE wild]
or SHOW INDEX FROM tbl_name [FROM db_name]
or SHOW STATUS
or SHOW VARIABLES [LIKE wild]
or SHOW PROCESSLIST
or SHOW TABLE STATUS [FROM db_name] [LIKE wild]
@end example

@code{SHOW} provides information about databases, tables, columns or the
server. If the @code{LIKE wild} part is used, the @code{wild} string can be a
string that uses the SQL @samp{%} and @samp{_} wildcard characters.

You can use @code{db_name.tbl_name} as an alternative to the @code{tbl_name
FROM db_name} syntax.  These two statements are equivalent:

@example
mysql> SHOW INDEX FROM mytable FROM mydb;
mysql> SHOW INDEX FROM mydb.mytable;
@end example

@code{SHOW DATABASES} lists the databases on the @strong{MySQL} server
host.  You can also get this list using the @code{mysqlshow} command.

@code{SHOW TABLES} lists the tables in a given database.  You can also
get this list using the @code{mysqlshow db_name} command.

@strong{Note:} If a user doesn't have any privileges for a table, the table
will not show up in the output from @code{SHOW TABLES} or @code{mysqlshow
db_name}.

@code{SHOW COLUMNS} lists the columns in a given table.
If the column types are different than you expect them to be based on a
@code{CREATE TABLE} statement, note that MySQL sometimes changes column
types.
@xref{Silent column changes}.

The @code{DESCRIBE} statement provides information similar to
@code{SHOW COLUMNS}.
@xref{DESCRIBE, , @code{DESCRIBE}}.

@code{SHOW TABLE STATUS} (new in 3.23) works likes @code{SHOW STATUS}, but
provides a lot of information about each table. You can also
get this list using the @code{mysqlshow --status db_name} command.
The following columns are returned:

@multitable @columnfractions .35 .65
@item Name @tab Name of the table
@item Type @tab Type of table (NISAM, MYISAM or HEAP)
@item Rows @tab Number of rows
@item Avg_row_length @tab Average row length
@item Data_length @tab Length of the data file
@item Max_data_length @tab Max length of the data file
@item Index_length @tab Length of the index file
@item Data_free @tab Number of allocated but not used bytes
@item Auto_increment @tab Next autoincrement value
@item Create_time @tab When the table was created
@item Update_time @tab When the data file was last updated
@item Check_time @tab When one last run a check on the table
@item Create_min_rows @tab The "min_rows" option used when creating the table
@item Create_max_rows @tab The "max_rows" option used when creating the table
@item Create_avg_row_length @tab The "avg_row_length" option used when creating the table
@item Comment @tab The comment used when creating the table (or some information why MySQL couldn't access the table information).
@end multitable

@code{SHOW FIELDS} is a synonym for @code{SHOW COLUMNS} and
@code{SHOW KEYS} is a synonym for @code{SHOW INDEX}.  You can also
list a table's columns or indexes with @code{mysqlshow db_name tbl_name}
or @code{mysqlshow -k db_name tbl_name}.

@code{SHOW INDEX} returns the index information in a format that closely
resembles the @code{SQLStatistics} call in ODBC. The following columns
are returned:

@multitable @columnfractions .35 .65
@item Table @tab Name of the table
@item Non_unique @tab 0 if the index can't contain duplicates.
@item Key_name @tab Name of the index
@item Seq_in_index @tab Column sequence number in index, starting with 1.
@item Column_name @tab Column name.
@item Collation @tab How the column is sorted in the index.  In @strong{MySQL}, this can have values @code{A} (Ascending) or @code{NULL} (Not sorted).
@item Cardinality @tab Number of unique values in the index.  This is updated by running @code{isamchk -a}.
@item Sub_part @tab Number of indexed characters if the column is only partly indexed. @code{NULL} if the entire key is indexed.
@end multitable


@cindex @code{mysqladmin}
@code{SHOW STATUS} provides server status information
(like @code{mysqladmin extended-status}). The output resembles that shown
below, though the format and numbers may differ somewhat:

@example
+--------------------------+--------+
| Variable_name            | Value  |
+--------------------------+--------+
| Aborted_clients          | 0      |
| Aborted_connects         | 0      |
| Created_tmp_tables       | 0      |
| Delayed_insert_threads   | 0      |
| Delayed_writes           | 0      |
| Delayed_errors           | 0      |
| Flush_commands           | 2      |
| Handler_delete           | 2      |
| Handler_read_first       | 0      |
| Handler_read_key         | 1      |
| Handler_read_next        | 0      |
| Handler_read_rnd         | 35     |
| Handler_update           | 0      |
| Handler_write            | 2      |
| Key_blocks_used          | 0      |
| Key_read_requests        | 0      |
| Key_reads                | 0      |
| Key_write_requests       | 0      |
| Key_writes               | 0      |
| Max_used_connections     | 1      |
| Not_flushed_key_blocks   | 0      |
| Not_flushed_delayed_rows | 0      |
| Open_tables              | 1      |
| Open_files               | 2      |
| Open_streams             | 0      |
| Opened_tables            | 11     |
| Questions                | 14     |
| Running_threads          | 1      |
| Slow_queries             | 0      |
| Uptime                   | 149111 |
+--------------------------+--------+
@end example

The status variables listed above have the following meaning:

@multitable @columnfractions .35 .65
@item @code{Aborted_clients} @tab Number of connections that has been aborted because the client has died without closing the connection properly.
@item @code{Aborted_connects} @tab Number of tries to connect to the MySQL server that has failed.
@item @code{Created_tmp_tables} @tab Number of implicit temporary tables that has been created while executing statements.
@item @code{Delayed_insert_threads} @tab Number of delayed insert handler threads in use.
@item @code{Delayed_writes} @tab Number of rows written with @code{INSERT DELAYED}.
@item @code{Delayed_errors} @tab Number of rows written with @code{INSERT DELAYED} for which some error occurred (probably @code{duplicate key}).
@item @code{Flush_commands} @tab Number of executed @code{FLUSH} commands.
@item @code{Handler_delete} @tab Number of requests to delete a row from a table.
@item @code{Handler_read_first} @tab Number of request to read first the row in a table.
@item @code{Handler_read_key} @tab Number of request to read a row based on a key.
@item @code{Handler_read_next} @tab Number of request to read next row in key order.
@item @code{Handler_read_rnd} @tab Number of request to read a row based on a fixed position.
@item @code{Handler_update} @tab Number of requests to update a row in a table.
@item @code{Handler_write} @tab Number of requests to insert a row in a table.
@item @code{Key_blocks_used} @tab The number of used blocks in the key cache.
@item @code{Key_read_requests} @tab The number of request to read a key block from the cache.
@item @code{Key_reads} @tab The number of physical reads of a key block from disk.
@item @code{Key_write_requests} @tab The number of request to write a key block to the cache.
@item @code{Key_writes} @tab The number of physical writes of a key block to disk.
@item @code{Max_used_connections} @tab The maximum number of connections that has been in use simultaneously.
@item @code{Not_flushed_key_blocks} @tab Keys blocks in the key cache that has changed but hasn't yet been flushed to disk.
@item @code{Not_flushed_delayed_rows} @tab Number of rows waiting to be written in @code{INSERT DELAY} queues.
@item @code{Open_tables} @tab Number of tables that are open.
@item @code{Open_files} @tab  Number of files that are open.
@item @code{Open_streams} @tab Number of streams that are open (used mainly for logging)
@item @code{Opened_tables} @tab Number of tables that has been opened.
@item @code{Questions} @tab Number of questions asked from to the server.
@item @code{Running_threads} @tab Number of currently open connections.
@item @code{Slow_queries} @tab Number of queries that has taken more than @code{long_query_time}
@item @code{Uptime} @tab How many seconds the server has been up.
@end multitable

Some comments about the above:

@itemize @bullet
@item
If @code{Opened_tables} is big, then your @code{table_cache}
variable is probably too small.
@item
If @code{key_reads} is big, then your @code{key_cache} is probably too
small.  The cache hit rate can be calculated with
@code{key_reads}/@code{key_read_requests}.
@item
If @code{Handler_read_rnd} is big, then you have a probably a lot of queries
that requires MySQL to scan whole tables or you have joins that doesn't use
keys properly.
@end itemize

@code{SHOW VARIABLES} shows the values of the some of @strong{MySQL} system
variables.  You can also get this information using the @code{mysqladmin
variables} command.  If the default values are unsuitable, you can set most
of these variables using command-line options when @code{mysqld} starts up.
The output resembles that shown below, though the format and numbers may
differ somewhat:

@example
+------------------------+--------------------------+
| Variable_name          | Value                    |
+------------------------+--------------------------+
| back_log               | 5                        |
| connect_timeout        | 5                        |
| basedir                | /my/monty/               |
| datadir                | /my/monty/data/          |
| delayed_insert_limit   | 100                      |
| delayed_insert_timeout | 300                      |
| delayed_queue_size     | 1000                     |
| join_buffer_size       | 131072                   |
| flush_time             | 0                        |
| key_buffer_size        | 1048540                  |
| language               | /my/monty/share/english/ |
| log                    | OFF                      |
| log_update             | OFF                      |
| long_query_time        | 10                       |
| low_priority_updates   | OFF                      |
| max_allowed_packet     | 1048576                  |
| max_connections        | 100                      |
| max_connect_errors     | 10                       |
| max_delayed_threads    | 20                       |
| max_heap_table_size    | 16777216                 |
| max_join_size          | 4294967295               |
| max_sort_length        | 1024                     |
| max_tmp_tables         | 32                       |
| net_buffer_length      | 16384                    |
| port                   | 3306                     |
| protocol-version       | 10                       |
| record_buffer          | 131072                   |
| skip_locking           | ON                       |
| socket                 | /tmp/mysql.sock          |
| sort_buffer            | 2097116                  |
| table_cache            | 64                       |
| thread_stack           | 131072                   |
| tmp_table_size         | 1048576                  |
| tmpdir                 | /machine/tmp/            |
| version                | 3.23.0-alpha-debug       |
| wait_timeout           | 28800                    |
+------------------------+--------------------------+
@end example

@xref{Server parameters, ,Server parameters}.

@findex Threads
@findex PROCESSLIST
@code{SHOW PROCESSLIST} shows you which threads are running.  You can also
get this information using the @code{mysqladmin processlist} command.  If you
have the @strong{process} privilege, you can see all threads.  Otherwise, you
can see only your own threads.
@xref{KILL, , @code{KILL}}.

@findex EXPLAIN
@findex SELECT, optimizing
@node EXPLAIN, DESCRIBE, SHOW, Reference
@section @code{EXPLAIN} syntax (Get information about a @code{SELECT})

@example
EXPLAIN SELECT select_options
@end example

When you precede a @code{SELECT} statement with the keyword @code{EXPLAIN},
@strong{MySQL} explains how it would process the @code{SELECT}, providing
information about how tables are joined and in which order.

With the help of @code{EXPLAIN}, you can see when you must add indexes
to tables to get a faster @code{SELECT} that uses indexes to find the
records. You can also see if the optimizer joins the tables in an optimal
order. To force the optimizer to use a specific join order for a
@code{SELECT} statement, add a @code{STRAIGHT_JOIN} clause.

For non-simple joins, @code{EXPLAIN} returns a row of information for each
table used in the @code{SELECT} statement. The tables are listed in the order
they would be read.  @strong{MySQL} resolves all joins using a single-sweep
multi-join method. This means that @strong{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.

Output from @code{EXPLAIN} includes the following columns:

@table @code
@item table
The table to which the row of output refers.

@item type
The join type.  Information about the various types is given below.

@item possible_keys
The @code{possible_keys} column indicates which indexes @strong{MySQL} could
use to find the rows in the table.  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 @code{WHERE} clause 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 @code{EXPLAIN} again.

@findex SHOW INDEX
To see what indexes a table has, use @code{SHOW INDEX FROM tbl_name}.

@item key
The @code{key} column indicates the key that @strong{MySQL} actually
decided to use.  The key is @code{NULL} if no index was chosen.

@item key_len
The @code{key_len} column indicates the length of the key that
@strong{MySQL} decided to use.  The length is @code{NULL} if the @code{key}
is @code{NULL}.

@item ref
The @code{ref} column shows which columns or constants are used with the
@code{key} to select rows from the table.

@item rows
The @code{rows} column indicates the number of rows @strong{MySQL} must
examine to execute the query.

@item Extra
If the @code{Extra} column includes the text @code{Only index}, this means
that information is retrieved from the table using only information in the
index tree.  Normally, this is much faster than scanning the entire table.

If the @code{Extra} column includes the text @code{where used}, it means that
a @code{WHERE} clause will be used to restrict which rows will be matched
against the next table or sent to the client.
@end table

The different join types are listed below, ordered from best to worst type:

@cindex System table
@cindex Table, system
@table @code
@item system
The table has only one row (= system table). This is a special case of
the @code{const} join type.

@cindex Constant table
@cindex Table, constant
@item const
The table has at most one matching row, which will be read at the start of
the query. Since there is only one row, values from the column in this row
can be regarded as constants by the rest of the optimizer.  @code{const}
tables are very fast as they are read only once!

@item eq_ref
One row will be read from this table for each combination of rows from
the previous tables.  This the best possible join type, other than the
@code{const} types.  It is used when all parts of an index are used by
the join and the index is @code{UNIQUE} or a @code{PRIMARY KEY}.

@item ref
All rows with matching index values will be read from this table for each
combination of rows from the previous tables.  @code{ref} is used if the join
uses only a leftmost prefix of the key, or if the key is not @code{UNIQUE}
or a @code{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.

@item range
Only rows that are in a given range will be retrieved, using an index to
select the rows.  The @code{ref} column indicates which index is used.

@item index
This is the same as @code{ALL}, except that only the index tree is
scanned.  This is usually faster than @code{ALL}, as the index file is usually
smaller than the data file.

@item ALL
A full table scan will be done for each combination of rows from the
previous tables.  This is normally not good if the table is the first
table not marked @code{const}, and usually @strong{very} bad in all other
cases. You normally can avoid @code{ALL} by adding more indexes, so that
the row can be retrieved based on constant values or column values from
earlier tables.
@end table

You can get a good indication of how good a join is by multiplying all values
in the @code{rows} column of the @code{EXPLAIN} output. This should tell you
roughly how many rows @strong{MySQL} must examine to execute the query. This
number is also used when you restrict queries with the @code{max_join_size}
variable.
@xref{Server parameters}.

The following example shows how a @code{JOIN} can be optimized progressively
using the information provided by @code{EXPLAIN}.

Suppose you have the @code{SELECT} statement shown below, that you examine
using @code{EXPLAIN}:

@example
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;
@end example

For this example, assume that:

@itemize @bullet
@item
The columns being compared have been declared as follows:

@multitable @columnfractions .1 .2 .7
@item @strong{Table} @tab @strong{Column} @tab @strong{Column type}
@item @code{tt}      @tab @code{ActualPC}      @tab @code{CHAR(10)}
@item @code{tt}      @tab @code{AssignedPC}    @tab @code{CHAR(10)}
@item @code{tt}      @tab @code{ClientID}      @tab @code{CHAR(10)}
@item @code{et}      @tab @code{EMPLOYID}      @tab @code{CHAR(15)}
@item @code{do}      @tab @code{CUSTNMBR}      @tab @code{CHAR(15)}
@end multitable

@item
The tables have the indexes shown below:

@multitable @columnfractions .1 .9
@item @strong{Table} @tab @strong{Index}
@item @code{tt}      @tab @code{ActualPC}
@item @code{tt}      @tab @code{AssignedPC}
@item @code{tt}      @tab @code{ClientID}
@item @code{et}      @tab @code{EMPLOYID} (primary key)
@item @code{do}      @tab @code{CUSTNMBR} (primary key)
@end multitable

@item
The @code{tt.ActualPC} values aren't evenly distributed.
@end itemize

Initially, before any optimizations have been performed, the @code{EXPLAIN}
statement produces the following information:

@example
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)
@end example

Since @code{type} is @code{ALL} for each table, this output indicates that
@strong{MySQL} is doing a full join for all 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 @code{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 @strong{MySQL} can't (yet) use indexes on columns
efficiently if they are declared differently.  In this context,
@code{VARCHAR} and @code{CHAR} are the same unless they are declared as
different lengths. Since @code{tt.ActualPC} is declared as @code{CHAR(10)}
and @code{et.EMPLOYID} is declared as @code{CHAR(15)}, there is a length
mismatch.

To fix this disparity between column lengths, use @code{ALTER TABLE} to
lengthen @code{ActualPC} from 10 characters to 15 characters:

@example
mysql> ALTER TABLE tt MODIFY ActualPC VARCHAR(15);
@end example

Now @code{tt.ActualPC} and @code{et.EMPLOYID} are both @code{VARCHAR(15)}.
Executing the @code{EXPLAIN} statement again produces this result:

@example
table type   possible_keys   key     key_len ref         rows    Extra
tt    ALL    AssignedPC,ClientID,ActualPC NULL NULL NULL 3872    where used
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
@end example

This is not perfect, but is much better (the product of the @code{rows}
values is now less by a factor of 74). This version is executed in a couple
of seconds.

A second alteration can be made to eliminate the column length mismatches
for the @code{tt.AssignedPC = et_1.EMPLOYID} and @code{tt.ClientID =
do.CUSTNMBR} comparisons:

@example
mysql> ALTER TABLE tt MODIFY AssignedPC VARCHAR(15),
                      MODIFY ClientID   VARCHAR(15);
@end example

Now @code{EXPLAIN} produces the output shown below:

@example
table type   possible_keys   key     key_len ref            rows     Extra
et    ALL    PRIMARY         NULL    NULL    NULL           74
tt    ref    AssignedPC,ClientID,ActualPC ActualPC 15 et.EMPLOYID 52 where used
et_1  eq_ref PRIMARY         PRIMARY 15      tt.AssignedPC  1
do    eq_ref PRIMARY         PRIMARY 15      tt.ClientID    1
@end example

This is ``almost'' as good as it can get.

The remaining problem is that, by default, @strong{MySQL} assumes that values
in the @code{tt.ActualPC} column are evenly distributed, and that isn't the
case for the @code{tt} table.  Fortunately, it is easy to tell @strong{MySQL}
about this:

@example
shell> isamchk --analyze PATH_TO_MYSQL_DATABASE/tt
shell> mysqladmin refresh
@end example

Now the join is ``perfect'', and @code{EXPLAIN} produces this result:

@example
table type   possible_keys   key     key_len ref            rows    Extra
tt    ALL    AssignedPC,ClientID,ActualPC NULL NULL NULL    3872    where used
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
@end example

Note that the @code{rows} column in the output from @code{EXPLAIN} is an
``educated guess'' from the @strong{MySQL} join optimizer;  To optimize a
query, you should check if the numbers are even close to the truth.  If not,
you may get better performance by using @code{STRAIGHT_JOIN} in your
@code{SELECT} statement and trying to list the tables in a different order in
the @code{FROM} clause.

@findex DESC
@findex DESCRIBE
@node DESCRIBE, LOCK TABLES, EXPLAIN, Reference
@section @code{DESCRIBE} syntax (Get information about columns)

@example
@{DESCRIBE | DESC@} tbl_name @{col_name | wild@}
@end example

@code{DESCRIBE} provides information about a table's columns.  @code{col_name}
may be a column name or a string containing the SQL @samp{%} and @samp{_}
wildcard characters.

If the column types are different than you expect them to be based on a
@code{CREATE TABLE} statement, note that MySQL sometimes changes column
types.
@xref{Silent column changes}.

@cindex Oracle compatibility
@cindex Compatibility, with Oracle
This statement is provided for Oracle compatibility.

The @code{SHOW} statement provides similar information.
@xref{SHOW, , @code{SHOW}}.

@findex LOCK TABLES
@findex UNLOCK TABLES
@node LOCK TABLES, SET OPTION, DESCRIBE, Reference
@section @code{LOCK TABLES/UNLOCK TABLES} syntax

@example
LOCK TABLES tbl_name [AS alias] @{READ | [LOW_PRIORITY] WRITE@}
            [, tbl_name @{READ | [LOW_PRIORITY] WRITE@} ...]
...
UNLOCK TABLES
@end example

@code{LOCK TABLES} locks tables for the current thread.  @code{UNLOCK TABLES}
releases any locks held by the current thread.  All tables that are locked by
the current thread are automatically unlocked when the thread issues another
@code{LOCK TABLES}, or when the connection to the server is closed.

If a thread obtains a @code{READ} lock on a table, that thread (and all other
threads) can only read from the table. If a thread obtains a @code{WRITE}
lock on a table, then only the thread holding the lock can @code{READ} from
or @code{WRITE} to the table.  Other threads are blocked.

Each thread waits (without timing out) until it obtains all the locks it has
requested.

@code{WRITE} locks normally have higher priority than @code{READ} locks, to
ensure that updates are processed as soon as possible. This means that if one
thread obtains a @code{READ} lock and then another thread requests a
@code{WRITE} lock, subsequent @code{READ} lock requests will wait until the
@code{WRITE} thread has gotten the lock and released it.  You can use
@code{LOW_PRIORITY WRITE} locks to allow other threads to obtain @code{READ}
locks while the thread is waiting for the @code{WRITE} lock. You should only
use @code{LOW_PRIORITY WRITE} locks if you are sure that there will
eventually be a time when no threads will have a @code{READ} lock.

When you use @code{LOCK TABLES}, you must lock all tables that you are
going to use!  If you are using a table multiple times in a query (with
aliases), you must get a lock for each alias! This policy ensures that
table locking is deadlock free.

Note that you should @strong{NOT} lock any tables that you are using with
@code{INSERT DELAYED}.  This is because that in this case the @code{INSERT}
is done by a separate thread. 

Normally, you don't have to lock tables, as all single @code{UPDATE} statements
are atomic; no other thread can interfere with any other currently executing
SQL statement. There are a few cases when you would like to lock tables
anyway:

@itemize @bullet
@item
If you are going to run many operations on a bunch of tables, it's much
faster to lock the tables you are going to use.  The downside is, of course,
that no other thread can update a @code{READ}-locked table and no other
thread can read a @code{WRITE}-locked table.
@item
@strong{MySQL} doesn't support a transaction environment, so you must use
@code{LOCK TABLES} if you want to ensure that no other thread comes between a
@code{SELECT} and an @code{UPDATE}. The example shown below
requires @code{LOCK TABLES} in order to execute safely:

@example
mysql> LOCK TABLES trans READ, customer WRITE;
mysql> select sum(value) from trans where customer_id= some_id;
mysql> update customer set total_value=sum_from_previous_statement
           where customer_id=some_id;
mysql> UNLOCK TABLES;
@end example

Without @code{LOCK TABLES}, there is a chance that another thread might
insert a new row in the @code{trans} table between execution of the
@code{SELECT} and @code{UPDATE} statements.
@end itemize

By using incremental updates (@code{UPDATE customer SET
value=value+new_value}) or the @code{LAST_INSERT_ID()} function, you can
avoid using @code{LOCK TABLES} in many cases.

You can also solve some cases by using the user-level lock functions
@code{GET_LOCK()} and @code{RELEASE_LOCK()}.  These locks are saved in a hash
table in the server and implemented with @code{pthread_mutex_lock()} and
@code{pthread_mutex_unlock()} for high speed.
@xref{Miscellaneous functions}.

See @ref{Internal locking}, for more information on locking policy.

@findex SET OPTION
@node SET OPTION, GRANT, LOCK TABLES, Reference
@section @code{SET OPTION} syntax

@example
SET [OPTION] SQL_VALUE_OPTION= value, ...
@end example

@code{SET OPTION} sets various options that affect the operation of the
server or your client.  Any option you set remains in effect until the
current session ends, or until you set the option to a different value.

@table @code
@item CHARACTER SET character_set_name | DEFAULT
This maps all strings from and to the client with the given mapping.
Currently the only option for @code{character_set_name} is
@code{cp1251_koi8}, but you can easily add new mappings by editing the
@file{sql/convert.cc} file in the @strong{MySQL} source distribution.  The
default mapping can be restored by using a @code{character_set_name} value of
@code{DEFAULT}.

Note that the syntax for setting the @code{CHARACTER SET} option differs
from the syntax for setting the other options.

@item PASSWORD = PASSWORD('some password')
@cindex Passwords, setting
Set the password for the current user. Any non-anonymous user can change his
own password!

@item PASSWORD FOR user = PASSWORD('some password')
@cindex Passwords, setting
Set the password for a specific user on the current server host. Only a user
with access to the @code{mysql} database can do this.  The user should be
given in @code{user@@hostname} format, where @code{user} and @code{hostname}
are exactly as they are listed in the @code{User} and @code{Host} columns of
the @code{mysql.user} table entry.  For example, if you had an entry with
@code{User} and @code{Host} fields of @code{'bob'} and @code{'%.loc.gov'},
you would write:

@example
mysql> SET PASSWORD FOR bob@@"%.loc.gov" = PASSWORD("newpass");
@end example

@item SQL_BIG_TABLES = 0 | 1
@cindex The table is full
If set to @code{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
@code{The table tbl_name is full} for big @code{SELECT} operations that
require a large temporary table.  The default value for a new connection is
@code{0} (i.e., use in-memory temporary tables).

@item SQL_BIG_SELECTS = 0 | 1
If set to @code{1}, @strong{MySQL} will abort if a @code{SELECT} is attempted
that probably will take a very long time. This is useful when an inadvisable
@code{WHERE} statement has been issued. A big query is defined as a
@code{SELECT} that probably will have to examine more than
@code{max_join_size} rows.  The default value for a new connection is
@code{0} (which will allow all @code{SELECT} statements).

@item SQL_LOW_PRIORITY_UPDATES = 0 | 1
If set to @code{1}, all @code{INSERT}, @code{UPDATE} and @code{DELETE}
statements wait until there is no pending @code{SELECT} on the affected
table.

@item SQL_SELECT_LIMIT = value | DEFAULT
The maximum number of records to return from @code{SELECT} statements.  If
a @code{SELECT} has a @code{LIMIT} clause, the @code{LIMIT} takes precedence
over the value of @code{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 @code{SQL_SELECT_LIMIT} value of @code{DEFAULT}.

@item SQL_LOG_OFF = 0 | 1
If set to @code{1}, no logging will be done to the standard log for this
client, if the client has the @strong{process} privilege.  This does not
affect the update log!

@item SQL_LOG_UPDATE = 0 | 1
If set to @code{0}, no logging will be done to the update log for the client,
if the client has the @strong{process} privilege.  This does not affect the
standard log!

@item TIMESTAMP = timestamp_value | DEFAULT
Set the time for this client.  This is used to get the original timestamp if
you use the update log to restore rows.

@item LAST_INSERT_ID = #
Set the value to be returned from @code{LAST_INSERT_ID()}. This is stored in
the update log when you use @code{LAST_INSERT_ID()} in a command that updates
a table.

@item INSERT_ID = #
Set the value to be used by the following @code{INSERT} command when inserting
an @code{AUTO_INCREMENT} value.  This is mainly used with the update log.
@end table

@findex GRANT
@findex REVOKE
@node GRANT, CREATE INDEX, SET OPTION, Reference
@section @code{GRANT} and @code{REVOKE} syntax

@example
GRANT priv_type [(column_list)] [, priv_type [(column_list)] ...]
    ON @{tbl_name | * | *.* | db_name.*@}
    TO user_name [IDENTIFIED BY 'password']
        [, user_name [IDENTIFIED BY 'password'] ...]
    [WITH GRANT OPTION]

REVOKE priv_type [(column_list)] [, priv_type [(column_list)] ...]
    ON @{tbl_name | * | *.* | db_name.*@}
    FROM user_name [, user_name ...]
@end example

@code{GRANT} is implemented in @strong{MySQL} 3.22.11 or later. For
earlier @strong{MySQL} versions, the @code{GRANT} statement does nothing.

The @code{GRANT} and @code{REVOKE} commands allow system administrators to
grant and revoke rights to @strong{MySQL} users at four privilege levels:

@table @strong
@item Global level
Global privileges apply to all databases on a given server. These privileges
are stored in the @code{mysql.user} table.

@item Database level
Database privileges apply to all tables in a given database. These privileges
are stored in the @code{mysql.db} and @code{mysql.host} tables.

@item Table level
Table privileges apply to all columns in a given table. These privileges are
stored in the @code{mysql.tables_priv} table.

@item Column level
Column privileges apply to single columns in a given table. These privileges are
stored in the @code{mysql.columns_priv} table.
@end table

For examples of how @code{GRANT} works, see @ref{Adding users}.

For the @code{GRANT} and @code{REVOKE} statements, @code{priv_type} may be
specified as any of the following:

@example
ALL PRIVILEGES      FILE                RELOAD
ALTER               INDEX               SELECT
CREATE              INSERT              SHUTDOWN
DELETE              PROCESS             UPDATE
DROP                REFERENCES          USAGE
@end example

@code{ALL} is a synonym for @code{ALL PRIVILEGES}.  @code{REFERENCES} is not
yet implemented.  @code{USAGE} is currently a synonym for ``no privileges''.
It can be used when you want to create a user that has no privileges.

To revoke the @strong{grant} privilege from a user, use a @code{priv_type}
value of @code{GRANT OPTION}:

@example
REVOKE GRANT OPTION ON ... FROM ...;
@end example

The only @code{priv_type} values you can specify for a table are @code{SELECT},
@code{INSERT}, @code{UPDATE}, @code{DELETE}, @code{CREATE}, @code{DROP},
@code{GRANT}, @code{INDEX} and @code{ALTER}.

The only @code{priv_type} values you can specify for a column (that is, when
you use a @code{column_list} clause) are @code{SELECT}, @code{INSERT} and
@code{UPDATE}.

You can set global privileges by using @code{ON *.*} syntax.  You can set
database privileges by using @code{ON db_name.*} syntax. If you specify
@code{ON *} and you have a current database, you will set the privileges for
that database.  (@strong{Warning:} If you specify @code{ON *} and you
@emph{don't} have a current database, you will affect the global privileges!)

In order to accommodate granting rights to users from arbitrary hosts,
@strong{MySQL} supports specifying the @code{user_name} value in the form
@code{user@@host}.  If you want to specify a @code{user} string
containing special characters (such as @samp{-}), or a @code{host} string
containing special characters or wildcard characters (such as @samp{%}), you
can quote the user or host name (e.g., @code{'test-user'@@'test-hostname'}).

You can specify wildcards in the hostname.  For example,
@code{user@@"%.loc.gov"} applies to @code{user} for any host in the
@code{loc.gov} domain, and @code{user@@"144.155.166.%"} applies to @code{user}
for any host in the @code{144.155.166} class C subnet.

The simple form @code{user} is a synonym for @code{user@@"%"}.
@strong{Note:} If you allow anonymous users to connect to the @strong{MySQL}
server (which is the default), you should also add all local users as
@code{user@@localhost} because otherwise the anonymous user entry for the
local host in the @code{mysql.user} table will be used when the user tries to
log into the @strong{MySQL} server from the local machine!  Anonymous users
are defined by inserting entries with @code{User=''} into the
@code{mysql.user} table. You can verify if this applies to you by executing
this query:

@example
mysql> SELECT Host,User FROM mysql.user WHERE User='';
@end example

For the moment, @code{GRANT} only supports host, table, database and
column names up to 60 characters long. A user name can be up to 16
characters.

The privileges for a table or column are formed from the
logical OR of the privileges at each of the four privilege
levels.  For example, if the @code{mysql.user} table specifies that a
user has a global @strong{select} privilege, this can't be denied by an
entry at the database, table or column level.

The privileges for a column can be calculated as follows:

@example
global privileges
OR (database privileges AND host privileges)
OR table privileges
OR column privileges
@end example

In most cases, you grant rights to a user at only one of the privilege
levels, so life isn't normally as complicated as above. :) The details of the
privilege-checking procedure are presented in
@ref{Privilege system}.

If you grant privileges for a user/hostname combination that does not exist
in the @code{mysql.user} table, an entry is added and remains there until
deleted with a @code{DELETE} command.  In other words, @code{GRANT} may
create @code{user} table entries, but @code{REVOKE} will not remove them;
you must do that explicitly using @code{DELETE}.

@cindex Passwords, setting
In @strong{MySQL} 3.22.12 or later,
if a new user is created or if you have global grant privileges, the user's
password will be set to the password specified by the @code{IDENTIFIED BY}
clause, if one is given.  If the user already had a password, it is replaced
by the new one.

@strong{Warning:} If you create a new user but do not specify an
@code{IDENTIFIED BY} clause, the user has no password.  This is insecure.

Passwords can also be set with the @code{SET PASSWORD} command.
@xref{SET OPTION, , @code{SET OPTION}}.

If you grant privileges for a database, an entry in the @code{mysql.db}
table is created if needed. When all privileges for the database have been
removed with @code{REVOKE}, this entry is deleted.

If a user doesn't have any privileges on a table, the table is not displayed
when the user requests a list of tables (e.g., with a @code{SHOW TABLES}
statement).

The @code{WITH GRANT OPTION} clause gives the user the ability to give
to other users any privileges the user has at the specified privilege level.
You should be careful to whom you give the @strong{grant} privilege, as two
users with different privileges may be able to join privileges!

You cannot grant another user a privilege you don't have yourself;
the @strong{grant} privilege allows you to give away only those privileges
you possess.

Be aware that when you grant a user the @strong{grant} privilege at a
particular privilege level, any privileges the user already possesses (or
is given in the future!) at that level are also grantable by that user.
Suppose you grant a user the @strong{insert} privilege on a database.  If
you then grant the @strong{select} privilege on the database and specify
@code{WITH GRANT OPTION}, the user can give away not only the @strong{select}
privilege, but also @strong{insert}.  If you then grant the @strong{update}
privilege to the user on the database, the user can give away the
@strong{insert}, @strong{select} and @strong{update}.

You should not grant @strong{alter} privileges to a normal user.  If you
do that, the user can try to subvert the privilege system by renaming
tables!

Note that if you are using table or column privileges for even one user, the
server examines table and column privileges for all users and this will slow
down @strong{MySQL} a bit.

When @code{mysqld} starts, all privileges are read into memory.
Database, table and column privileges take effect at once and
user-level privileges take effect the next time the user connects.
Modifications to the grant tables that you perform using @code{GRANT} or
@code{REVOKE} are noticed by the server immediately.
If you modify the grant tables manually (using @code{INSERT}, @code{UPDATE},
etc.), you should execute a @code{FLUSH PRIVILEGES} statement or run
@code{mysqladmin flush-privileges} to tell the server to reload the grant
tables.
@xref{Privilege changes}.

@cindex ANSI SQL, differences from
The biggest differences between the ANSI SQL and @strong{MySQL} versions of
@code{GRANT} are:

@itemize @bullet
@item
ANSI SQL doesn't have global or database-level privileges and ANSI SQL
doesn't support all privilege types that @strong{MySQL} supports.

@item
When you drop a table in ANSI SQL, all privileges for the table are revoked.
If you revoke a privilege in ANSI SQL, all privileges that were granted based
on this privilege are also revoked. In @strong{MySQL}, privileges can be
dropped only with explicit @code{REVOKE} commands or by manipulating the
@strong{MySQL} grant tables.
@end itemize

@cindex Indexes
@cindex Indexes, multi-part
@cindex Multi-part index
@findex CREATE INDEX
@node CREATE INDEX, DROP INDEX, GRANT, Reference
@section @code{CREATE INDEX} syntax

@example
CREATE [UNIQUE] INDEX index_name ON tbl_name (col_name[(length]),... )
@end example

The @code{CREATE INDEX} statement doesn't do anything in @strong{MySQL} prior
to version 3.22.  In 3.22 or later, @code{CREATE INDEX} is mapped to an
@code{ALTER TABLE} statement to create indexes.
@xref{ALTER TABLE, , @code{ALTER TABLE}}.

Normally, you create all indexes on a table at the time the table itself
is created with @code{CREATE TABLE}.
@xref{CREATE TABLE, , @code{CREATE TABLE}}.
@code{CREATE INDEX} allows you to add indexes to existing tables.

A column list of the form @code{(col1,col2,...)} creates a multiple-column
index.  Index values are formed by concatenating the values of the given
columns.

For @code{CHAR} and @code{VARCHAR} columns, indexes can be created that
use only part of a column, using @code{col_name(length)} syntax.  The
statement shown below creates an index using the first 10 characters
of the @code{name} column:

@example
mysql> CREATE INDEX part_of_name ON customer (name(10));
@end example

Since most names usually differ in the first 10 characters, this index should
not be much slower than an index created from the entire @code{name} column.
Also, using partial columns for indexes can make the index file much smaller,
which could save a lot of disk space and might also speed up @code{INSERT}
operations!

For more information about how @strong{MySQL} uses indexes, see
@ref{MySQL indexes, , @strong{MySQL} indexes}.

@findex DROP INDEX
@node DROP INDEX, Comments, CREATE INDEX, Reference
@section @code{DROP INDEX} syntax

@example
DROP INDEX index_name
@end example

@code{DROP INDEX} doesn't do anything in @strong{MySQL} prior to version
3.22.  In 3.22 or later, @code{DROP INDEX} is mapped to an @code{ALTER TABLE}
statement to drop the index.
@xref{ALTER TABLE, , @code{ALTER TABLE}}.

@findex Comment syntax
@node Comments, CREATE FUNCTION, DROP INDEX, Reference
@section Comment syntax

The @strong{MySQL} server supports the @code{# to end of line} and @code{/*
in-line or multiple-line */} comment styles:

@example
mysql> select 1+1;     # This comment continues to the end of line
mysql> select 1 /* this is an in-line comment */ + 1;
mysql> select 1+
/*
this is a
multiple-line comment
*/
1;
@end example

Although the server understands the comment syntax just described,
there are some limitations on the way that the @code{mysql} client
parses @code{/* ... */} comments:

@itemize @bullet
@item
Single-quote and double-quote characters are taken to indicate the beginning
of a quoted string, even within a comment.  If the quote is not matched by a
second quote within the comment, the parser doesn't realize the comment has
ended.  If you are running @code{mysql} interactively, you can tell that it
has gotten confused like this because the prompt changes from @code{mysql>}
to @code{'>} or @code{">}.

@item
A semicolon is taken to indicate the end of the current SQL statement
and anything following it to indicate the beginning of the next statement.
@end itemize

These limitations apply both when you run @code{mysql} interactively
and when you put commands in a file and tell @code{mysql} to read its
input from that file with @code{mysql < some-file}.

@strong{MySQL} doesn't support the @samp{--} ANSI SQL comment style.
@xref{Missing comments}.

@findex CREATE FUNCTION
@findex DROP FUNCTION
@findex UDF functions
@findex User-defined functions
@findex Functions, user-defined
@node CREATE FUNCTION, Reserved words, Comments, Reference
@section @code{CREATE FUNCTION/DROP FUNCTION} syntax

@example
CREATE FUNCTION function_name RETURNS @{STRING|REAL|INTEGER@}
       SONAME shared_library_name

DROP FUNCTION function_name
@end example

A user-definable function (UDF) is a way to extend @strong{MySQL} with a new
function that works like native (built in) @strong{MySQL} functions such as
@code{ABS()} and @code{CONCAT()}.

@code{CREATE FUNCTION} saves the function's name, type and shared library
name in the @code{mysql.func} system table.  You must have the
@strong{insert} and @strong{delete} privileges for the @code{mysql} database
to create and drop functions.

All active functions are reloaded each time the server starts, unless
you start @code{mysqld} with the @code{--skip-grant-tables} option.  In
this case, UDF initialization is skipped and UDFs are unavailable.
(An active function is one that has been loaded with @code{CREATE FUNCTION}
and not removed with @code{DROP FUNCTION}.)

For instructions on writing user-definable functions, see @ref{Adding
functions}.  For the UDF mechanism to work, functions must be written in C or
C++ and your operating system must support dynamic loading.

@cindex Keywords
@cindex Reserved words
@cindex Reserved words, exceptions
@node Reserved words,  , CREATE FUNCTION, Reference
@section Is @strong{MySQL} picky about reserved words?

A common problem stems from trying to create a table with column names that
use the names of datatypes or functions built into @strong{MySQL}, such as
@code{TIMESTAMP} or @code{GROUP}.  You're allowed to do it (for example,
@code{ABS} is an allowed column name), but whitespace is not allowed between
a function name and the @samp{(} when using functions whose names are also
column names.

The following words are explicitly reserved in @strong{MySQL}. Most of
them are forbidden by ANSI SQL92 as column and/or table names
(for example, @code{group}).
A few are reserved because @strong{MySQL} needs them and is
(currently) using a @code{yacc} parser:

@multitable @columnfractions .25 .25 .25 .25
@c This is fixed by including the symbols table from sql_lex.cc here and then running
@c fix-mysql-reserved-words in emacs (or let David do it): 
@c (defun fix-mysql-reserved-words ()
@c   (interactive)
@c   (let ((cnt 0))
@c     (insert "\n@item ")
@c     (while (looking-at " *{ +\"\\([^\"]+\\)\",.*\n")
@c       (replace-match "@code{\\1}")
@c       (incf cnt)
@c       (if (> cnt 3)
@c 	  (progn
@c 	    (setf cnt 0)
@c 	    (insert "\n@item "))
@c 	(insert " @tab ")))))
@c But remove the non alphanumeric entries by hand first.
@item @code{action} @tab @code{add} @tab @code{all} @tab @code{alter}
@item @code{after} @tab @code{and} @tab @code{as} @tab @code{asc}
@item @code{auto_increment} @tab @code{between} @tab @code{bigint} @tab @code{bit}
@item @code{binary} @tab @code{blob} @tab @code{bool} @tab @code{both}
@item @code{by} @tab @code{cascade} @tab @code{char} @tab @code{character}
@item @code{change} @tab @code{check} @tab @code{column} @tab @code{columns}
@item @code{constraint} @tab @code{create} @tab @code{cross} @tab @code{current_date}
@item @code{current_time} @tab @code{current_timestamp} @tab @code{data} @tab @code{database}
@item @code{databases} @tab @code{date} @tab @code{datetime} @tab @code{day}
@item @code{day_hour} @tab @code{day_minute} @tab @code{day_second} @tab @code{dayofmonth}
@item @code{dayofweek} @tab @code{dayofyear} @tab @code{dec} @tab @code{decimal}
@item @code{default} @tab @code{delete} @tab @code{desc} @tab @code{describe}
@item @code{distinct} @tab @code{distinctrow} @tab @code{double} @tab @code{drop}
@item @code{escaped} @tab @code{enclosed} @tab @code{enum} @tab @code{explain}
@item @code{exists} @tab @code{fields} @tab @code{first} @tab @code{float}
@item @code{float4} @tab @code{float8} @tab @code{foreign} @tab @code{from}
@item @code{for} @tab @code{full} @tab @code{function} @tab @code{grant}
@item @code{group} @tab @code{having} @tab @code{hour} @tab @code{hour_minute}
@item @code{hour_second} @tab @code{ignore} @tab @code{in} @tab @code{index}
@item @code{infile} @tab @code{insert} @tab @code{int} @tab @code{integer}
@item @code{interval} @tab @code{int1} @tab @code{int2} @tab @code{int3}
@item @code{int4} @tab @code{int8} @tab @code{into} @tab @code{if}
@item @code{is} @tab @code{join} @tab @code{key} @tab @code{keys}
@item @code{last_insert_id} @tab @code{leading} @tab @code{left} @tab @code{like}
@item @code{lines} @tab @code{limit} @tab @code{load} @tab @code{lock}
@item @code{long} @tab @code{longblob} @tab @code{longtext} @tab @code{low_priority}
@item @code{match} @tab @code{mediumblob} @tab @code{mediumtext} @tab @code{mediumint}
@item @code{middleint} @tab @code{minute} @tab @code{minute_second} @tab @code{month}
@item @code{monthname} @tab @code{natural} @tab @code{numeric} @tab @code{no}
@item @code{not} @tab @code{null} @tab @code{on} @tab @code{option}
@item @code{optionally} @tab @code{or} @tab @code{order} @tab @code{outer}
@item @code{outfile} @tab @code{partial} @tab @code{password} @tab @code{precision}
@item @code{primary} @tab @code{procedure} @tab @code{processlist} @tab @code{privileges}
@item @code{quarter} @tab @code{read} @tab @code{real} @tab @code{references}
@item @code{rename} @tab @code{regexp} @tab @code{reverse} @tab @code{repeat}
@item @code{replace} @tab @code{restrict} @tab @code{returns} @tab @code{rlike}
@item @code{second} @tab @code{select} @tab @code{set} @tab @code{show}
@item @code{smallint} @tab @code{soname} @tab @code{sql_big_tables} @tab @code{sql_big_selects}
@item @code{sql_select_limit} @tab @code{sql_low_priority_updates} @tab @code{sql_log_off} @tab @code{sql_log_update}
@item @code{straight_join} @tab @code{starting} @tab @code{status} @tab @code{string}
@item @code{table} @tab @code{tables} @tab @code{terminated} @tab @code{text}
@item @code{time} @tab @code{timestamp} @tab @code{tinyblob} @tab @code{tinytext}
@item @code{tinyint} @tab @code{trailing} @tab @code{to} @tab @code{use}
@item @code{using} @tab @code{unique} @tab @code{unlock} @tab @code{unsigned}
@item @code{update} @tab @code{usage} @tab @code{values} @tab @code{varchar}
@item @code{variables} @tab @code{varying} @tab @code{varbinary} @tab @code{with}
@item @code{write} @tab @code{where} @tab @code{year} @tab @code{year_month}
@item @code{zerofill}
@end multitable

The following symbols (from the table above) are disallowed by ANSI SQL
but allowed by @strong{MySQL} as column/table names. This is because some
of these names are very natural names and a lot of people have already
used them.

@itemize @bullet
@item @code{ACTION}
@item @code{BIT}
@item @code{DATE}
@item @code{ENUM}
@item @code{NO}
@item @code{TEXT}
@item @code{TIME}
@item @code{TIMESTAMP}
@end itemize

@node Tutorial, Server, Reference, Top
@chapter @strong{MySQL} Tutorial

@menu
* Connecting-disconnecting::    Connecting to and disconnecting from the server
* Entering queries::            Entering queries
* Database use::                Creating and using a database
* Getting information::         Getting information about databases and tables
* Batch mode::                  Using @code{mysql} in batch mode
* Twin::                        Queries from twin project
@end menu

This chapter provides a tutorial introduction to @strong{MySQL} by showing
how to use the @code{mysql} client program to create and use a simple
database.  @code{mysql} (sometimes referred to as the ``terminal monitor'' or
just ``monitor'') is an interactive program that allows you to connect to a
@strong{MySQL} server, run queries and view the results.  @code{mysql} may
also be used in batch mode: you place your queries in a file beforehand, then
tell @code{mysql} to execute the contents of the file.  Both ways of using
@code{mysql} are covered here.

To see a list of options provided by @code{mysql}, invoke it with
the @code{--help} option:

@example
shell> mysql --help
@end example

This chapter assumes that @code{mysql} is installed on your machine, and that
a @strong{MySQL} server is available to which you can connect.  If this is
not true, contact your @strong{MySQL} administrator.  (If @emph{you} are the
administrator, you will need to consult other sections of this manual.)

The chapter describes the entire process of setting up and using a
database.  If you are interested only in accessing an already-existing
database, you may want to skip over the sections that describe how to
create the database and the tables it contains.

Since this chapter is tutorial in nature, many details are necessarily left
out.  Consult the relevant sections of the manual for more
information on the topics covered here.

@node Connecting-disconnecting, Entering queries, Tutorial, Tutorial
@section Connecting to and disconnecting from the server

To connect to the server, you'll usually need to provide a @strong{MySQL}
user name when you invoke @code{mysql} and, most likely, a password.  If the
server runs on a machine other than the one where you log in, you'll also
need to specify a hostname.  Contact your administrator to find out what
connection parameters you should use to connect (i.e., what host, user name
and password to use).  Once you know the proper parameters, you should be
able to connect like this:

@example
shell> mysql -h host -u user -p
Enter password: ********
@end example

The @code{********} represents your password; enter it when @code{mysql}
displays the @code{Enter password:} prompt.

If that works, you should see some introductory information followed by a
@code{mysql>} prompt:


@example
shell> mysql -h host -u user -p
Enter password: ********
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 459 to server version: 3.22.20a-log

Type 'help' for help.

mysql> 
@end example

The prompt tells you that @code{mysql} is ready for you to enter commands.

Some @strong{MySQL} installations allow users to connect as the ``anonymous''
(unnamed) user to the server running on the local host.  If this is the case
on your machine, you should be able to connect to that server by invoking
@code{mysql} without any options:

@example
shell> mysql
@end example

After you have connected successfully, you can disconnect any time by typing
@code{QUIT} at the @code{mysql>} prompt:

@example
mysql> QUIT
Bye
@end example

You can also disconnect by typing control-D.

Most examples in the following sections assume you are connected to the
server.  They indicate this by the @code{mysql>} prompt.

@node Entering queries, Database use, Connecting-disconnecting, Tutorial
@section Entering queries

Make sure you are connected to the server, as discussed in the previous
section.  Doing so will not in itself select any database to work with, but
that's okay.  At this point, it's more important to find out a little about
how to issue queries than to jump right in creating tables, loading data
into them and retrieving data from them.  This section describes the basic
principles of entering commands, using several queries you can try out to
familiarize yourself with how @code{mysql} works.

Here's a simple command that asks the server to tell you its version number
and the current date.  Type it in as shown below following the @code{mysql>}
prompt and hit the RETURN key:

@example
mysql> SELECT VERSION(), CURRENT_DATE;
+--------------+--------------+
| version()    | CURRENT_DATE |
+--------------+--------------+
| 3.22.20a-log | 1999-03-19   |
+--------------+--------------+
1 row in set (0.01 sec)
mysql>
@end example

This query illustrates several things about @code{mysql}:

@itemize @bullet
@item
A command normally consists of a SQL statement followed by a semicolon.
(There are some exceptions where a semicolon is not needed.  @code{QUIT},
mentioned earlier, is one of them.  We'll get to others later.)

@item
When you issue a command, @code{mysql} sends it to the server for execution
and displays the results, then prints another @code{mysql>} to indicate
that it is ready for another command.

@item
@code{mysql} displays query output as a table (rows and columns).  The first
row contains labels for the columns.  The rows following are the query
results.  Normally, column labels are the names of the columns you fetch from
database tables.  If you're retrieving the value of an expression rather than
a table column (as in the example just shown), @code{mysql} labels the column
using the expression itself.

@item
@code{mysql} shows how many rows were returned, and how long the query took
to execute, which gives you a rough idea of server performance.  These values
are imprecise because they represent wall clock time (not CPU or machine
time), and because they are affected by factors such as server load and
network latency.  (For brevity, the ``rows in set'' line is not shown in
the remaining examples in this chapter.)
@end itemize

Keywords may be entered in any lettercase.  The following queries are
equivalent:

@example
mysql> SELECT VERSION(), CURRENT_DATE;
mysql> select version(), current_date;
mysql> SeLeCt vErSiOn(), current_DATE;
@end example

Here's another query.  It demonstrates that you can use @code{mysql} as a
simple calculator:

@example
mysql> SELECT SIN(PI()/4), (4+1)*5;
+-------------+---------+
| SIN(PI()/4) | (4+1)*5 |
+-------------+---------+
|    0.707107 |      25 |
+-------------+---------+
@end example

The commands shown thus far have been relatively short, single-line
statements.  You can even enter multiple statements on a single line.
Just end each one with a semicolon:

@example
mysql> SELECT VERSION(); SELECT NOW();
+--------------+
| version()    |
+--------------+
| 3.22.20a-log |
+--------------+

+---------------------+
| NOW()               |
+---------------------+
| 1999-03-19 00:15:33 |
+---------------------+
@end example

A command need not be given all on a single line, so lengthy commands that
require several lines are not a problem.  @code{mysql} determines where your
statement ends by looking for the terminating semicolon, not by looking for
the end of the input line.  (In other words, @code{mysql}
accepts free-format input:  it collects input lines but does not execute them
until it sees the semicolon.)

Here's a simple multiple-line statement:

@example
mysql> SELECT
    -> USER()
    -> ,
    -> CURRENT_DATE;
+--------------------+--------------+
| USER()             | CURRENT_DATE |
+--------------------+--------------+
| joesmith@@localhost | 1999-03-18   |
+--------------------+--------------+
@end example

In this example, notice how the prompt changes from @code{mysql>} to
@code{->} after you enter the first line of a multiple-line query.  This is
how @code{mysql} indicates that it hasn't seen a complete statement and is
waiting for the rest.  The prompt is your friend, because it provides
valuable feedback.  If you use that feedback, you will always be aware of
what @code{mysql} is waiting for.

If you decide you don't want to execute a command that you are in the
process of entering, cancel it by typing @code{\c}:

@example
mysql> SELECT
    -> USER()
    -> \c
mysql>
@end example

Here, too, notice the prompt.  It switches back to @code{mysql>} after you
type @code{\c}, providing feedback to indicate that @code{mysql} is ready
for a new command.

The following table shows each of the prompts you may see and summarizes what
they mean about the state that @code{mysql} is in:

@multitable @columnfractions .10 .9
@item @strong{Prompt} @tab @strong{Meaning}
@item @code{mysql>} @tab Ready for new command
@item @code{@ @ @ @ ->} @tab Waiting for next line of multiple-line command
@item @code{@ @ @ @ '>} @tab Waiting for next line, collecting a string that begins
with a single quote (@samp{'})
@item @code{@ @ @ @ ">} @tab Waiting for next line, collecting a string that begins
with a double quote (@samp{"})
@end multitable

Multiple-line statements commonly occur ``by accident'' when you intend to
issue a command on a single line, but forget the terminating semicolon.  In
this case, @code{mysql} waits for more input:

@example
mysql> SELECT USER()
    ->
@end example

If this happens to you (you think you've entered a statement but the only
response is a @code{->} prompt), most likely @code{mysql} is waiting for the
semicolon.  If you don't notice what the prompt is telling you, you might sit
there for a while before realizing what you need to do.  Enter a semicolon to
complete the statement, and @code{mysql} will execute it:

@example
mysql> SELECT USER()
    -> ;
+--------------------+
| USER()             |
+--------------------+
| joesmith@@localhost |
+--------------------+
@end example

The @code{'>} and @code{">} prompts occur during string collection.
In @strong{MySQL}, you can write strings surrounded by either @samp{'}
or @samp{"} characters (for example, @code{'hello'} or @code{"goodbye"}),
and @code{mysql} lets you enter strings that span multiple lines.  When you
see a @code{'>} or @code{">} prompt, it means that you've entered a line
containing a string that begins with a @samp{'} or @samp{"} quote character,
but have not yet entered the matching quote that terminates the string.
That's fine if you really are entering a multiple-line string, but how likely
is that?  Not very.  More often, the @code{'>} and @code{">} prompts indicate
that you've inadvertantly left out a quote character.  For example:

@example
mysql> SELECT * FROM my_table WHERE name = "Smith AND age < 30;
    ">
@end example

If you enter this @code{SELECT} statement, then hit RETURN and wait for the
result, nothing will happen.  Instead of wondering, ``why does this
query take so long?,'' notice the clue provided by the @code{">} prompt.  It
tells you that @code{mysql} expects to see the rest of an unterminated
string.  (Do you see the error in the statement?  The string @code{"Smith} is
missing the second quote.)

At this point, what do you do?  The simplest thing is to cancel the command.
However, you cannot just type @code{\c} in this case, because @code{mysql}
interprets it as part of the string that it is collecting!  Instead, enter
the closing quote character (so @code{mysql} knows you've finished the
string), then type @code{\c}:

@example
mysql> SELECT * FROM my_table WHERE name = "Smith AND age < 30;
    "> "\c
mysql>
@end example

The prompt changes back to @code{mysql>}, indicating that @code{mysql}
is ready for a new command.

It's important to know what the @code{'>} and @code{">} prompts signify,
because if you mistakenly enter an unterminated string, any further lines you
type will appear to be ignored by @code{mysql} --- including a line
containing @code{QUIT}!  This can be quite confusing, especially if you
don't know that you need to supply the terminating quote before you can
cancel the current command.

@node Database use, Getting information, Entering queries, Tutorial
@section Creating and using a database

@menu
* Creating database::           Creating a database
* Creating tables::             Creating a table
* Loading tables::              Loading data into a table
* Retrieving data::             Retrieving information from a table
* Multiple tables::             Using more than one table
@end menu

Now that you know how to enter commands, it's time to access a database.

Suppose you have several pets in your home (your ``menagerie'') and you'd
like to keep track of various types of information about them.  You can do so
by creating tables to hold your data and loading them with the desired
information.  Then you can answer different sorts of questions about your
animals by retrieving data from the tables.  This section shows how to do
all that:

@itemize @bullet
@item
How to create a database
@item
How to create a table
@item
How to load data into the table
@item
How to retrieve data from the table in various ways
@item
How to use multiple tables
@end itemize

The menagerie database will be simple (deliberately), but it is not difficult
to think of real-world situations in which a similar type of database might
be used.  For example, a database like this could be used by a farmer to keep
track of livestock, or by a veterinarian to keep track of patient records.

Use the @code{SHOW} statement to find out what databases currently exist
on the server:

@example
mysql> SHOW DATABASES;
+----------+
| Database |
+----------+
| mysql    |
| test     |
| tmp      |
+----------+
@end example

The list of databases is probably different on your machine, but the
@code{mysql} and @code{test} databases are likely to be among them.  The
@code{mysql} database is required because it describes user access
privileges.  The @code{test} database is often provided as a workspace for
users to try things out.

If the @code{test} database exists, try to access it:

@example
mysql> USE test
Database changed
@end example

Note that @code{USE}, like @code{QUIT}, does not require a semicolon.  (You
can terminate such statements with a semicolon if you like; it does no harm.)
The @code{USE} statement is special in another way, too:  it must be given on
a single line.

You can use the @code{test} database (if you have access to it) for the
examples that follow, but anything you create in that database can be
removed by anyone else with access to it.  For this reason, you should
probably ask your @strong{MySQL} administrator for permission to use a
database of your own.  Suppose you want to call yours @code{menagerie}.  The
administrator needs to execute a command like this:

@example
mysql> GRANT ALL ON menagerie.* TO your_mysql_name;
@end example

where @code{your_mysql_name} is the @strong{MySQL} user name assigned to
you.

@node Creating database, Creating tables, Database use, Database use
@subsection Creating and selecting a database

If the administrator creates your database for you when setting up your
permissions, you can begin using it.  Otherwise, you need to create it
yourself:

@example
mysql> CREATE DATABASE menagerie;
@end example

Under Unix, database names are case sensitive (unlike SQL keywords), so you
must always refer to your database as @code{menagerie}, not as
@code{Menagerie}, @code{MENAGERIE} or some other variant.  This is also true
for table names.  (Under Windows, this restriction does not apply, although
you must refer to databases and tables using the same lettercase throughout a
given query.)

Creating a database does not select it for use, you must do that explicitly.
To make @code{menagerie} the current database, use this command:

@example
mysql> USE menagerie
Database changed
@end example

Your database needs to be created only once, but you must select it for use
each time you begin a @code{mysql} session.  You can do this by issuing a
@code{USE} statement as shown above.  Alternatively, you can select the
database on the command line when you invoke @code{mysql}.  Just specify its
name after any connection parameters that you might need to provide.  For
example:

@example
shell> mysql -h host -u user -p menagerie
Enter password: ********
@end example

Note that @code{menagerie} is not your password on the command just shown.
If you want to supply your password on the command line after the @code{-p}
option, you must do so with no intervening space (e.g., as
@code{-pmypassword}, not as @code{-p mypassword}).  However, putting your
password on the command line is not recommended, because doing so exposes it
to snooping by other users logged in on your machine.

@node Creating tables, Loading tables, Creating database, Database use
@subsection Creating a table

Creating the database is the easy part, but at this point it's empty, as
@code{SHOW TABLES} will tell you:

@example
mysql> SHOW TABLES;
Empty set (0.00 sec)
@end example

The harder part is deciding what the structure of your database should be:
what tables you will need, and what columns will be in each of them.

You'll want a table that contains a record for each of your pets.  This can
be called the @code{pet} table, and it should contain, as a bare minimum,
each animal's name.  Since the name by itself is not very interesting, the
table should contain other information.  For example, if more than one person
in your family keeps pets, you might want to list each animal's owner.  You
might also want to record some basic descriptive information such as species
and sex.

How about age?  That might be of interest, but it's not a good thing to store
in a database.  Age changes as time passes, which means you'd have to update
your records often.  Instead, it's better to store a fixed value such as
date of birth.  Then, whenever you need age, you can calculate it as the
difference between the current date and the birth date.  @strong{MySQL}
provides functions for doing date arithmetic, so this is not difficult.
Storing birth date rather than age has other advantages, too:

@itemize @bullet
@item
You can use the database for tasks such as generating reminders for upcoming
pet birthdays.  (If you think this type of query is somewhat silly, note that
it is the same question you might ask in the context of a business database
to identify clients to whom you'll soon need to send out birthday greetings,
for that computer-assisted personal touch.)

@item
You can calculate age in relation to dates other than the current date.  For
example, if you store death date in the database, you can easily calculate
how old a pet was when it died.
@end itemize

You can probably think of other types of information that would be useful in
the @code{pet} table, but the ones identified so far are sufficient for now:
name, owner, species, sex, birth and death.

Use a @code{CREATE TABLE} statement to specify the layout of your table:

@example
mysql> CREATE TABLE pet (name VARCHAR(20), owner VARCHAR(20),
    -> species VARCHAR(20), sex CHAR(1), birth DATE, death DATE);
@end example

@code{VARCHAR} is a good choice for the @code{name}, @code{owner} and
@code{species} columns since the column values will vary in length.  The
lengths of those columns need not all be the same, and need not be
@code{20}.  You can pick any length from @code{1} to @code{255}, whatever
seems most reasonable to you.  (If you make a poor choice and it turns
out later that you need a longer field, @strong{MySQL} provides an
@code{ALTER TABLE} statement.)

Animal sex can be represented in a variety of ways, for example, @code{"m"}
and @code{"f"}, or perhaps @code{"male"} and @code{"female"}.  It's simplest
to use the single characters @code{"m"} and @code{"f"}.

The use of the @code{DATE} data type for the @code{birth} and @code{death}
columns is a fairly obvious choice.

Now that you have created a table, @code{SHOW TABLES} should produce some
output:

@example
mysql> SHOW TABLES;
+---------------------+
| Tables in menagerie |
+---------------------+
| pet                 |
+---------------------+
@end example

To verify that your table was created the way you expected, use
a @code{DESCRIBE} statement:

@example
mysql> DESCRIBE pet;
+---------+-------------+------+-----+---------+-------+
| Field   | Type        | Null | Key | Default | Extra |
+---------+-------------+------+-----+---------+-------+
| name    | varchar(20) | YES  |     | NULL    |       |
| owner   | varchar(20) | YES  |     | NULL    |       |
| species | varchar(20) | YES  |     | NULL    |       |
| sex     | char(1)     | YES  |     | NULL    |       |
| birth   | date        | YES  |     | NULL    |       |
| death   | date        | YES  |     | NULL    |       |
+---------+-------------+------+-----+---------+-------+
@end example

You can use @code{DESCRIBE} any time, for example, if you forget the names of
the columns in your table or what types they are.

@node Loading tables, Retrieving data, Creating tables, Database use
@subsection Loading data into a table

After creating your table, you need to populate it.  The @code{LOAD DATA} and
@code{INSERT} statements are useful for this.

Suppose your pet records can be described as shown below.
(Observe that @strong{MySQL} expects dates in @code{YYYY-MM-DD} format;
this may be different than what you are used to.)

@multitable @columnfractions .16 .16 .16 .16 .16 .16
@item @strong{name} @tab @strong{owner} @tab @strong{species} @tab @strong{sex} @tab @strong{birth} @tab @strong{death}
@item Fluffy @tab Harold @tab cat @tab f @tab 1993-02-04 @tab
@item Claws @tab Gwen @tab cat @tab m @tab 1994-03-17 @tab
@item Buffy @tab Harold @tab dog @tab f @tab 1989-05-13 @tab
@item Fang @tab Benny @tab dog @tab m @tab 1990-08-27 @tab
@item Bowser @tab Diane @tab dog @tab m @tab 1998-08-31 @tab 1995-07-29
@item Chirpy @tab Gwen @tab bird @tab f @tab 1998-09-11 @tab
@item Whistler @tab Gwen @tab bird @tab @tab 1997-12-09 @tab
@item Slim @tab Benny @tab snake @tab m @tab 1996-04-29 @tab
@end multitable

Since you are beginning with an empty table, an easy way to populate it is to
create a text file containing a row for each of your animals, then load the
contents of the file into the table with a single statement.

You could create a text file @file{pet.txt} containing one record per line,
with values separated by tabs, and given in the order in which the columns
were listed in the @code{CREATE TABLE} statement.  For missing values (such
as unknown sexes, or death dates for animals that are still living), you can
use @code{NULL} values.  To represent these in your text file, use
@code{\N}.  For example, the record for Whistler the bird would look like
this (where the whitespace between values is a single tab character):

@multitable @columnfractions .15 .15 .15 .15 .25 .15
@item @code{Whistler} @tab @code{Gwen} @tab @code{bird} @tab @code{\N} @tab @code{1997-12-09} @tab @code{\N}
@end multitable

To load the text file @file{pet.txt} into the @code{pet} table, use this
command:

@example
mysql> LOAD DATA LOCAL INFILE "pet.txt" INTO TABLE pet;
@end example

You can specify the column value separator and end of line marker explicitly
in the @code{LOAD DATA} statement if you wish, but the defaults are tab and
linefeed.  These are sufficient for the statement to read the file
@file{pet.txt} properly.

When you want to add new records one at a time, the @code{INSERT} statement
is useful.  In its simplest form, you supply values for each column, in the
order in which the columns were listed in the @code{CREATE TABLE} statement.
Suppose Diane gets a new hamster named Puffball.  You could add a new record
using an @code{INSERT} statement like this:

@example
mysql> INSERT INTO pet
    -> VALUES ('Puffball','Diane','hamster','f','1999-03-30',NULL);
@end example

Note that string and date values are specified as quoted strings here.  Also,
with @code{INSERT}, you can insert @code{NULL} directly to represent a
missing value.  You do not use @code{\N} like you do with @code{LOAD DATA}.

From this example, you should be able to see that there would be a lot more
typing involved to load
your records initially using several @code{INSERT} statements rather
than a single @code{LOAD DATA} statement.

@node Retrieving data, Multiple tables, Loading tables, Database use
@subsection Retrieving information from a table

@menu
* Selecting all::               Selecting all data
* Selecting rows::              Selecting particular rows
* Selecting columns::           Selecting particular columns
* Sorting rows::                Sorting rows
* Date calculations::           Date calculations
* Working with NULL::           Working with @code{NULL} values
* Pattern matching::            Pattern matching
* Counting rows::               Counting rows
@end menu

The @code{SELECT} statement is used to pull information from a table.
The general form of the statement is:

@example
SELECT what_to_select
FROM which_table
WHERE conditions_to_satisfy
@end example

@code{what_to_select} indicates what you want to see.  This can be a list of
columns, or @code{*} to to indicate ``all columns.'' @code{which_table}
indicates the table from which you want to retrieve data.  The @code{WHERE}
clause is optional.  If it's present, @code{conditions_to_satisfy} specifies
conditions that rows must satisfy to qualify for retrieval.

@node Selecting all, Selecting rows, Retrieving data, Retrieving data
@subsubsection Selecting all data

The simplest form of @code{SELECT} retrieves everything from a table:

@example
mysql> SELECT * FROM pet;
+----------+--------+---------+------+------------+------------+
| name     | owner  | species | sex  | birth      | death      |
+----------+--------+---------+------+------------+------------+
| Fluffy   | Harold | cat     | f    | 1993-02-04 | NULL       |
| Claws    | Gwen   | cat     | m    | 1994-03-17 | NULL       |
| Buffy    | Harold | dog     | f    | 1989-05-13 | NULL       |
| Fang     | Benny  | dog     | m    | 1990-08-27 | NULL       |
| Bowser   | Diane  | dog     | m    | 1998-08-31 | 1995-07-29 |
| Chirpy   | Gwen   | bird    | f    | 1998-09-11 | NULL       |
| Whistler | Gwen   | bird    | NULL | 1997-12-09 | NULL       |
| Slim     | Benny  | snake   | m    | 1996-04-29 | NULL       |
| Puffball | Diane  | hamster | f    | 1999-03-30 | NULL       |
+----------+--------+---------+------+------------+------------+
@end example

This form of @code{SELECT} is useful if you want to review your entire table,
for instance, after you've just loaded it with your initial dataset.  As it
happens, the output just shown reveals an error in your data file:  Bowser
appears to have been born after he died!  Consulting your original pedigree
papers, you find that the correct birth year is 1989, not 1998.

There are are least a couple of ways to fix this:

@itemize @bullet
@item
Edit the file @file{pet.txt} to correct the error, then empty the table
and reload it using @code{DELETE} and @code{LOAD DATA}:

@example
mysql> DELETE FROM pet;
mysql> LOAD DATA LOCAL INFILE "pet.txt" INTO TABLE pet;
@end example

However, if you do this, you must also re-enter the record for Puffball.

@item
Fix only the erroneous record with an @code{UPDATE} statement:

@example
mysql> UPDATE pet SET birth = "1989-08-31" WHERE name = "Bowser";
@end example
@end itemize

As shown above, it is easy to retrieve an entire table.  But typically you
don't want to do that, particularly when the table becomes large.  Instead,
you're usually more interested in answering a particular question, in which
case you specify some constraints on the information you want.  Let's look at
some selection queries in terms of questions about your pets that they
answer.

@node Selecting rows, Selecting columns, Selecting all, Retrieving data
@subsubsection Selecting particular rows

You can select only particular rows from your table.  For example, if you want
to verify the change that you made to Bowser's birth date, select Bowser's
record like this:

@example
mysql> SELECT * FROM pet WHERE name = "Bowser";
+--------+-------+---------+------+------------+------------+
| name   | owner | species | sex  | birth      | death      |
+--------+-------+---------+------+------------+------------+
| Bowser | Diane | dog     | m    | 1989-08-31 | 1995-07-29 |
+--------+-------+---------+------+------------+------------+
@end example

The output confirms that the year is correctly recorded now as 1989, not 1998.

String comparisons are normally case-insensitive, so you can specify the
name as @code{"bowser"}, @code{"BOWSER"}, etc.  The query result will be
the same.

You can specify conditions on any column, not just @code{name}.  For example,
if you want to know which animals were born after 1998, test the @code{birth}
column:

@example
mysql> SELECT * FROM pet WHERE birth >= "1998-1-1";
+----------+-------+---------+------+------------+-------+
| name     | owner | species | sex  | birth      | death |
+----------+-------+---------+------+------------+-------+
| Chirpy   | Gwen  | bird    | f    | 1998-09-11 | NULL  |
| Puffball | Diane | hamster | f    | 1999-03-30 | NULL  |
+----------+-------+---------+------+------------+-------+
@end example

You can combine conditions, for example, to locate female dogs:

@example
mysql> SELECT * FROM pet WHERE species = "dog" AND sex = "f";
+-------+--------+---------+------+------------+-------+
| name  | owner  | species | sex  | birth      | death |
+-------+--------+---------+------+------------+-------+
| Buffy | Harold | dog     | f    | 1989-05-13 | NULL  |
+-------+--------+---------+------+------------+-------+
@end example

The preceding query uses the @code{AND} logical operator.  There is also an
@code{OR} operator:

@example
mysql> SELECT * FROM pet WHERE species = "snake" OR species = "bird";
+----------+-------+---------+------+------------+-------+
| name     | owner | species | sex  | birth      | death |
+----------+-------+---------+------+------------+-------+
| Chirpy   | Gwen  | bird    | f    | 1998-09-11 | NULL  |
| Whistler | Gwen  | bird    | NULL | 1997-12-09 | NULL  |
| Slim     | Benny | snake   | m    | 1996-04-29 | NULL  |
+----------+-------+---------+------+------------+-------+
@end example

@code{AND} and @code{OR} may be intermixed.  If you do that, it's a good idea
to use parentheses to indicate how conditions should be grouped:

@example
mysql> SELECT * FROM pet WHERE (species = "cat" AND sex = "m")
    -> OR (species = "dog" AND sex = "f");
+-------+--------+---------+------+------------+-------+
| name  | owner  | species | sex  | birth      | death |
+-------+--------+---------+------+------------+-------+
| Claws | Gwen   | cat     | m    | 1994-03-17 | NULL  |
| Buffy | Harold | dog     | f    | 1989-05-13 | NULL  |
+-------+--------+---------+------+------------+-------+
@end example

@node Selecting columns, Sorting rows, Selecting rows, Retrieving data
@subsubsection Selecting particular columns


If you don't want to see entire rows from your table, just name the columns
in which you're interested, separated by commas.  For example, if you want to
know when your animals were born, select the @code{name} and @code{birth}
columns:

@example
mysql> SELECT name, birth FROM pet;
+----------+------------+
| name     | birth      |
+----------+------------+
| Fluffy   | 1993-02-04 |
| Claws    | 1994-03-17 |
| Buffy    | 1989-05-13 |
| Fang     | 1990-08-27 |
| Bowser   | 1989-08-31 |
| Chirpy   | 1998-09-11 |
| Whistler | 1997-12-09 |
| Slim     | 1996-04-29 |
| Puffball | 1999-03-30 |
+----------+------------+
@end example

To find out who owns pets, use this query:

@example
mysql> SELECT owner FROM pet;
+--------+
| owner  |
+--------+
| Harold |
| Gwen   |
| Harold |
| Benny  |
| Diane  |
| Gwen   |
| Gwen   |
| Benny  |
| Diane  |
+--------+
@end example

However, notice that the query simply retrieves the @code{owner} field from
each record, and some of them appear more than once.  To minimize the output,
retrieve each unique output record just once by adding the keyword
@code{DISTINCT}:

@example
mysql> SELECT DISTINCT owner FROM pet;
+--------+
| owner  |
+--------+
| Benny  |
| Diane  |
| Gwen   |
| Harold |
+--------+
@end example

You can use a @code{WHERE} clause to combine row selection with column
selection.  For example, to get birth dates for dogs and cats only,
use this query:

@example
mysql> SELECT name, species, birth FROM pet
    -> WHERE species = "dog" OR species = "cat";
+--------+---------+------------+
| name   | species | birth      |
+--------+---------+------------+
| Fluffy | cat     | 1993-02-04 |
| Claws  | cat     | 1994-03-17 |
| Buffy  | dog     | 1989-05-13 |
| Fang   | dog     | 1990-08-27 |
| Bowser | dog     | 1989-08-31 |
+--------+---------+------------+
@end example

@node Sorting rows, Date calculations, Selecting columns, Retrieving data
@subsubsection Sorting rows

You may have noticed in the preceding examples that the result rows are
displayed in no particular order.  However, it's often easier to examine
query output when the rows are sorted in some meaningful way.  To sort a
result, use an @code{ORDER BY} clause.

Here are animal birthdays, sorted by date:

@example
mysql> SELECT name, birth FROM pet ORDER BY birth;
+----------+------------+
| name     | birth      |
+----------+------------+
| Buffy    | 1989-05-13 |
| Bowser   | 1989-08-31 |
| Fang     | 1990-08-27 |
| Fluffy   | 1993-02-04 |
| Claws    | 1994-03-17 |
| Slim     | 1996-04-29 |
| Whistler | 1997-12-09 |
| Chirpy   | 1998-09-11 |
| Puffball | 1999-03-30 |
+----------+------------+
@end example

To sort in reverse order, add the @code{DESC} (descending) keyword to the
name of the column you are sorting by:

@example
mysql> SELECT name, birth FROM pet ORDER BY birth DESC;
+----------+------------+
| name     | birth      |
+----------+------------+
| Puffball | 1999-03-30 |
| Chirpy   | 1998-09-11 |
| Whistler | 1997-12-09 |
| Slim     | 1996-04-29 |
| Claws    | 1994-03-17 |
| Fluffy   | 1993-02-04 |
| Fang     | 1990-08-27 |
| Bowser   | 1989-08-31 |
| Buffy    | 1989-05-13 |
+----------+------------+
@end example

You can sort on multiple columns.  For example, to sort by type of
animal, then by birth date within animal type with youngest animals first,
use the following query:

@example
mysql> SELECT name, species, birth FROM pet ORDER BY species, birth DESC;
+----------+---------+------------+
| name     | species | birth      |
+----------+---------+------------+
| Chirpy   | bird    | 1998-09-11 |
| Whistler | bird    | 1997-12-09 |
| Claws    | cat     | 1994-03-17 |
| Fluffy   | cat     | 1993-02-04 |
| Fang     | dog     | 1990-08-27 |
| Bowser   | dog     | 1989-08-31 |
| Buffy    | dog     | 1989-05-13 |
| Puffball | hamster | 1999-03-30 |
| Slim     | snake   | 1996-04-29 |
+----------+---------+------------+
@end example

Note that the @code{DESC} keyword applies only to the column name immediately
preceding it (@code{birth}); @code{species} values are still sorted in
ascending order.

@node Date calculations, Working with NULL, Sorting rows, Retrieving data
@subsubsection Date calculations

@strong{MySQL} provides several functions that you can use to perform
calculations on dates, for example, to calculate ages or extract
parts of dates.

To determine how many years old each of your pets is, compute age as the
difference between the birth date and the current date.  Do this by
converting the two dates to days, take the difference, and divide by 365 (the
number of days in a year):

@example
mysql> SELECT name, (TO_DAYS(NOW())-TO_DAYS(birth))/365 FROM pet;
+----------+-------------------------------------+
| name     | (TO_DAYS(NOW())-TO_DAYS(birth))/365 |
+----------+-------------------------------------+
| Fluffy   |                                6.15 |
| Claws    |                                5.04 |
| Buffy    |                                9.88 |
| Fang     |                                8.59 |
| Bowser   |                                9.58 |
| Chirpy   |                                0.55 |
| Whistler |                                1.30 |
| Slim     |                                2.92 |
| Puffball |                                0.00 |
+----------+-------------------------------------+
@end example

Although the query works, there are some things about it that could be
improved.  First, the result could be scanned more easily if the rows were
presented in some order.  Second, the heading for the age column isn't very
meaningful.

The first problem can be handled by adding an @code{ORDER BY name} clause to
sort the output by name.  To deal with the column heading, provide a name for
the column so that a different label appears in the output (this is called a
column alias):

@example
mysql> SELECT name, (TO_DAYS(NOW())-TO_DAYS(birth))/365 AS age
    -> FROM pet ORDER BY name;
+----------+------+
| name     | age  |
+----------+------+
| Bowser   | 9.58 |
| Buffy    | 9.88 |
| Chirpy   | 0.55 |
| Claws    | 5.04 |
| Fang     | 8.59 |
| Fluffy   | 6.15 |
| Puffball | 0.00 |
| Slim     | 2.92 |
| Whistler | 1.30 |
+----------+------+
@end example

To sort the output by @code{age} rather than @code{name}, just use a
different @code{ORDER BY} clause:

@example
mysql>  SELECT name, (TO_DAYS(NOW())-TO_DAYS(birth))/365 AS age
    ->  FROM pet ORDER BY age;
+----------+------+
| name     | age  |
+----------+------+
| Puffball | 0.00 |
| Chirpy   | 0.55 |
| Whistler | 1.30 |
| Slim     | 2.92 |
| Claws    | 5.04 |
| Fluffy   | 6.15 |
| Fang     | 8.59 |
| Bowser   | 9.58 |
| Buffy    | 9.88 |
+----------+------+
@end example

A similar query can be used to determine age at death for animals that have
died.  You determine which animals these are by checking whether or not the
@code{death} value is @code{NULL}.  Then, for those with non-@code{NULL}
values, compute the difference between the @code{death} and @code{birth}
values:

@example
mysql>  SELECT name, birth, death, (TO_DAYS(death)-TO_DAYS(birth))/365 AS age
    ->  FROM pet WHERE death IS NOT NULL ORDER BY age;
+--------+------------+------------+------+
| name   | birth      | death      | age  |
+--------+------------+------------+------+
| Bowser | 1989-08-31 | 1995-07-29 | 5.91 |
+--------+------------+------------+------+
@end example

The query uses @code{death IS NOT NULL} rather than @code{death != NULL}
because @code{NULL} is a special value.  This is explained later.
@xref{Working with NULL,  , Working with @code{NULL}}.

What if you want to know which animals have birthdays next month?  For this
type of calculation, year and day are irrelevant, you simply want to extract
the month part of the @code{birth} column.  @strong{MySQL} provides several
date-part extraction functions, such as @code{YEAR()}, @code{MONTH()} and
@code{DAY()}.  @code{MONTH()} is the appropriate function here.  To see how
it works, run a simple query that displays the value of both @code{birth} and
@code{MONTH(birth)}:

@example
mysql> SELECT name, birth, MONTH(birth) FROM pet;
+----------+------------+--------------+
| name     | birth      | MONTH(birth) |
+----------+------------+--------------+
| Fluffy   | 1993-02-04 |            2 |
| Claws    | 1994-03-17 |            3 |
| Buffy    | 1989-05-13 |            5 |
| Fang     | 1990-08-27 |            8 |
| Bowser   | 1989-08-31 |            8 |
| Chirpy   | 1998-09-11 |            9 |
| Whistler | 1997-12-09 |           12 |
| Slim     | 1996-04-29 |            4 |
| Puffball | 1999-03-30 |            3 |
+----------+------------+--------------+
@end example

Finding animals with birthdays in the upcoming month is easy, too.  Suppose
the current month is April.  Then the month value is @code{4} and you look
for animals born in May (month 5) like this:

@example
mysql> SELECT name, birth FROM pet WHERE MONTH(birth) = 5;
+-------+------------+
| name  | birth      |
+-------+------------+
| Buffy | 1989-05-13 |
+-------+------------+
@end example

There is a small complication if the current month is December, of course.
You don't just add one to the month number (@code{12}) and look for animals
born in month 13, because there is no such month.  Instead, you look for
animals born in January (month 1).

You can even write the query so that it works no matter what the current
month is.  That way you don't have to use a particular month number
in the query.  @code{DATE_ADD()} allows you to add a time interval to a
given date.  If you add a month to the value of @code{NOW()}, then extract
the month part with @code{MONTH()}, the result produces the month in which to
look for birthdays:

@example
mysql> SELECT name, birth FROM pet
    -> WHERE MONTH(birth) = MONTH(DATE_ADD(NOW(), INTERVAL 1 MONTH));
@end example

A different way to accomplish the same task is to add @code{1} to get the
next month after the current one (after using the modulo function (@code{MOD})
to ``wrap around'' the month value to @code{0} if it is currently
@code{12}):

@example
mysql> SELECT name, birth FROM pet
    -> WHERE MONTH(birth) = MOD(MONTH(NOW()),12) + 1;
@end example

@node Working with NULL, Pattern matching, Date calculations, Retrieving data
@subsubsection Working with @code{NULL} values

The @code{NULL} value can be surprising until you get used to it.
Conceptually, @code{NULL} means ``missing value'' or ``unknown value'' and it
is treated somewhat differently than other values.  To test for @code{NULL},
you cannot use the arithmetic comparison operators such as @code{=}, @code{<}
or @code{!=}.  To demonstrate this for yourself, try the following query:

@example
mysql> SELECT 1 = NULL, 1 != NULL, 1 < NULL, 1 > NULL;
+----------+-----------+----------+----------+
| 1 = NULL | 1 != NULL | 1 < NULL | 1 > NULL |
+----------+-----------+----------+----------+
|     NULL |      NULL |     NULL |     NULL |
+----------+-----------+----------+----------+
@end example

Clearly you get no meaningful results from these comparisons.  Use
the @code{IS NULL} and @code{IS NOT NULL} operators instead:

@example
mysql> SELECT 1 IS NULL, 1 IS NOT NULL;
+-----------+---------------+
| 1 IS NULL | 1 IS NOT NULL |
+-----------+---------------+
|         0 |             1 |
+-----------+---------------+
@end example

In @strong{MySQL}, 0 means false and 1 means true.

This special treatment of @code{NULL} is why, in the previous section, it
was necessary to determine which animals are no longer alive using
@code{death IS NOT NULL} instead of @code{death != NULL}.

@node Pattern matching, Counting rows, Working with NULL, Retrieving data
@subsubsection Pattern matching

@strong{MySQL} provides standard SQL pattern matching as well as a form of
pattern matching based on extended regular expressions similar to those used
by Unix utilities such as @code{vi}, @code{grep} and @code{sed}.

SQL pattern matching allows you to use @samp{_} to match any single
character, and @samp{%} to match an arbitrary number of characters (including
zero characters).  SQL patterns are case insensitive.  Some examples are
shown below.  Note that you do not use @code{=} or @code{!=} when you use SQL
patterns; use the @code{LIKE} or @code{NOT LIKE} comparison operators
instead.

To find names beginning with @samp{b}:

@example
mysql> SELECT * FROM pet WHERE name LIKE "b%";
+--------+--------+---------+------+------------+------------+
| name   | owner  | species | sex  | birth      | death      |
+--------+--------+---------+------+------------+------------+
| Buffy  | Harold | dog     | f    | 1989-05-13 | NULL       |
| Bowser | Diane  | dog     | m    | 1989-08-31 | 1995-07-29 |
+--------+--------+---------+------+------------+------------+
@end example

To find names ending with @samp{fy}:

@example
mysql> SELECT * FROM pet WHERE name LIKE "%fy";
+--------+--------+---------+------+------------+-------+
| name   | owner  | species | sex  | birth      | death |
+--------+--------+---------+------+------------+-------+
| Fluffy | Harold | cat     | f    | 1993-02-04 | NULL  |
| Buffy  | Harold | dog     | f    | 1989-05-13 | NULL  |
+--------+--------+---------+------+------------+-------+
@end example

To find names containing a @samp{w}:

@example
mysql> SELECT * FROM pet WHERE name LIKE "%w%";
+----------+-------+---------+------+------------+------------+
| name     | owner | species | sex  | birth      | death      |
+----------+-------+---------+------+------------+------------+
| Claws    | Gwen  | cat     | m    | 1994-03-17 | NULL       |
| Bowser   | Diane | dog     | m    | 1989-08-31 | 1995-07-29 |
| Whistler | Gwen  | bird    | NULL | 1997-12-09 | NULL       |
+----------+-------+---------+------+------------+------------+
@end example

To find names containing exactly five characters, use the @samp{_} pattern
character:

@example
mysql> SELECT * FROM pet WHERE name LIKE "_____";
+-------+--------+---------+------+------------+-------+
| name  | owner  | species | sex  | birth      | death |
+-------+--------+---------+------+------------+-------+
| Claws | Gwen   | cat     | m    | 1994-03-17 | NULL  |
| Buffy | Harold | dog     | f    | 1989-05-13 | NULL  |
+-------+--------+---------+------+------------+-------+
@end example

The other type of pattern matching provided by @strong{MySQL} uses extended
regular expressions.  When you test for a match for this type of pattern, use
the @code{REGEXP} and @code{NOT REGEXP} operators (or @code{RLIKE} and
@code{NOT RLIKE}, which are synonyms).

Some characteristics of extended regular expressions are:

@itemize @bullet
@item
@samp{.} matches any single character.

@item
A character class @samp{[...]} matches any character within the brackets.
For example, @samp{[abc]} matches @samp{a}, @samp{b} or @samp{c}.  To name a
range of characters, use a dash.  @samp{[a-z]} matches any lowercase letter,
whereas @samp{[0-9]} matches any digit.

@item
@samp{*} matches zero or more instances of the thing preceding it.  For
example, @samp{x*} matches any number of @samp{x} characters,
@samp{[0-9]*} matches any number of digits, and @samp{.*} matches any
number of anything.

@item
Regular expressions are case sensitive, but you can use a character class to
match both lettercases if you wish.  For example, @samp{[aA]} matches
lowercase or uppercase @samp{a} and @samp{[a-zA-Z]} matches any letter in
either case.

@item
The pattern matches if it occurs anywhere in the value being tested
(SQL patterns match only if they match the entire value).

@item
To anchor a pattern so that it must match the beginning or end of the value
being tested, use @samp{^} at the beginning or @samp{$} at the end of the
pattern.
@end itemize

To demonstrate how extended regular expressions work, the @code{LIKE} queries
shown above are rewritten below to use @code{REGEXP}:

To find names beginning with @samp{b}, use @samp{^} to match the beginning of
the name and @samp{[bB]} to match either lowercase or uppercase @samp{b}:

@example
mysql> SELECT * FROM pet WHERE name REGEXP "^[bB]";
+--------+--------+---------+------+------------+------------+
| name   | owner  | species | sex  | birth      | death      |
+--------+--------+---------+------+------------+------------+
| Buffy  | Harold | dog     | f    | 1989-05-13 | NULL       |
| Bowser | Diane  | dog     | m    | 1989-08-31 | 1995-07-29 |
+--------+--------+---------+------+------------+------------+
@end example

To find names ending with @samp{fy}, use @samp{$} to match the end of the
name:

@example
mysql> SELECT * FROM pet WHERE name REGEXP "fy$";
+--------+--------+---------+------+------------+-------+
| name   | owner  | species | sex  | birth      | death |
+--------+--------+---------+------+------------+-------+
| Fluffy | Harold | cat     | f    | 1993-02-04 | NULL  |
| Buffy  | Harold | dog     | f    | 1989-05-13 | NULL  |
+--------+--------+---------+------+------------+-------+
@end example

To find names containing a @samp{w}, use
@samp{[wW]} to match either lowercase or uppercase @samp{w}:

@example
mysql> SELECT * FROM pet WHERE name REGEXP "[wW]";
+----------+-------+---------+------+------------+------------+
| name     | owner | species | sex  | birth      | death      |
+----------+-------+---------+------+------------+------------+
| Claws    | Gwen  | cat     | m    | 1994-03-17 | NULL       |
| Bowser   | Diane | dog     | m    | 1989-08-31 | 1995-07-29 |
| Whistler | Gwen  | bird    | NULL | 1997-12-09 | NULL       |
+----------+-------+---------+------+------------+------------+
@end example

Since a regular expression pattern matches if it occurs anywhere in the
value, it is not necessary in the previous query to put a wildcard on either
side of the pattern to get it to match the entire value like it would be if
you used an SQL pattern.

To find names containing exactly five characters, use @samp{^} and @samp{$}
to match the beginning and end of the name, and five instances of @samp{.}
in between:

@example
mysql> SELECT * FROM pet WHERE name REGEXP "^.....$";
+-------+--------+---------+------+------------+-------+
| name  | owner  | species | sex  | birth      | death |
+-------+--------+---------+------+------------+-------+
| Claws | Gwen   | cat     | m    | 1994-03-17 | NULL  |
| Buffy | Harold | dog     | f    | 1989-05-13 | NULL  |
+-------+--------+---------+------+------------+-------+
@end example

You could also write the previous query using the @samp{@{n@}}
``repeat-@code{n}-times'' operator:

@example
mysql> SELECT * FROM pet WHERE name REGEXP "^.@{5@}$";
+-------+--------+---------+------+------------+-------+
| name  | owner  | species | sex  | birth      | death |
+-------+--------+---------+------+------------+-------+
| Claws | Gwen   | cat     | m    | 1994-03-17 | NULL  |
| Buffy | Harold | dog     | f    | 1989-05-13 | NULL  |
+-------+--------+---------+------+------------+-------+
@end example

@node Counting rows,  , Pattern matching, Retrieving data
@subsubsection Counting rows

Databases are often used to answer the question, ``how often does a certain
type of data occur in a table?''  For example, you might want to know how
many pets you have, or how many pets each owner has, or you might want to
perform various kinds of censuses on your animals.

Counting the total number of animals you have is the same question as ``how
many rows are in the @code{pet} table?,'' since there is one record per pet.
The @code{COUNT()} function counts the number of non-@code{NULL} results, so
the query to count your animals looks like this:

@example
mysql> SELECT COUNT(*) FROM pet;
+----------+
| COUNT(*) |
+----------+
|        9 |
+----------+
@end example

Earlier, you retrieved the names of the people who owned pets.  You can
use @code{COUNT()} if you want to find out how many pets each owner has:

@example
mysql> SELECT owner, COUNT(*) FROM pet GROUP BY owner;
+--------+----------+
| owner  | COUNT(*) |
+--------+----------+
| Benny  |        2 |
| Diane  |        2 |
| Gwen   |        3 |
| Harold |        2 |
+--------+----------+
@end example

Note the use of @code{GROUP BY} to group together all records for each
@code{owner}.  Without it, all you get is an error message:

@example
mysql> SELECT owner, COUNT(owner) FROM pet;
ERROR 1140 at line 1: Mixing of GROUP columns (MIN(),MAX(),COUNT()...)
with no GROUP columns is illegal if there is no GROUP BY clause
@end example

@code{COUNT()} and @code{GROUP BY} are useful for characterizing your
data in various ways.  The following examples show different ways to
perform animal census operations.

Number of animals per species:

@example
mysql> SELECT species, COUNT(*) FROM pet GROUP BY species;
+---------+----------+
| species | COUNT(*) |
+---------+----------+
| bird    |        2 |
| cat     |        2 |
| dog     |        3 |
| hamster |        1 |
| snake   |        1 |
+---------+----------+
@end example

Number of animals per sex:

@example
mysql> SELECT sex, COUNT(*) FROM pet GROUP BY sex;
+------+----------+
| sex  | COUNT(*) |
+------+----------+
| NULL |        1 |
| f    |        4 |
| m    |        4 |
+------+----------+
@end example

(In this output, @code{NULL} indicates ``sex unknown.'')

Number of animals per combination of species and sex:

@example
mysql> SELECT species, sex, COUNT(*) FROM pet GROUP BY species, sex;
+---------+------+----------+
| species | sex  | COUNT(*) |
+---------+------+----------+
| bird    | NULL |        1 |
| bird    | f    |        1 |
| cat     | f    |        1 |
| cat     | m    |        1 |
| dog     | f    |        1 |
| dog     | m    |        2 |
| hamster | f    |        1 |
| snake   | m    |        1 |
+---------+------+----------+
@end example

You need not retrieve an entire table when you use @code{COUNT()}.  For
example, the previous query, when performed just on dogs and cats, looks like
this:

@example
mysql> SELECT species, sex, COUNT(*) FROM pet
    -> WHERE species = "dog" OR species = "cat"
    -> GROUP BY species, sex;
+---------+------+----------+
| species | sex  | COUNT(*) |
+---------+------+----------+
| cat     | f    |        1 |
| cat     | m    |        1 |
| dog     | f    |        1 |
| dog     | m    |        2 |
+---------+------+----------+
@end example

Or, if you wanted the number of animals per sex only for known-sex animals:

@example
mysql> SELECT species, sex, COUNT(*) FROM pet
    -> WHERE sex IS NOT NULL
    -> GROUP BY species, sex;
+---------+------+----------+
| species | sex  | COUNT(*) |
+---------+------+----------+
| bird    | f    |        1 |
| cat     | f    |        1 |
| cat     | m    |        1 |
| dog     | f    |        1 |
| dog     | m    |        2 |
| hamster | f    |        1 |
| snake   | m    |        1 |
+---------+------+----------+
@end example

@node Multiple tables,  , Retrieving data, Database use
@subsection Using more than one table

The @code{pet} table keeps track of which pets you have.  If you want to
record other information about them, such as events in their lives like
visits to the vet or when litters are born, you need another table.  What
should this table look like?

@itemize @bullet
@item
It needs to contain the pet name so you know which animal each event pertains
to.

@item
It needs a date so you know when the event occurred.

@item
It needs a field to describe the event.

@item
If you want to be able to categorize events, it would be useful to have an
event type field.
@end itemize

Given these considerations, the @code{CREATE TABLE} statement for the
@code{event} table might look like this:

@example
mysql> CREATE TABLE event (name VARCHAR(20), date DATE,
    -> type VARCHAR(15), remark VARCHAR(255));
@end example

As with the @code{pet} table, it's easiest to load the initial records
by creating a tab-delimited text file containing the information:

@multitable @columnfractions .15 .15 .15 .55
@item Fluffy @tab 1995-05-15 @tab litter @tab 4 kittens, 3 female, 1 male
@item Buffy @tab 1993-06-23 @tab litter @tab 5 puppies, 2 female, 3 male
@item Buffy @tab 1994-06-19 @tab litter @tab 3 puppies, 3 female
@item Chirpy @tab 1999-03-21 @tab vet @tab needed beak straightened
@item Slim @tab 1997-08-03 @tab vet @tab broken rib
@item Bowser @tab 1991-10-12 @tab kennel
@item Fang @tab 1991-10-12 @tab kennel
@item Fang @tab 1998-08-28 @tab birthday @tab Gave him a new chew toy
@item Claws @tab 1998-03-17 @tab birthday @tab Gave him a new flea collar
@item Whistler @tab 1998-12-09 @tab birthday @tab First birthday
@end multitable

Load the records like this:

@example
mysql> LOAD DATA LOCAL INFILE "event.txt" INTO TABLE event;
@end example

Based on what you've learned from the queries you've run on the @code{pet}
table, you should be able to perform retrievals on the records in the
@code{event} table; the principles are the same.  But when is the
@code{event} table by itself insufficient to answer questions you might ask?

Suppose you want to find out the ages of each pet when they had their
litters.  The @code{event} table indicates when this occurred, but to
calculate age of the mother, you need her birth date.  Since that is
stored in the @code{pet} table, you need both tables for the query:

@example
mysql> SELECT pet.name, (TO_DAYS(date) - TO_DAYS(birth))/365 AS age, remark
    -> FROM pet, event
    -> WHERE pet.name = event.name AND type = "litter";
+--------+------+-----------------------------+
| name   | age  | remark                      |
+--------+------+-----------------------------+
| Fluffy | 2.27 | 4 kittens, 3 female, 1 male |
| Buffy  | 4.12 | 5 puppies, 2 female, 3 male |
| Buffy  | 5.10 | 3 puppies, 3 female         |
+--------+------+-----------------------------+
@end example

There are several things to note about this query:

@itemize @bullet
@item
The @code{FROM} clause lists two tables since the query needs to pull
information from both of them.

@item
When combining information from multiple tables, you need to specify how
records in one table can be matched to records in the other.  This is easy
since they both have a @code{name} column.  The query uses @code{WHERE}
clause to match up records in the two tables based on the @code{name}
values.

@item
Since the @code{name} column occurs in both tables, you must be specific
about which table you mean when referring to the column.  This is done
by prepending the table name to the column name.
@end itemize

You need not have two different tables to perform a join.  Sometimes it is
useful to join a table to itself, if you want to compare records in a table
to other records in that same table.  For example, to find breeding pairs
among your pets, you can join the @code{pet} table with itself to pair up
males and females of like species:

@example
mysql> SELECT p1.name, p1.sex, p2.name, p2.sex, p1.species
    -> FROM pet AS p1, pet AS p2
    -> WHERE p1.species = p2.species AND p1.sex = "f" AND p2.sex = "m";
+--------+------+--------+------+---------+
| name   | sex  | name   | sex  | species |
+--------+------+--------+------+---------+
| Fluffy | f    | Claws  | m    | cat     |
| Buffy  | f    | Fang   | m    | dog     |
| Buffy  | f    | Bowser | m    | dog     |
+--------+------+--------+------+---------+
@end example

In this query, we specify aliases for the table name in order to be able
to refer to the columns and keep straight which instance of the table
each column reference is associated with.

@node Getting information, Batch mode, Database use, Tutorial
@section Getting information about databases and tables

What if you forget the name of a database or table, or what the structure of
a given table is (e.g., what its columns are called)?  @strong{MySQL}
addresses this problem through several statements that provide information
about the databases and tables it supports.

You have already seen @code{SHOW DATABASES}, which lists the databases
managed by the server.  To find out which database is currently selected,
use the @code{DATABASE()} function:

@example
mysql> SELECT DATABASE();
+------------+
| DATABASE() |
+------------+
| menagerie  |
+------------+
@end example

If you haven't selected any database yet, the result is blank.

To find out what tables the current database contains (for example, when
you're not sure about the name of a table), use this command:

@example
mysql> SHOW TABLES;
+---------------------+
| Tables in menagerie |
+---------------------+
| event               |
| pet                 |
+---------------------+
@end example

If you want to find out about the structure of a table, the @code{DESCRIBE}
command is useful; it displays information about each of a table's columns:

@example
mysql> DESCRIBE pet;
+---------+-------------+------+-----+---------+-------+
| Field   | Type        | Null | Key | Default | Extra |
+---------+-------------+------+-----+---------+-------+
| name    | varchar(20) | YES  |     | NULL    |       |
| owner   | varchar(20) | YES  |     | NULL    |       |
| species | varchar(20) | YES  |     | NULL    |       |
| sex     | char(1)     | YES  |     | NULL    |       |
| birth   | date        | YES  |     | NULL    |       |
| death   | date        | YES  |     | NULL    |       |
+---------+-------------+------+-----+---------+-------+
@end example

@code{Field} indicates the column name, @code{Type} is the data type for
the column, @code{Null} indicates whether or not the column can contain
@code{NULL} values, @code{Key} indicates whether or not the column is
indexed and @code{Default} specifies the column's default value.

If you have indexes on a table,
@code{SHOW INDEX FROM tbl_name} produces information about them.

@node Batch mode, Twin, Getting information, Tutorial
@section Using @code{mysql} in batch mode

In the previous sections, you used @code{mysql} interactively to enter
queries and view the results.  You can also run @code{mysql} in batch
mode.  To do this, put the commands you want to run in a file, then
tell @code{mysql} to read its input from the file:

@example
shell> mysql < batch-file
@end example

If you need to specify connection parameters on the command line, the
command might look like this:

@example
shell> mysql -h host -u user -p < batch-file
Enter password: ********
@end example

When you use @code{mysql} this way, you are creating a script file, then
executing the script.

Why use a script?  Here are a few reasons:

@itemize @bullet
@item
If you run a query repeatedly (say, every day or every week), making it a
script allows you to avoid retyping it each time you execute it.

@item
You can generate new queries from existing ones that are similar by copying
and editing script files.

@item
Batch mode can also be useful while you're developing a query, particularly
for multiple-line commands or multiple-statement sequences of commands.  If
you make a mistake, you don't have to retype everything.  Just edit your
script to correct the error, then tell @code{mysql} to execute it again.

@item
If you have a query that produces a lot of output, you can run the output
through a pager rather than watching it scroll off the top of your screen:

@example
shell> mysql < batch-file | more
@end example

@item
You can catch the output in a file for further processing:

@example
shell> mysql < batch-file > mysql.out
@end example

@item
You can distribute your script to other people so they can run the commands,
too.

@item
Some situations do not allow for interactive use, for example, when you run
a query from a @code{cron} job.  In this case, you must use batch mode.
@end itemize

The default output format is different (more concise) when you run
@code{mysql} in batch mode than when you use it interactively.  For
example, the output of @code{SELECT DISTINCT species FROM pet} looks like
this when run interactively:

@example
+---------+
| species |
+---------+
| bird    |
| cat     |
| dog     |
| hamster |
| snake   |
+---------+
@end example

But like this when run in batch mode:

@example
species
bird
cat
dog
hamster
snake
@end example

If you want to get the interactive output format in batch mode, use
@code{mysql -t}.  To echo to the output the commands that are executed, use
@code{mysql -vvv}.

@node Twin,  , Batch mode, Tutorial
@section Queries from twin project

At Analytikerna and Lentus, we have been doing the systems and field work
for a big research project. This project is a collaboration between the
Institute of Environmental Medicine at Karolinska Institutet Stockholm
and the Section on Clinical Research in Aging and Psychology at the
University of Southern California.

The project involves a screening part where all twins in Sweden older
than 65 years are interviewed by telephone. Twins who meet certain
criteria are passed on to the next stage. In this latter stage, twins who
want to participate are visited by a doctor/nurse team. Some of the
examinations include physical and neuropsychological examination,
laboratory testing, neuroimaging, psychological status assessment, and family
history collection. In addition, data are collected on medical and
environmental risk factors.

More information about Twin studies can be found at:

@example
@url{http://www.imm.ki.se/TWIN/TWINUKW.HTM}
@end example

The latter part of the project is administered with a web interface
written using Perl and @strong{MySQL}.

Each night all data from the interviews are moved into a @strong{MySQL}
database.

@menu
* Twin pool::                   Find all non-distributed twins
* Twin event::                  Show a table on twin pair status
@end menu

@node Twin pool, Twin event, Twin, Twin
@subsection Find all non-distributed twins

The following query is used to determine who goes into the second part of the
project:

@example
select
        concat(p1.id, p1.tvab) + 0 as tvid,
        concat(p1.christian_name, " ", p1.surname) as Name,
        p1.postal_code as Code,
        p1.city as City,
        pg.abrev as Area,
        if(td.participation = "Aborted", "A", " ") as A,
        p1.dead as dead1,
        l.event as event1,
        td.suspect as tsuspect1,
        id.suspect as isuspect1,
        td.severe as tsevere1,
        id.severe as isevere1,
        p2.dead as dead2,
        l2.event as event2,
        h2.nurse as nurse2,
        h2.doctor as doctor2,
        td2.suspect as tsuspect2,
        id2.suspect as isuspect2,
        td2.severe as tsevere2,
        id2.severe as isevere2,
        l.finish_date
from
        twin_project as tp
        /* For Twin 1 */
        left join twin_data as td on tp.id = td.id and tp.tvab = td.tvab
        left join informant_data as id on tp.id = id.id and tp.tvab = id.tvab
        left join harmony as h on tp.id = h.id and tp.tvab = h.tvab
        left join lentus as l on tp.id = l.id and tp.tvab = l.tvab
        /* For Twin 2 */
        left join twin_data as td2 on p2.id = td2.id and p2.tvab = td2.tvab
        left join informant_data as id2 on p2.id = id2.id and p2.tvab = id2.tvab
        left join harmony as h2 on p2.id = h2.id and p2.tvab = h2.tvab
        left join lentus as l2 on p2.id = l2.id and p2.tvab = l2.tvab,
        person_data as p1,
        person_data as p2,
        postal_groups as pg
where
        /* p1 gets main twin and p2 gets his/her twin. */
        /* ptvab is a field inverted from tvab */
        p1.id = tp.id and p1.tvab = tp.tvab and
        p2.id = p1.id and p2.ptvab = p1.tvab and
        /* Just the sceening survey */
        tp.survey_no = 5 and
        /* Skip if partner died before 65 but allow emigration (dead=9) */
        (p2.dead = 0 or p2.dead = 9 or
         (p2.dead = 1 and
          (p2.death_date = 0 or
           (((to_days(p2.death_date) - to_days(p2.birthday)) / 365)
            >= 65))))
        and
        (
        /* Twin is suspect */
        (td.future_contact = 'Yes' and td.suspect = 2) or
        /* Twin is suspect - Informant is Blessed */
        (td.future_contact = 'Yes' and td.suspect = 1 and id.suspect = 1) or
        /* No twin - Informant is Blessed */
        (ISNULL(td.suspect) and id.suspect = 1 and id.future_contact = 'Yes') or
        /* Twin broken off - Informant is Blessed */
        (td.participation = 'Aborted'
         and id.suspect = 1 and id.future_contact = 'Yes') or
        /* Twin broken off - No inform - Have partner */
        (td.participation = 'Aborted' and ISNULL(id.suspect) and p2.dead = 0))
        and
        l.event = 'Finished'
        /* Get at area code */
        and substring(p1.postal_code, 1, 2) = pg.code
        /* Not already distributed */
        and (h.nurse is NULL or h.nurse=00 or h.doctor=00)
        /* Has not refused or been aborted */
        and not (h.status = 'Refused' or h.status = 'Aborted'
        or h.status = 'Died' or h.status = 'Other')
order by
        tvid;
@end example

Some explanations:
@table @asis
@item @code{concat(p1.id, p1.tvab) + 0 as tvid}
We want to sort on the concatenated @code{id} and @code{tvab} in
numerical order. Adding @code{0} to the result causes @strong{MySQL} to treat the
result as a number.
@item column @code{id}
This identifies a pair of twins. It is a key in all tables.
@item column @code{tvab}
This identifies a twin in a pair. It has a value of @code{1} or @code{2}.
@item column @code{ptvab}
This is an inverse of @code{tvab}. When @code{tvab} is @code{1} this is
@code{2}, and vice versa. It exists to save typing and to make it easier for
@strong{MySQL} to optimize the query.
@end table

This query demonstrates, among other things, how to do lookups on a
table from the same table with a join (@code{p1} and @code{p2}). In the example, this
is used to check whether a twin's partner died before the age of 65. If so,
the row is not returned.

All of the above exist in all tables with twin-related information. We
have a key on both @code{id,tvab} (all tables) and @code{id,ptvab}
(@code{person_data}) to make queries faster.

On our production machine (A 200MHz UltraSPARC), this query returns
about 150-200 rows and takes less than one second.

The current number of records in the tables used above:
@multitable @columnfractions .3 .5
@item @strong{Table}            @tab @strong{Rows}
@item @code{person_data}        @tab 71074
@item @code{lentus}		@tab 5291
@item @code{twin_project}       @tab 5286
@item @code{twin_data}		@tab 2012
@item @code{informant_data}	@tab 663
@item @code{harmony}		@tab 381
@item @code{postal_groups}	@tab 100
@end multitable

@node Twin event,  , Twin pool, Twin
@subsection Show a table on twin pair status

Each interview ends with a status code called @code{event}. The query
shown below is used to display a table over all twin pairs combined by
event. This indicates in how many pairs both twins are finished, in how many
pairs one twin is finished and the other refused, and so on.

@example
select
        t1.event,
        t2.event,
        count(*)
from
        lentus as t1,
        lentus as t2,
        twin_project as tp
where
        /* We are looking at one pair at a time */
        t1.id = tp.id
        and t1.tvab=tp.tvab
        and t1.id = t2.id
        /* Just the sceening survey */
        and tp.survey_no = 5
        /* This makes each pair only appear once */
        and t1.tvab='1' and t2.tvab='2'
group by
        t1.event, t2.event;

@end example

@cindex Server functions
@node Server, Performance, Tutorial, Top
@chapter @strong{MySQL} Server functions

@menu
* Languages::                   What languages are supported by @strong{MySQL}?
* Update log::                  The update log
* Table size::                  How big @strong{MySQL} tables can be
@end menu

@cindex Which languages @strong{MySQL} supports
@cindex Language support
@node Languages, Update log, Server, Server
@section What languages are supported by @strong{MySQL}?

@code{mysqld} can issue error messages in the following languages: Czech,
Dutch, English (the default), French, German, Hungarian, Italian, Norwegian,
Norwegian-ny, Polish, Portuguese, Spanish and Swedish.

To start @code{mysqld} with a particular language, use either the
@code{--language=lang} or @code{-L lang} options. For example:

@example
shell> mysqld --language=swedish
@end example

or:

@example
shell> mysqld --language=/usr/local/share/swedish
@end example

Note that all language names are specified in lowercase.

The language files are located (by default) in
@file{@var{mysql_base_dir}/share/@var{LANGUAGE}/}.

To update the error message file, you should edit the @file{errmsg.txt} file
and execute the following command to generate the @file{errmsg.sys} file:

@example
shell> comp_err errmsg.txt errmsg.sys
@end example

If you upgrade to a newer version of @strong{MySQL}, remember to repeat
your changes with the new @file{errmsg.txt} file.

@menu
* Character sets::              The character set used for data and sorting
* Adding character set::        Adding a new character set
* Multi-byte characters::       Multi-byte character support
@end menu

@node Character sets, Adding character set, Languages, Languages
@subsection The character set used for data and sorting

By default, @strong{MySQL} uses the ISO-8859-1 (Latin1) character
set. This is the character set used in the USA and western Europe.

The character set determines what characters are allowed in names and how
things are sorted by the @code{ORDER BY} and @code{GROUP BY} clauses of
the @code{SELECT} statement.

You can change the character set at compile time by using the
@code{--with-charset=charset} option to @code{configure}.
@xref{Quick install}.

To add another character set to @strong{MySQL}, use the following procedure:

@node Adding character set, Multi-byte characters, Character sets, Languages
@subsection Adding a new character set

@enumerate
@item
Choose a name for the character set, denoted @code{MYSET} below.

@item
Create the file
@file{strings/ctype-MYSET.c} in the @strong{MySQL} source distribution.

@item
Look at one of the existing @file{ctype-*.c} files to see what needs to be
defined. Note that the arrays in your file must have names like
@code{ctype_MYSET}, @code{to_lower_MYSET} and so on.

@code{to_lower[]} and @code{to_upper[]} are simple arrays that hold the
lowercase and uppercase characters corresponding to each member of the
character set.  For example:

@example
to_lower['A'] should contain 'a'
to_upper['a'] should contain 'A'
@end example

@code{sort_order[]} is a map indicating how characters should be ordered for
comparison and sorting purposes.  For many character sets, this is the same as
@code{to_upper[]} (which means sorting will be case insensitive).
@strong{MySQL} will sort characters based on the value of
@code{sort_order[character]}.

@code{ctype[]} is an array of bit values, with one element for one character.
(Note that @code{to_lower[]}, @code{to_upper[]} and @code{sort_order[]}
are indexed by character value, but @code{ctype[]} is indexed by character
value + 1.  This is an old legacy to be able to handle EOF.)
You can find the following bitmask definitions in @file{m_ctype.h}:

@example
#define _U      01      /* Upper case */
#define _L      02      /* Lower case */
#define _N      04      /* Numeral (digit) */
#define _S      010     /* Spacing character */
#define _P      020     /* Punctuation */
#define _C      040     /* Control character */
#define _B      0100    /* Blank */
#define _X      0200    /* heXadecimal digit */
@end example

The @code{ctype[]} entry for each character should be the union of the
applicable bitmask values that describe the character.
For example, @code{'A'} is an uppercase character (@code{_U}) as well as a
hexidecimal digit (@code{_X}), so @code{ctype['A'+1]} should contain the value:
@example
_U + _X = 01 + 0200 = 0201
@end example

@item
Add a unique number for your character set to @file{include/m_ctype.h.in}.

@item
Add the character set name to the @code{CHARSETS_AVAILABLE} list in
@code{configure.in}.

@item
Reconfigure, recompile and test.
@end enumerate

@cindex Multi-byte characters
@node Multi-byte characters,  , Adding character set, Languages
@subsection Multi-byte character support

If you are creating a multi-byte character set, you can use the
@code{_MB} macros.  In @file{include/m_ctype.h.in}, add:

@example
#define MY_CHARSET_MYSET  X
#if MY_CHARSET_CURRENT == MY_CHARSET_MYSET
#define USE_MB
#define USE_MB_IDENT
#define ismbchar(p, end)  (...)
#define ismbhead(c)       (...)
#define mbcharlen(c)      (...)
#define MBMAXLEN          N
#endif
@end example

Where:

@multitable @columnfractions .25 .75
@item @code{MY_CHARSET_MYSET} @tab A unique character set value.
@item @code{USE_MB}           @tab This character set has multi-byte
characters, handled by @code{ismbhead()} and @code{mbcharlen()}
@item @code{USE_MB_IDENT}     @tab (optional) If defined, you can use table and
column names that use multi-byte characters
@item @code{ismbchar(p, e)}   @tab return 0 if @code{p} is not a multi-byte
character string, or the size of the character (in bytes) if it is.  @code{p}
and @code{e} point to the beginning and end of the string.
Check from @code{(char*)p} to @code{(char*)e-1}.
@item @code{ismbhead(c)}      @tab True if @code{c} is the first character of
a multi-byte character string
@item @code{mbcharlen(c)}     @tab Size of a multi-byte character string if
@code{c} is the first character of such a string
@item @code{MBMAXLEN}         @tab Size in bytes of the largest character in
the set
@end multitable

@cindex Update log
@node Update log, Table size, Languages, Server
@section The update log

When started with the @code{--log-update=file_name} option, @code{mysqld}
writes a log file containing all SQL commands that update data. The file is
written in the data directory and has a name of @code{file_name.#}, where
@code{#} is a number that is incremented each time you execute
@code{mysqladmin refresh} or @code{mysqladmin flush-logs}, the @code{FLUSH
LOGS} statement, or restart the
server.

If you use the @code{--log} or @code{-l} options, the filename is
@file{hostname.log}, and restarts and refreshes do not cause a new log file
to be generated. By default, the @code{mysql.server} script starts the
@strong{MySQL} server with the @code{-l} option.  If you need better
performance when you start using @strong{MySQL} in a production environment,
you can remove the @code{-l} option from @code{mysql.server}.

Update logging is smart since it logs only statements that really update
data. So an @code{UPDATE} or a @code{DELETE} with a @code{WHERE} that finds no
rows is not written to the log. It even skips @code{UPDATE} statements that
set a column to the value it already has.

If you want to update a database from update log files, you could do the
following (assuming your log files have names of the form
@file{file_name.#}):

@example
shell> ls -1 -t -r file_name.[0-9]* | xargs cat | mysql
@end example

@code{ls} is used to get all the log files in the right order.

This can be useful if you have to revert to backup files after a crash
and you want to redo the updates that occurred between the time of the backup
and the crash.

@cindex Database replication
@cindex Replication, database
@cindex Database mirroring
@cindex Mirroring, database
You can also use the update logs when you have a mirrored database on
another host and you want to replicate the changes that have been made
to the master database.

@cindex Table size
@cindex Size of tables
@node Table size,  , Update log, Server
@section How big @strong{MySQL} tables can be

@strong{MySQL} itself has a 4G limit on table size, and
operating systems have their own file size limits.  On Linux, the
current limit is 2G; on Solaris 2.5.1, the limit is 4G; on Solaris 2.6,
the limit is going to be 1000G.  Currently, table sizes are limited to
either 4G (the @strong{MySQL} limit) or the operating system limit,
whichever is smaller.  To get more than 4G requires some changes to
@strong{MySQL} that are on the TODO. @xref{TODO}.

If your big table is going to be read-only, you could use @code{pack_isam}
to merge and compress many tables to one.  @code{pack_isam} usually
compresses a table by at least 50%, so you can have, in effect, much bigger
tables.
@xref{pack_isam,  , @code{pack_isam}}.

Another solution can be the included MERGE library, which allows you to
handle a collection of identical tables as one.  (Identical in this case
means that all tables are created with identical column information.)
Currently MERGE can only be used to scan a collection of tables because it
doesn't support indexes. We will add indexes to this in the near future.

@cindex Performance
@node Performance, Benchmarks, Server, Top
@chapter Getting maximum performance from @strong{MySQL}

@menu
* Server parameters::           Tuning server parameters
* Memory use::                  How @strong{MySQL} uses memory
* Compile and link options::    How compiling and linking affects the speed of @strong{MySQL}
* MySQL indexes::               How @strong{MySQL} uses indexes
* Where optimizations ::        How @strong{MySQL} optimizes @code{WHERE} clauses
* LEFT JOIN optimization::      How @strong{MySQL} optimizes @code{LEFT JOIN}
* Table cache::                 How @strong{MySQL} opens and closes tables
* Open tables::                 Why so many open tables?
* Symbolic links::              Using symbolic links for databases and tables
* Internal locking::            How @strong{MySQL} locks tables
* Table efficiency::            How to arrange a table to be as fast/small as possible
* Table locking::               Table locking issues
* Insert speed::                Factors affecting the speed of @code{INSERT} statements
* Delete speed::                Factors affecting the speed of @code{DELETE} statements
* Optimize::                    What options to use to get @strong{MySQL} to run at full speed
* Row format::                  What are the different row formats? Or when to use VARCHAR/CHAR?
* Table types::                 @strong{MySQL} table types.
@end menu

@cindex Startup parameters
@node Server parameters, Memory use, Performance, Performance
@section Tuning server parameters

You can get the default buffer sizes used by the @code{mysqld} server
with this command:

@example
shell> mysqld --help
@end example

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

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

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

@example
shell> mysqladmin variables
@end example

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

@table @code
@item @code{back_log}
The number of outstanding connection requests @strong{MySQL} can have. This
comes into play when the main @strong{MySQL} thread gets @strong{VERY}
many connection requests in a very short time. It then takes some time
(although very little) for the main thread to check the connection and start
a new thread. The @code{back_log} value indicates how many requests can be
stacked during this short time before @strong{MySQL} momentarily stops
answering new requests. You need to increase this only if you expect a large
number of connections in a short period of time.

In other words, this value is the size of the listen queue for incoming
TCP/IP connections.  Your operating system has its own limit on the size
of this queue.  The manual page for the Unix @code{listen(2)} system
call should have more details.  Check your OS documentation for the
maximum value for this variable.  Attempting to set @code{back_log}
higher than this maximum will be
ineffective.

@item @code{connect_timeout}
The number of seconds the @code{mysqld} server is waiting for a connect
packet before responding with @code{Bad handshake}.

@item @code{delayed_insert_timeout}
How long a @code{INSERT DELAYED} thread should wait for @code{INSERT} statements
before terminating.
@item @code{delayed_insert_limit}
After inserting @code{delayed_insert_limit} rows, the @code{INSERT DELAYED}
handler will check if there are any @code{SELECT} statements pending.  If so, it
allows these to execute before continuing.

@item @code{delayed_queue_size}
How big a queue (in rows) should be allocated for handling @code{INSERT DELAYED}.
If the queue becomes full, any client that does @code{INSERT DELAYED} will wait until
there is room in the queue again.

@item @code{flush_time}
If this is set, then every @code{flush_time} seconds all tables will be closed
(to free up resources and sync things to disk).

@item @code{join_buffer}
The size of the buffer that is used for full joins (joins that do not
use indexes).  The buffer is allocated one time for each full join
between two tables. Increase this value to get a faster full join when
adding indexes is not possible. (Normally the best way to get fast joins
is to add indexes.)

@item @code{key_buffer}
Index blocks are buffered and are shared by all threads. @code{key_buffer} is
the size of the buffer used for index blocks. You might want to increase this
value when doing many @code{DELETE} or @code{INSERT} operations on a table
with lots of indexes. To get even more speed, use @code{LOCK TABLES}.
@xref{LOCK TABLES, , @code{LOCK TABLES}}.

@item @code{long_query_time}
If a query takes longer than this (in seconds), the @code{slow_queries} counter
will be incremented.

@item @code{max_allowed_packet}
The maximum size of one packet. The message buffer is initialized to
@code{net_buffer_length} bytes, but can grow up to @code{max_allowed_packet}
bytes when needed.  This value by default is small to catch big (possibly
wrong) packets.  You must increase this value if you are using big
@code{BLOB} columns. It should be as big as the biggest @code{BLOB} you want
to use.

@item @code{max_connections}
The number of simultaneous clients allowed. Increasing this value increases
the number of file descriptors that @code{mysqld} requires.  See below for
comments on file descriptor limits.

@item @code{max_connect_errors}
If there is more than this number of interrupted connections from a host
this host will be blocked for further connections.  You can unblock a host
with the command @code{FLUSH HOSTS}.

@item @code{max_delayed_threads} Don't start more than this number of
threads to handle @code{INSERT DELAYED}.  If you try to insert data in
a new table after all @code{INSERT DELAYED} threads are in use, the row will
be inserted as if the @code{DELAYED} attribute wasn't specified.

@item @code{max_join_size}
Joins that are probably going to read more than @code{max_join_size}
records return an error. Set this value if your users tend to perform joins
without a @code{WHERE} clause that take a long time and return
millions of rows.

@item @code{max_sort_length}
The number of bytes to use when sorting @code{BLOB} or @code{TEXT}
values (only the first @code{max_sort_length} bytes of each value
are used; the rest are ignored).

@item @code{max_tmp_tables}
(This option doesn't yet do anything).
Maximum number of temporary tables a client can keep open at the same time.

@item @code{net_buffer_length}
The communication buffer is reset to this size between queries. This
should not normally be changed, but if you have very little memory, you
can set it to the expected size of a query.  (That is, the expected length of
SQL statements sent by clients.  If statements exceed this length, the buffer
is automatically enlarged, up to @code{max_allowed_packet} bytes.)

@item @code{record_buffer}
Each thread that does a sequential scan allocates a buffer of this
size for each table it scans. If you do many sequential scans, you may
want to increase this value.

@item @code{sort_buffer}
Each thread that needs to do a sort allocates a buffer of this
size. Increase this value for faster @code{ORDER BY} or @code{GROUP BY}
operations.
@xref{Temporary files}.

@cindex Table cache
@findex table_cache
@item @code{table_cache}
The number of open tables for all threads. Increasing this value increases
the number of file descriptors that @code{mysqld} requires.  @strong{MySQL}
needs two file descriptors for each unique open table.  See below for
comments on file descriptor limits.  For information about how the table
cache works, see @ref{Table cache}.

@item @code{tmp_table_size}
If a temporary table exceeds this size, @strong{MySQL} generates an error of
the form @code{The table tbl_name is full}. Increase the value of
@code{tmp_table_size} if you do many advanced @code{GROUP BY} queries.

@item @code{thread_stack}
The stack size for each thread.  Many of the limits detected by the
@code{crash-me} test are dependent on this value. The default is normally
large enough.
@xref{Benchmarks}.

@item wait_timeout
The number of seconds the server waits for activity on a connection before
closing it.
@end table

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

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

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

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

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

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

@example
shell> safe_mysqld -O key_buffer=512k -O sort_buffer=100k \
           -O record_buffer=100k &
@end example

or even:

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

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

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

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

@example
shell> mysqld -O key_buffer=32m --help
@end example

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

@cindex Memory use
@node Memory use, Compile and link options, Server parameters, Performance
@section How @strong{MySQL} uses memory

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

@itemize @bullet
@item
The key buffer (variable @code{key_buffer}) is shared by all threads;
Other buffers used by the server are allocated as needed.

@item
Each connection uses some thread specific space; A stack (64K, variable
@code{thread_stack}) a connection buffer (variable
@code{net_buffer_length}), and a result buffer (variable
@code{net_buffer_length}). The connection buffer and result buffer are
dynamicly enlarged up to @code{max_allowed_packet} when needed.  When a
query is running a copy of the current query string is also alloced.

@item
All threads share the same base memory.

@item
Nothing is memory-mapped yet (except compressed tables, but that's another
story). This is because the 32-bit memory space of 4GB is not large
enough for most large tables. When we get a system with a 64-bit address
space, we may add general support for memory-mapping.

@item
Each request doing a sequential scan over a table allocates a read buffer
(variable @code{record_buffer}).

@item
All joins are done in one pass and most joins can be done without even
using a temporary table. Most temporary tables are memory-based (HEAP)
tables.  Temporary tables with a big record length (calculated as the
sum of all column lengths) or that contain @code{BLOB} columns are
stored on disk.  One current problem is that if a HEAP table exceeds the
size of @code{tmp_table_size}, you get the error @code{The table
tbl_name is full}.  In the future, we will fix this by automatically
changing the in-memory (HEAP) table to a disk-based (NISAM) table as
necessary.  To work around this problem, you can increase the temporary
table size by setting the @code{tmp_table_size} option to @code{mysqld},
or by setting the SQL option @code{SQL_BIG_TABLES} in the client
program.  @xref{SET OPTION, , @code{SET OPTION}}. In @strong{MySQL}
3.20, the maximum size of the temporary table was
@code{record_buffer*16}, so if you are using this version, you have to
increase the value of @code{record_buffer}. You can also start
@code{mysqld} with the @code{--big-tables} option to always store
temporary tables on disk, however, this will affect the speed of all
complicated queries.

@item
Most requests doing a sort allocate a sort buffer and one or two temporary
files. @xref{Temporary files}.

@item
Almost all parsing and calculating is done in a local memory store. No
memory overhead is needed for small items and the normal slow memory
allocation and freeing is avoided. Memory is allocated only for
unexpectedly large strings (this is done with @code{malloc()} and
@code{free()}).

@item
Each index file is opened once and the data file is opened once for each
concurrently-running thread. For each concurrent thread, a table structure,
column structures for each column, and a buffer of size @code{3 * n} is
allocated (where @code{n} is the maximum row length, not counting @code{BLOB}
columns). A @code{BLOB} uses 5 to 8 bytes plus the length of the @code{BLOB}
data.

@item
For each table having @code{BLOB} columns, a buffer is enlarged dynamically
to read in larger @code{BLOB} values. If you scan a table, a buffer as large
as the largest @code{BLOB} value is allocated.

@item
Table handlers for all in-use tables are saved in a cache and managed as a
FIFO. Normally the cache has 64 entries. If a table has been used by two
running threads at the same time, the cache contains two entries for the
table.
@xref{Table cache}.

@item
A @code{mysqladmin flush-tables} command closes all tables that are not in
use and marks all in-use tables to be closed when the currently executing
thread finishes. This will effectively free most in-use memory.
@end itemize

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

@node Compile and link options, MySQL indexes, Memory use, Performance
@section How compiling and linking affects the speed of @strong{MySQL}

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

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

On Linux, you will get the fastest code when compiling with @code{pgcc} and
@code{-O6}.  To compile @file{sql_yacc.cc} with these options, you need 180M
memory because
@code{gcc/pgcc} needs a lot of memory to make all functions inline.
You should also set @code{CXX=gcc} when configuring @strong{MySQL} to avoid
inclusion of the @code{libstdc++} library.

@itemize @bullet
@item
If you use @code{pgcc} and compile everything with @code{-O6}, the
@code{mysqld} server is 11% faster than with @code{gcc}.

@item
If you link dynamically (without @code{-static}), the result is 13% slower.

@item
If you connect using TCP/IP rather than Unix sockets, the result is 7.5%
slower.

@item
On a Sun SPARCstation 10, @code{gcc} 2.7.3 is 13% faster than Sun Pro C++ 4.2.

@item
On Solaris 2.5.1, MIT-pthreads is 8-12% slower than Solaris native threads.
@end itemize

The @strong{MySQL}-Linux distribution provided by TcX is compiled with
@code{pgcc} and linked statically.

@node MySQL indexes, Where optimizations , Compile and link options, Performance
@section How @strong{MySQL} uses indexes

All indexes (@code{PRIMARY}, @code{UNIQUE} and @code{INDEX()}) are stored
in B-trees. Strings are automatically prefix- and end-space compressed.
@xref{CREATE INDEX, , @code{CREATE INDEX}}.

Indexes are used to:
@itemize @bullet
@item
Quickly find the rows that match a @code{WHERE} clause.

@item
Retrieve rows from other tables when performing joins.

@item
Find the @code{MAX()} or @code{MIN()} value for a specific key.

@item
Sort or group a table if the sorting or grouping is done on a leftmost
prefix of a usable key (e.g., @code{ORDER BY key_part_1,key_part_2 }).  The
key is read in reverse order if all key parts are followed by @code{DESC}.

@item
Retrieve values without consulting the data file, in some cases.  If all used
columns for some table are numeric and form a leftmost prefix for some key,
the values may be retrieved from the index tree for greater speed.
@end itemize

Suppose you issue the following @code{SELECT} statement:

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

If a multiple-column index exists on @code{col1} and @code{col2}, the
appropriate rows can be fetched directly. If separate single-column
indexes exist on @code{col1} and @code{col2}, the optimizer decides
which index will find fewer rows and uses that index to fetch the rows.

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

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

@example
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;
@end example

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

@findex LIKE, and indexes
@findex LIKE, and wildcards
@cindex Indexes, and @code{LIKE}
@cindex Wildcards, and @code{LIKE}
@strong{MySQL} also uses indexes for @code{LIKE} comparisons if the argument
to @code{LIKE} is a constant string that doesn't start with a wildcard
character.  For example, the following @code{SELECT} statements use indexes:

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

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

The following @code{SELECT} statements will not use indexes:
@example
mysql> select * from tbl_name where key_col LIKE "%Patrick%";
mysql> select * from tbl_name where key_col LIKE other_col;
@end example

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

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

Any index that doesn't span all @code{AND} levels in the @code{WHERE} clause
is not used to optimize the query.

The following @code{WHERE} clauses use indexes:
@example
... WHERE index_part1=1 AND index_part2=2
... WHERE index=1 OR A=10 AND index=2      /* index = 1 OR index = 2 */
... WHERE index_part1='hello' AND index_part_3=5
          /* optimized like "index_part1='hello'" */
@end example

These @code{WHERE} clauses do @strong{NOT} use indexes:
@example
... WHERE index_part2=1 AND index_part3=2  /* index_part_1 is not used */
... WHERE index=1 OR A=10                  /* No index */
... WHERE index_part1=1 OR index_part2=10  /* No index spans all rows */
@end example

@cindex Optimizations
@node Where optimizations , LEFT JOIN optimization, MySQL indexes, Performance
@section How @strong{MySQL} optimizes @code{WHERE} clauses

(This section is incomplete; @strong{MySQL} does many optimizations.)

In general, when you want to make a slow @code{SELECT ... WHERE} faster, the
first thing to check is whether or not you can add an index. All references
between different tables should usually be done with indexes. You can use the
@code{EXPLAIN} command to determine which indexes are used for a
@code{SELECT}.
@xref{EXPLAIN, , @code{EXPLAIN}}.

Some of the optimizations performed by @strong{MySQL} are listed below:

@itemize @bullet
@item
Removal of unnecessary parentheses:
@example
   ((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)
@end example
@item
Constant folding:
@example
   (a<b AND b=c) AND a=5
-> b>5 AND b=c AND a=5
@end example
@item
Constant condition removal (needed because of constant folding):
@example
   (B>=5 AND B=5) OR (B=6 AND 5=5) OR (B=7 AND 5=6)
-> B=5 OR B=6
@end example
@item
Constant expressions used by indexes are evaluated only once.
@item
@code{COUNT(*)} on a single table without a @code{WHERE} is retrieved
directly from the table information.  This is also done for any @code{NOT NULL}
expression when used with only one table.
@item
Early detection of invalid constant expressions. @strong{MySQL} quickly
detects that some @code{SELECT} statements are impossible and returns no rows.
@item
@code{HAVING} is merged with @code{WHERE} if you don't use @code{GROUP
BY} or group functions (@code{COUNT()}, @code{MIN()}...)
@item
For each sub join, a simpler @code{WHERE} is constructed to get a fast
@code{WHERE} evaluation for each sub join and also to skip records as
soon as possible.
@cindex Constant table
@cindex Table, constant
@item
All constant tables are read first, before any other tables in the query.
A constant table is:
@itemize @minus
@item
An empty table or a table with 1 row.
@item
A table that is used with a @code{WHERE} clause on a @code{UNIQUE} index or a
@code{PRIMARY KEY}, where all index parts are used with constant expressions.
@end itemize
All the following tables are used as constant tables:
@example
mysql> SELECT * FROM t WHERE primary_key=1;
mysql> SELECT * FROM t1,t2
           WHERE t1.primary_key=1 AND t2.primary_key=t1.id;
@end example

@item
The best join combination to join the tables is found by trying all
possibilities :(. If all columns in @code{ORDER BY} and in @code{GROUP BY}
come from the same table, then this table is preferred first when joining.
@item
If there is an @code{ORDER BY} clause and a different @code{GROUP BY} clause,
or if the @code{ORDER BY} or @code{GROUP BY}
contains columns from tables other than the first table in the join
queue, a temporary table is created.
@item
If you use @code{SQL_SMALL_RESULT}, @strong{MySQL} will use an in-memory
temporary table.
@item
As @code{DISTINCT} is converted to a @code{GROUP BY} on all columns,
@code{DISTINCT} combined with @code{ORDER BY} will in many cases also need
a temporary table.
@item
Each table index is queried and the best index that spans less than 30% of
the rows is used. If no such index can be found, a quick table scan is used.
@item
In some cases, @strong{MySQL} can read rows from the index without even
consulting the data file.  If all columns used from the index are numeric,
then only the index tree is used to resolve the query.
@item
Before each record is output, those that do not match the @code{HAVING} clause
are skipped.
@end itemize

Some examples of queries that are very fast:

@example
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;
@end example

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

@example
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;
@end example

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

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

@node LEFT JOIN optimization, Table cache, Where optimizations , Performance
@section How @strong{MySQL} optimizes @code{LEFT JOIN}

@code{A LEFT JOIN B} is in @strong{MySQL} implemented as follows

@itemize @bullet
@item
The table @code{B} is set to be dependent on table @code{A}.
@item
The table @code{A} is set to be dependent on all tables (except @code{B})
that are used in the @code{LEFT JOIN} condition.
@item
All @code{LEFT JOIN} conditions are moved to the @code{WHERE} clause.
@item
All standard join optimizations are done, with the exception that a table is
always read after all tables it is dependent on.  If there is a circular
dependence then @strong{MySQL} will issue an error.
@item
All standard @code{WHERE} optimzations are done.
@item
If there is a row in @code{A} that matches the @code{WHERE} clause, but there
wasn't any row in @code{B} that matched the @code{LEFT JOIN} condition,
then an extra @code{B} row is generated with all columns set to @code{NULL}.
@end itemize

@cindex Symbolic links
@cindex Table cache
@node Table cache, Open tables, LEFT JOIN optimization, Performance
@section How @strong{MySQL} opens and closes tables

@menu
* Creating many tables::        Drawbacks of creating large numbers of tables in a database
@end menu

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

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

@itemize @bullet
@item
Tables that are not currently in use are released, in least-recently-used
order.

@item
If the cache is full and no tables can be released, but a new table needs to
be opened, the cache is temporarily extended as necessary.

@item
If the cache is in a temporarily-extended state and a table goes from in-use
to not-in-use state, it is closed and released from the cache.
@end itemize

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 @code{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.

@node Creating many tables,  , Table cache, Table cache
@subsection Drawbacks of creating large numbers of tables in a database

If you have many files in a directory, open, close and create operations will
be slow.  If you execute @code{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.

@node Open tables, Symbolic links, Table cache, Performance
@section Why so many open tables?

When you run @code{mysqladmin status}, you'll see something like this:

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

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

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

@node Symbolic links, Internal locking, Open tables, Performance
@section Using symbolic links for databases and tables

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

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

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

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

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

If you really need this, you must change the following code in
@file{mysys/mf_format.c}:

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

Change the code to this:

@example
if (realpath(to,buff))
@end example

@node Internal locking, Table efficiency, Symbolic links, Performance
@section How @strong{MySQL} locks tables

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

The locking method @strong{MySQL} uses for @code{WRITE} locks works as follows:

@itemize @bullet
@item
If there are no locks on the table, put a write lock on it.
@item
Otherwise, put the lock request in the write lock queue.
@end itemize

The locking method @strong{MySQL} uses for @code{READ} locks works as follows:

@itemize @bullet
@item
If there are no write locks on the table, put a read lock on it.
@item
Otherwise, put the lock request in the read lock queue.
@end itemize

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, @code{SELECT}
statements will wait until there are no more updates.

To work around this for the case where you want to do many @code{INSERT} and
@code{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:
@example
mysql> LOCK TABLES real_table WRITE, insert_table WRITE;
mysql> insert into real_table select * from insert_table;
mysql> delete from insert_table;
mysql> UNLOCK TABLES;
@end example

You can use the @code{LOW_PRIORITY} or @code{HIGH_PRIORITY} options with
@code{INSERT} if you want to prioritize retrieval in some specific cases.
@xref{INSERT, , @code{INSERT}}.

You could also change the locking code in @file{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.

@node Table efficiency, Table locking, Internal locking, Performance
@section How to arrange a table to be as fast/small as possible

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

@itemize @bullet
@item
Declare columns to be @code{NOT NULL} if possible. It makes everything faster
and you save one bit per column.

@item
Take advantage of the fact that all columns have default values. Insert
values explicitly only when the value to be inserted differs from the default.
You don't have to insert a value into the first @code{TIMESTAMP} column or
into an @code{AUTO_INCREMENT} column in an @code{INSERT} statement.
@xref{mysql_insert_id,  , @code{mysql_insert_id()}}.

@item
Use the smaller integer types if possible to get smaller tables. For example,
@code{MEDIUMINT} is often better than @code{INT}.

@item
If you don't have any variable-length columns (@code{VARCHAR}, @code{TEXT} or
@code{BLOB} columns), a fixed-size record format is used. This is much faster
but unfortunately may waste some space.
@xref{Row format}.

@item
To help @strong{MySQL} optimize queries better, run @code{isamchk --analyze}
on a table after it has been loaded with relevant data. This updates a
value for each index that indicates the average number of rows that have the
same value.  (For unique indexes, this is always 1, of course.)

@item
To sort an index and data according to an index, use
@code{isamchk --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!

@item
For @code{INSERT} statements, use multiple value lists if possible.  This
is much faster than using separate @code{INSERT} statements.

@item
When loading a table with data, use @code{LOAD DATA INFILE}. This is usually
20 times faster than using a lot of @code{INSERT} statements.
@xref{LOAD DATA, , @code{LOAD DATA}}.

You can even get more speed when loading data into a table with many indexes
using the following procedure:

@enumerate
@item
Create the table in @code{mysql} or Perl with @code{CREATE TABLE}.

@item
Execute @code{mysqladmin flush-tables}.

@item
Use @code{isamchk --keys-used=0 -rq /path/to/db/tbl_name}. This will remove all
usage of all indexes from the table.

@item
Insert data into the table with @code{LOAD DATA INFILE}.

@item
If you have @code{pack_isam} and want to compress the table, run
@code{pack_isam} on it.

@item
Recreate the indexes with @code{isamchk -r -q /path/to/db/tbl_name}.

@item
Execute @code{mysqladmin flush-tables}.
@end enumerate

@item
To get some more speed for both @code{LOAD DATA INFILE} and
@code{INSERT}, enlarge the key buffer.  This can be done with the
@code{-O key_buffer=#} option to @code{mysqld} or @code{safe_mysqld}.  For
example, 16M should be a good value if you have much RAM. :)

@item
When dumping data as text files for use by other programs, use
@code{SELECT ... INTO OUTFILE}. @xref{LOAD DATA, , @code{LOAD DATA}}.

@item
When doing many successive inserts or updates, you can get more speed by
locking your tables using @code{LOCK TABLES}. @code{LOAD DATA INFILE} and
@code{SELECT ...INTO OUTFILE} are atomic, so you don't have to use @code{LOCK
TABLES} when using them.
@xref{LOCK TABLES, , @code{LOCK TABLES}}.
@end itemize

To check how fragmented your tables are, run @code{isamchk -evi} on the
@file{.ISM} file.
@xref{Maintenance}.

@node Table locking, Insert speed, Table efficiency, Performance
@section Table locking issues

The table locking code in @strong{MySQL} is deadlock free.

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

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

As updates of databases normally are considered to be more important than
@code{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.

One main problem with this is the following:

@itemize @bullet
@item
A client issues a @code{SELECT} that takes a long time to run.
@item
Another client then issues an @code{INSERT} on a used table;  This client
will wait until the @code{SELECT} is finished..
@item
Another client issues another @code{SELECT} statement on the same table;  As
@code{INSERT} has higher priority than @code{SELECT}, this @code{SELECT}
will wait for the @code{INSERT} to finish.  It will also wait for the first
@code{SELECT} to finish!
@end itemize

Some possible solutions to this problem are:

@itemize @bullet
@item
Try to get the @code{SELECT} statements to run faster;  You may have to create
some summary tables to do this.

@item
Start @code{mysqld} with @code{--low-priority-inserts}.  This will give
all statements that update a table lower priority than a @code{SELECT}
statement. In this case the last @code{SELECT} statement in the previous
scenario would execute before the @code{INSERT} statement.

@item
You can give a specific @code{INSERT},@code{UPDATE} or @code{DELETE} statement
lower priority with the @code{LOW_PRIORITY} attribute.

@item
You can specify that all updates from a specific thread should be done with
low priority by using the SQL command: @code{SET SQL_LOW_PRIORITY_UPDATES=1}.
@xref{SET OPTION, , @code{SET OPTION}}.

@item
You can specify that a specific @code{SELECT} is very important with the
@code{HIGH_PRIORITY} attribute. @xref{SELECT, , @code{SELECT}}.

@item
If you mainly mix @code{INSERT} and @code{SELECT} statements, the
@code{DELAYED} attribute to @code{INSERT} will probably solve your problems.
@xref{INSERT, , @code{INSERT}}.

@item
If you have problems with @code{SELECT} and @code{DELETE}, the @code{LIMIT}
option to @code{DELETE} may help. @xref{DELETE, , @code{DELETE}}.
@end itemize

@node Insert speed, Delete speed, Table locking, Performance
@section Factors affecting the speed of @code{INSERT} statements

The time to insert a record consists of:

@itemize @bullet
@item
Connect:                 (3)
@item
Sending query to server: (2)
@item
Parsing query:           (2)
@item
Inserting record:        (1 x size of record)
@item
Inserting indexes:       (1 x indexes)
@item
Close:                   (1)
@end itemize

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

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

You can speed up insertions by locking your table and/or using multiple value
lists with @code{INSERT} statements.  Using multiple value lists can be up to
5 times faster than using separate inserts.

@example
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;
@end example

The main speed difference is that the index buffer is flushed to disk only
once, after all @code{INSERT} statements have completed. Normally there would
be as many index buffer flushes as there are different @code{INSERT}
statements. Locking is not needed if you can insert all rows with a single
statement.

Locking will also lower the total time of multi-connection tests, but the
maximum wait time for some threads will go up (because they wait for
locks).  For example:

@example
thread 1 does 1000 inserts
thread 2, 3, and 4 does 1 insert
thread 5 does 1000 inserts
@end example

If you don't use locking, 2, 3 and 4 will finish before 1 and 5. If you
use locking, 2, 3 and 4 probably will not finish before 1 or 5, but the
total time should be about 40% faster.

As @code{INSERT}, @code{UPDATE} and @code{DELETE} operations are very fast in
@strong{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 @code{LOCK
TABLES} followed by a @code{UNLOCK TABLES} once in a while (about each
1000 rows) to allow other threads access to the table. This would still
result in a nice performance gain.

Of course, @code{LOAD DATA INFILE} is much faster still.

If you are inserting a lot of rows from different clients, you can get higher
speed by using the @code{INSERT DELAYED} statement. @xref{INSERT, ,
@code{INSERT}}.

@node Delete speed, Optimize, Insert speed, Performance
@section Factors affecting the speed of @code{DELETE} statements

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. The default index cache is 1M; to get faster deletes, it
should be increased by several factors (try 16M if you have enough
memory).

@node Optimize, Row format, Delete speed, Performance
@section How do I get @strong{MySQL} to run at full speed?

Start by benchmarking your problem!  You can take any program from the
@strong{MySQL} benchmark suite (normally found in the @file{sql-bench}
directory) 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.

@itemize @bullet
@item
Start @code{mysqld} with the correct options. More memory gives more speed
if you have it. @xref{Server parameters}.
@item
Create indexes to make your @code{SELECT} statements faster.
@xref{MySQL indexes, , @strong{MySQL} indexes}.
@item
Optimize your column types to be as efficient as possible.  For example,
declere columns to be @code{NOT NULL} if possible.
@xref{Table efficiency}.
@item
@strong{MySQL} has two different levels of locks: Internal locks and
external locks. The internal locks ensures that all update/retrieve
operations are atomic (run without conflicts from other clients). The external
locks allows multiple @strong{MySQL} servers to run on the same data and
allows you to use @code{isamchk} to check tables without taking down @code{mysqld}.

The @code{--skip-locking} option disables external locking (file
locking) between SQL requests. This gives greater speed but has the
following consequences:

@itemize @minus
@item
You @strong{MUST} flush all tables with @code{mysqladmin flush-tables} before
you try to check or repair tables with @code{isamchk}. (@code{isamchk -d
tbl_name} is always allowed, since that simply displays table information.)
@item
You can't run two @strong{MySQL} servers on the same data files, if
both are going to update the same tables.
@end itemize

The @code{--skip-locking} option is on by default when compiling with
MIT-pthreads, because @code{flock()} isn't fully supported by MIT-pthreads on
all platforms.

The only case when you can't use @code{--skip-locking} is if you run
multiple @strong{MySQL} SERVERS (not clients) on the same data (or run
@code{isamchk} on the table without first flushing the @code{mysqld} server tables
first).

You can still use @code{LOCK TABLES} / @code{UNLOCK TABLES} even if you are
using @code{--skip-locking}

@item
If updates are a problem, you can 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.
@item
On FreeBSD systems, if the problem is with MIT-pthreads, upgrading to FreeBSD
3.0 (or higher) should help. This makes it possible to use Unix sockets (with
FreeBSD, this is quicker than connecting using TCP/IP with MIT-pthreads) and
the threads package is much more integrated.
@item
@code{GRANT} checking on the table or column level will decrease performance.
@end itemize

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

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

The above shows that @strong{MySQL} can execute 1,000,000 @code{+} expressions
in 0.32 seconds on a simple @code{PentiumII 400MHz}.

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

@node Row format, Table types, Optimize, Performance
@section What are the different row formats? Or, when should @code{VARCHAR/CHAR} be used?

@strong{MySQL} dosen't have true SQL @code{VARCHAR} types.

Instead, @strong{MySQL} has three different ways to store records and uses
these to emulate @code{VARCHAR}.

If a table doesn't have any @code{VARCHAR}, @code{BLOB} or @code{TEXT}
columns, a fixed row size is used. Otherwise a dynamic row size is
used.  @code{CHAR} and @code{VARCHAR} columns are treated identically from
the application's point of view; both have trailing spaces removed
when the columns are retrieved.

You can check the format used in a table with @code{isamchk -d} (@code{-d}
means ``describe the table'').

@strong{MySQL} has three different table formats: fixed-length, dynamic
and compressed.  These are compared below.

@noindent
@strong{Fixed-length tables}

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

@noindent
@strong{Dynamic tables}

@itemize @bullet
@item
This format is used if the table contains any @code{VARCHAR}, @code{BLOB}
or @code{TEXT} columns.
@item
All string columns are dynamic (except those with a length less than 4).
@item
Each record is preceded by a bitmap indicating which columns are empty
(@code{''}) for string columns, or zero for numeric columns (this isn't the
same as columns containing @code{NULL} values).  If a string column has a
length of zero after removal of trailing spaces, or a numeric column has a
value of zero, it is marked in the bit map and not saved to disk.  Non-empty
strings are saved as a length byte plus the string contents.
@item
Usually takes much less disk space than fixed-length tables.
@item
Each record uses only as much space as is required. If a record becomes
larger, it is split into as many pieces as required.  This results in record
fragmentation.
@item
If you update a row with information that extends the row length, the row
will be fragmented.  In this case, you may have to run @code{isamchk -r} from
time to time to get better performance.
Use @code{isamchk -ei tbl_name} for some statistics.
@item
Not as easy to reconstruct after a crash, because a record may be fragmented
into many pieces and a link (fragment) may be missing.
@item
The expected row length for dynamic sized records is:

@example
3
+ (number of columns + 7) / 8
+ (number of char columns)
+ packed size of numeric columns
+ length of strings
+ (number of NULL columns + 7) / 8
@end example

There is a penalty of 6 bytes for each link. A dynamic record is linked
whenever an update causes an enlargement of the record. Each new link will be
at least 20 bytes, so the next enlargement will probably go in the same link.
If not, there will be another link. You may check how many links there are
with @code{isamchk -ed}. All links may be removed with @code{isamchk -r}.
@end itemize

@noindent
@strong{Compressed tables}

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

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

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

@node Table types,  , Row format, Performance
@section @strong{MySQL} table types.

Table types are introduced in @strong{MySQL} 3.23!

When you create a new table, you can tell @strong{MySQL} which table type it
should use for the table.  @strong{MySQL} will always create a @code{.frm}
file to hold the table and column definitions.  Depending on the table type
the index and data will be stored in other files.

@itemize @bullet
@item @code{ISAM}

This is the original @strong{MySQL} table type.  This uses a @code{B-tree} index.
The index is stored in a file with the @code{.ISM} extension and the data is
stored in file with the @code{.ISD} extension.  You can check/repair
@code{ISAM} tables with the @code{isamchk} utility. @xref{Crash recovery}.
@code{ISAM} tables are not binary portable across OS/Platforms.

@code{ISAM} has the following features/properties:

@itemize @bullet
@item Compressed and fixed length keys
@item Fixed and dynamic record length
@item 16 keys with 16 key parts / key
@item Max key length 256 (default)
@item Data is stored in machine format;  Fast but is machine/OS dependent.
@end itemize

@item @code{MYISAM}
@code{MYISAM} is the default table type in @strong{MySQL} 3.22. It's based
on the @code{ISAM} code and has a lot of useful extensions.

The index is stored in a file with the @code{.MYI} extension and the data is
stored in file with the @code{.MYD} extension.  You can check/repair
@code{ISAM} tables with the @code{myisamchk} utility.
@xref{Crash recovery} 

The following is new in @code{MYISAM}:

@itemize @bullet
@item
Supports for big files (63 bit) on OSes that support big files.
@item
All data are stored with low byte first.  This makes the data machine
and OS independent.
@item
All number keys are stored with high byte first to give better compression.
@item
Internal handling of one @code{AUTO_INCREMENT} column.  @code{MYISAM}
will automatically update this on @code{INSERT/UPDATE}.  The
@code{AUTO_INCREMENT} value can be reset with @code{myisamchk}.
This will make @code{AUTO_INCREMENT} columns faster and old numbers
will not be reused.
@item
Maximum key length is now 500 by default.  In cases of keys longer than 250,
a bigger key block size than the default of 1024 bytes is used for this key.
@item
Maximum number of keys/table enlarged to 32 as default. This can be
enlarged to 64 without having to recompile @code{myisamchk}.
@item
There is a flag in the @code{MYISAM} file that indicates whether or not the
table was closed correctly.  This will soon be used for automatic repair
in the @strong{MySQL} server.
@item
@code{myisamchk} will now mark tables as checked. @code{myisamchk
--fast} will only check those tables that don't have this mark.
@item
@code{myisamchk -a} stores statistics for key parts (and not only for
whole keys as in @code{NISAM}).
@item
Dynamic size rows will now be much less fragmented when mixing deletes
with updates and inserts.  This is done by automatically combining adjacent
deleted blocks and by extending blocks if the next block is deleted.
@item
@code{myisampack} (called @code{pack_isam} in @code{NISAM}) can pack
@code{BLOB} and @code{VARCHAR}columns.
@end itemize

@code{MYISAM} also supports the following things, which @strong{MySQL}
will be able to use in the near future.

@itemize @bullet
@item
@code{BLOB} and @code{TEXT} columns can be indexed.
@item
Support for a true @code{VARCHAR} type; A @code{VARCHAR} column starts
with a length stored in 2 bytes.
@item
Tables with @code{VARCHAR} may have fixed or dynamic record length.
@item
@code{VARCHAR} and @code{CHAR} may be up to 65K.
All key segments have their own language definition. This will enable
@strong{MySQL} to have different language definitions per column.
@item
@code{NULL} values are allowed in indexed columns.  This takes 0-1 bytes/key.
@item
A hashed computed index can be used for @code{UNIQUE}; This will allow
you to have @code{UNIQUE} on any combination of columns in a table. (You
can't search on a @code{UNIQUE} computed index, however.)
@end itemize

@item @code{HEAP}
@code{HEAP} tables use a hashed index and are stored in memory.
This makes them very fast, but if @strong{MySQL} crashes you will lose all
data stored in them.  @code{HEAP} is very usable as temporary tables!

@example
CREATE TABLE test TYPE=HEAP SELECT ip,SUM(downloads) as down FROM log_table GROUP BY ip;
SELECT COUNT(ip),AVG(down) from test;
drop table test;
@end example

Here are some things you should consider when you use @code{HEAP} tables:

@itemize @bullet
@item
You should always use specify @code{MAX_ROWS} in the @code{CREATE} statement 
to ensure that you accidently do not use all memory.
@item
Indexes will only be used with @code{=} and @code{<=>} (but are VERY fast).
@item
@code{HEAP} tables uses a fixed record length format.
@item
@code{HEAP} doesn't support @code{BLOB/TEXT} columns.
@item
@code{HEAP} doesn't support @code{AUTO_INCREMENT} columns.
@item
@code{HEAP} doesn't support an index on a @code{NULL} column.
@item
You can have non-unique keys in a @code{HEAP} table (not that normal
with hashed tables).
@item
@code{HEAP} tables are shared between all clients (just like any other table).
@item
Data for @code{HEAP} tables are allocated in small blocks. The tables are
100% dynamic (on inserting). No overflow areas and no extra key space
is needed.  Deleted rows are put in a linked list and will be reused
when you insert new data into the table.
@item
To free memory, you should execute @code{DELETE FROM heap_table} or
@code{DROP TABLE heap_table}.
@item
To ensure that you accidentally don't do anything stupid, you can't create
@code{HEAP} tables bigger than @code{max_heap_table_size}.
@end itemize

@end itemize

@node Benchmarks, Tools, Performance, Top
@chapter The @strong{MySQL} benchmark suite

This should contain a technical description of the @strong{MySQL}
benchmark suite (and @code{crash-me}) but that description is not
written yet. Currently, you should look at the code and results in the
@file{bench} directory in the distribution (and of course on the web
page at @uref{http://www.mysql.com/crash-me-choose.htmy}).

It is meant to be a benchmark that will tell any user what things a
given SQL implementation performs well or poorly at.


@code{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:

@itemize @bullet
@item
What column types are supported
@item
How many indexes are supported
@item
What functions are supported
@item
How big a query can be
@item
How big a @code{VARCHAR} column can be
@end itemize

@node Tools, Maintenance, Benchmarks, Top
@chapter @strong{MySQL} Utilites

@menu
* Programs::                    What do the executables do?
* mysqladmin::                  Administering a @strong{MySQL} server
* mysqldump::                   Dumping the structure and data from @strong{MySQL} databases and tables
* mysqlimport::                 Importing data from text files
* pack_isam::                   The @strong{MySQL} compressed read only table generator
@end menu

@cindex Environment variables
@node Programs, mysqladmin, Tools, Tools
@section Overview of the different @strong{MySQL} programs

All @strong{MySQL} clients that communicate with the server using the
@code{mysqlclient} library use the following environment variables:

@tindex MYSQL_UNIX_PORT environment variable
@tindex Environment variable, MYSQL_UNIX_PORT
@tindex MYSQL_TCP_PORT environment variable
@tindex Environment variable, MYSQL_TCP_PORT
@tindex MYSQL_PWD environment variable
@tindex Environment variable, MYSQL_PWD
@tindex MYSQL_DEBUG environment variable
@tindex Environment variable, MYSQL_DEBUG
@multitable @columnfractions .25 .75
@item @strong{Name} @tab @strong{Description}
@item @code{MYSQL_UNIX_PORT} @tab The default socket; used for connections to @code{localhost}
@item @code{MYSQL_TCP_PORT}  @tab The default TCP/IP port
@item @code{MYSQL_PWD} @tab The default password
@item @code{MYSQL_DEBUG} @tab Debug-trace options when debugging
@item @code{TMPDIR} @tab The directory where temporary tables/files are created
@end multitable

Use of @code{MYSQL_PWD} is insecure.
@xref{Connecting}.

@tindex MYSQL_HISTFILE environment variable
@tindex Environment variable, MYSQL_HISTFILE
@tindex HOME environment variable
@tindex Environment variable, HOME
@cindex History file
@cindex Command line history
@tindex .mysql_history file
The @file{mysql} client uses the file named in the @code{MYSQL_HISTFILE}
environment variable to save the command line history. The default value for
the history file is @file{$HOME/.mysql_history}, where @code{$HOME} is the
value of the @code{HOME} environment variable.

All @strong{MySQL} programs take many different options. However, every
@strong{MySQL} program provides a @code{--help} option that you can use
to get a full description of the program's different options. For example, try
@code{mysql --help}.

The list below briefly describes the @strong{MySQL} programs:

@table @code

@cindex @code{isamchk}
@item isamchk
Utility to describe, check, optimize and repair @strong{MySQL} tables.
Because @code{isamchk} has many functions, it is described in its own
chapter.
@xref{Maintenance}.

@cindex @code{make_binary_release}
@item make_binary_release
Makes a binary release of a compiled @strong{MySQL}. This could be sent
by FTP to @file{/pub/mysql/Incoming} on @code{ftp.tcx.se} for the
convenience of other @strong{MySQL} users.

@cindex @code{msql2mysql}
@item msql2mysql
A shell script that converts @code{mSQL} programs to @strong{MySQL}. It doesn't
handle all cases, but it gives a good start when converting.

@cindex Scripts
@cindex @code{mysql}
@item mysql
@code{mysql} is a simple SQL shell (with GNU @code{readline} capabilities).
It supports interactive and non-interactive use. When used interactively,
query results are presented in an ASCII-table format. When used
non-interactively (e.g., as a filter), the result is presented in
tab-separated format.  (The output format can be changed using command-line
options.)  You can run scripts simply like this:

@example
shell> mysql database < script.sql > output.tab
@end example

If you have problems due to insufficient memory in the client, use the
@code{--quick} option!  This forces @code{mysql} to use
@code{mysql_use_result()} rather than @code{mysql_store_result()} to retrieve
the result set.

@cindex @code{mysqlaccess}
@item mysqlaccess
A script that checks the access privileges for a host, user and database
combination.

@cindex @code{mysqladmin}
@item mysqladmin
Utility for performing administrative operations, such as creating or
dropping databases, reloading the grant tables, flushing tables to disk and
reopening log files.  @code{mysqladmin} can also be used to retrieve version,
process and status information from the server.
@xref{mysqladmin, , @code{mysqladmin}}.

@cindex @code{mysqlbug}
@item mysqlbug
The @strong{MySQL} bug report script.  This script should always be used when
filing a bug report to the @strong{MySQL} list.

@cindex @code{mysqld}
@item mysqld
The SQL daemon. This should always be running.

@cindex @code{mysqldump}
@item mysqldump
Dumps a @strong{MySQL} database into a file as SQL statements or
as tab-separated text files. Enhanced freeware originally by Igor Romanenko.
@xref{mysqldump, , @code{mysqldump}}.

@cindex @code{mysqlimport}
@item mysqlimport
Imports text files into their respective tables using @code{LOAD DATA
INFILE}. @xref{mysqlimport, , @code{mysqlimport}}.

@cindex @code{mysqlshow}
@item mysqlshow
Displays information about databases, tables, columns and indexes.

@cindex @code{mysql_install_db}
@item mysql_install_db
Creates the @strong{MySQL} grant tables with default privileges. This is
usually executed only once, when first installing @strong{MySQL}
on a system.

@cindex @code{replace}
@item replace
A utility program that is used by @code{msql2mysql}, but that has more
general applicability as well.  @code{replace} changes strings in place in
files or on the standard input. Uses a finite state machine to match longer
strings first. Can be used to swap strings. For example, this command
swaps @code{a} and @code{b} in the given files:

@example
shell> replace a b b a -- file1 file2 ...
@end example

@cindex @code{safe_mysqld}

@item safe_mysqld
A script that starts the @code{mysqld} daemon with some safety features, such
as restarting the server when an error occurs and logging runtime information
to a log file.
@end table

@node mysqladmin, mysqldump, Programs, Tools
@section Administering a @strong{MySQL} server

Utility for performing administrative operations. The syntax is:

@example
shell> mysqladmin [OPTIONS] command [command-option] command ...
@end example

You can get a list of the options your version of @code{mysqladmin} supports
by executing @code{mysqladmin --help}.

The current @code{mysqladmin} supports the following commands:

@multitable @columnfractions .3 .7
@item create databasename @tab Create a new database.
@item drop databasename  @tab Delete a database and all its tables.
@item extended-status @tab Gives an extended status message from the server.
@item flush-hosts @tab Flush all cached hosts.
@item flush-logs @tab Flush all logs.
@item flush-tables @tab Flush all tables.
@item flush-privileges @tab Reload grant tables (same as reload)
@item kill id,id,...  @tab Kill mysql threads.
@item password @tab new-password Change old password to new-password
@item ping @tab Check if mysqld is alive
@item processlist @tab Show list of active threads in server
@item reload @tab Reload grant tables
@item refresh @tab Flush all tables and close and open logfiles
@item shutdown @tab Take server down
@item status @tab Gives a short status message from the server
@item variables @tab Prints variables available
@item version @tab Get version info from server
@end multitable

All commands can be shortened to their unique prefix.  For example:

@example
shell> mysqladmin proc stat
+----+-------+-----------+----+-------------+------+-------+------+
| Id | User  | Host      | db | Command     | Time | State | Info |
+----+-------+-----------+----+-------------+------+-------+------+
| 6  | monty | localhost |    | Processlist | 0    |       |      |
+----+-------+-----------+----+-------------+------+-------+------+
Uptime: 10077  Threads: 1  Questions: 9  Slow queries: 0  Opens: 6  Flush tables: 1  Open tables: 2  Memory in use: 1092K  Max memory used: 1116K
@end example

The @code{mysqladmin status} command result has the following columns:

@multitable @columnfractions .3 .7
@item Uptime @tab Number of seconds the @strong{MySQL} server have been up
@item Threads @tab Number of active threads (clients)
@item Questions @tab Number of questions from clients since @code{mysqld} was started
@item Slow queries @tab Queries that has taken more than @code{long_query_time} seconds
@item Opens @tab How many tables @code{mysqld} have opened.
@item Flush tables @tab Number of @code{flush ...}, @code{refresh} and @code{reload} commands.
@item Open tables @tab Number of tables that are open now
@item Memory in use @tab Memory allocated directly by the mysqld code (only available when @strong{MySQL} is compiled with --with-debug)
@item Max memory used @tab Maximum memory allocated directly by the mysqld code (only available when @strong{MySQL} is compiled with --with-debug)
@end multitable

@node mysqldump, mysqlimport, mysqladmin, Tools
@section Dumping the structure and data from @strong{MySQL} databases and tables

Utility to dump a database or a collection of database for backup or
for transferring the data to another SQL server.  The dump will contain SQL
statements to create the table and/or populate the table.

@example
shell> mysqldump [OPTIONS] database [tables]
@end example

If you don't give any tables, the whole database will be dumped.

You can get a list of the options your version of @code{mysqldump} supports
by executing @code{mysqldump --help}.

@code{mysqldump} supports the following options:

@table @code
@item --add-locks
Add @code{LOCK TABLES} before and @code{UNLOCK TABLE} after each table dump.
(To get faster inserts into @strong{MySQL}).
@item --add-drop-table
Add a @code{drop table} before each create statement.
@item --allow-keywords
Allow creation of column names that are keywords.  This works by
prefixing each column name with the table name.
@item -c, --complete-insert
Use complete insert statements (with column names).
@item -C, --compress
Compress all information between the client and the server if both support
compression.
@item --delayed
Insert rows with the @code{INSERT DELAYED} command.
@item -e, --extended-insert
Use the new multiline @code{INSERT} syntax. (Gives more compact and
faster inserts statements)
@item -#, --debug[=option_string]
Trace usage of the program (for debugging).
@item --help
Display a help message and exit.
@item --fields-terminated-by=...
@itemx --fields-enclosed-by=...
@itemx --fields-optionally-enclosed-by=...
@itemx --fields-escaped-by=...
@itemx --fields-terminated-by=...
These options are used with the @code{-T} option and have the same
meaning as the corresponding clauses for @code{LOAD DATA INFILE}.
@xref{LOAD DATA, , @code{LOAD DATA}}.
@item -F, --flush-logs
Flush logs file in the @strong{MySQL} server before starting the dump.
@item -f, --force,
Continue even if we get an SQL error during a table dump.
@item -h, --host=..
Dump data from the @strong{MySQL} server on the named host. The default host
is @code{localhost}.
@item -l, --lock-tables.
Lock all tables for starting the dump.
@item -t, --no-create-info
Don't write table creation info (The @code{CREATE TABLE} statment)
@item -d, --no-data
Don't write any row information for the table.  This is very useful if you
just want to get a dump of the structure for a table!
@item --opt
Same as @code{--quick --add-drop-table --add-locks --extended-insert
--use-locks}.  Should give you the fastest possible dump for reading
into a @strong{MySQL} server.
@item -pyour_pass, --password[=your_pass]
The password to use when connecting to the server. If you specify
no @samp{=your_pass} part,
@code{mysqldump} solicits the password from the terminal.
@item -P port_num, --port=port_num
The TCP/IP port number to use for connecting to a host.  (This is used for
connections to hosts other than @code{localhost}, for which Unix sockets are
used.)
@item  -q, --quick
Don't buffer query, dump directly to stdout;  Uses @code{mysql_use_result()}
to do this.
@item -S /path/to/socket, --socket=/path/to/socket
The socket file to use when connecting to @code{localhost} (which is the
default host).
@item  -T, --tab=path-to-some-directory
Creates a @code{table_name.sql} file, that conntains the SQL CREATE commands,
and a @code{table_name.txt} file, that contains the data, for each give table.
@strong{NOTE}: This only works if @code{mysqldump} is run on the same
machine as the @code{mysqld} daemon.  The format of the @code{.txt} file
is made according to the @code{--fields-xxx} and @code{--lines--xxx} options.
@item -u user_name, --user=user_name
The @strong{MySQL} user name to use when connecting to the server. The
default value is your Unix login name.
@item -O var=option, --set-variable var=option
Set the value of a variable.  The possible variables are listed below.
@item -v, --verbose
Verbose mode.  Print out more information what the program does.
@item -V, --version
Print version information and exit.
@item -w, --where='where-condition'
Dump only selected records; Note that QUOTES are mandatory!

@example
"--where=user='jimf'" "-wuserid>1" "-wuserid<1"
@end example
@end table

The most normal use of @code{mysqldump} is probably for making a backup of
whole database:

@example
mysqldump --opt database > backup-file.sql
@end example

But it's also very useful to populate another @strong{MySQL} server with
information from a databas:

@example
mysqldump --opt database | mysql ---host=remote-host -C database
@end example

@node mysqlimport, pack_isam, mysqldump, Tools
@section Importing data from text files

@code{mysqlimport} provides a command line interface to the @code{LOAD DATA
INFILE} SQL statement.  Most options to @code{mysqlimport} correspond
directly to the same options to @code{LOAD DATA INFILE}.
@xref{LOAD DATA, , @code{LOAD DATA}}.

@code{mysqlimport} is invoked like this:

@example
shell> mysqlimport [options] filename ...
@end example

For each text file named on the command line,
@code{mysqlimport} strips any extension from the filename and uses the result
to determine which table to import the file's contents into.  For example,
files named @file{patient.txt}, @file{patient.text} and @file{patient} would
all be imported into a table named @code{patient}.

@code{mysqlimport} supports the following options:

@table @code
@item -C, --compress
Compress all information between the client and the server if both support
compression.

@item -#, --debug[=option_string]
Trace usage of the program (for debugging).

@item -d, --delete
Empty the table before importing the text file.

@item --fields-terminated-by=...
@itemx --fields-enclosed-by=...
@itemx --fields-optionally-enclosed-by=...
@itemx --fields-escaped-by=...
@itemx --fields-terminated-by=...
These options have the same meaning as the corresponding clauses for
@code{LOAD DATA INFILE}. @xref{LOAD DATA, , @code{LOAD DATA}}.

@item -f, --force
Ignore errors.  For example, if a table for a text file doesn't exist,
continue processing any remaining files.  Without @code{--force},
@code{mysqlimport} exits if a table doesn't exist.

@item --help
Display a help message and exit.

@item -h host_name, --host=host_name
Import data to the @strong{MySQL} server on the named host. The default host
is @code{localhost}.

@item -i, --ignore
See the description for the @code{--replace} option.

@item -l, --lock-tables
Lock @strong{ALL} tables for writing before processing any text files. This
ensures that all tables are synchronized on the server.

@item -L, --local
Read input files from the client.  By default, text files are assumed to be on
the server if you connect to @code{localhost} (which is the default host).

@item -pyour_pass, --password[=your_pass]
The password to use when connecting to the server. If you specify
no @samp{=your_pass} part,
@code{mysqlimport} solicits the password from the terminal.

@item -P port_num, --port=port_num
The TCP/IP port number to use for connecting to a host.  (This is used for
connections to hosts other than @code{localhost}, for which Unix sockets are
used.)

@item -r, --replace
The @code{--replace} and @code{--ignore} options control handling of input
records that duplicate existing records on unique key values.  If you specify
@code{--replace}, new rows replace existing rows that have the same unique key
value. If you specify @code{--ignore}, input rows that duplicate an existing
row on a unique key value are skipped.  If you don't specify either option, an
error occurs when a duplicate key value is found, and the rest of the text
file is ignored.

@item  -s, --silent
Silent mode.  Write output only when errors occur.

@item -S /path/to/socket, --socket=/path/to/socket
The socket file to use when connecting to @code{localhost} (which is the
default host).

@item -u user_name, --user=user_name
The @strong{MySQL} user name to use when connecting to the server. The
default value is your Unix login name.

@item -v, --verbose
Verbose mode.  Print out more information what the program does.

@item -V, --version
Print version information and exit.
@end table

@cindex @code{pack_isam}
@node pack_isam,  , mysqlimport, Tools
@section The @strong{MySQL} compressed read-only table generator

@code{pack_isam} is an extra utility that you get when you order more than 10
licenses or extended support. Since @code{pack_isam} is distributed only in
binary form, @code{pack_isam} is available only on some platforms.

Of course, all future updates to @code{pack_isam} are included in the
price. @code{pack_isam} may at some time be included as standard when
we get some kind of turnover for @strong{MySQL}.

@code{pack_isam} works by compressing each column in the table separately.
The information needed to decompress columns is read into memory when the
table is opened. This results in much better performance when accessing
individual records, since you only have to uncompress exactly one record, not
a much larger disk block like when using Stacker on MS-DOS.
Usually, @code{pack_isam} packs the data file 40%-70%.

@strong{MySQL} uses memory mapping (@code{mmap()}) on compressed tables and
falls back to normal read/write file usage if @code{mmap()} doesn't work.

There are currently two limitations with @code{pack_isam}:
@itemize @bullet
@item
After packing, the table is read only.
@item
It can't pack @code{BLOB} columns, yet.
@end itemize

Fixing these limitations is on our TODO list but with low priority.

@code{pack_isam} is invoked like this:

@example
shell> pack_isam [options] filename ...
@end example

Each filename should be the name of an index (@file{.ISM}) file.  If you
are not in the database directory, you should specify the pathname to the
file.  It is permissible to omit the @file{.ISM} extension.

@code{pack_isam} supports the following options:

@table @code
@item -b, --backup
Make a backup of the table as @code{tbl_name.OLD}.

@item -#, --debug=debug_options
Output debug log. The @code{debug_options} string often is
@code{'d:t:o,filename'}.

@item -f, --force
Force packing of the table even if it becomes bigger or if the temporary file
exists.  (@code{pack_isam} creates a temporary file named @file{tbl_name.TMD}
while it compresses the table.  If you kill @code{pack_isam}, the @file{.TMD}
file may not be deleted.  Normally, @code{pack_isam} exits with an error if
it finds that @file{tbl_name.TMD} exists.  With @code{--force},
@code{pack_isam} packs the table anyway.

@item -?, --help
Display a help message and exit.

@item -j big_tbl_name, --join=big_tbl_name
Join all tables named on the command line into a single table
@code{big_tbl_name}.  All tables that are to be combined
MUST be identical (same column names and types, same indexes, etc.)

@item -p #, --packlength=#
Specify the record length storage size, in bytes.  The value should be 1, 2
or 3.  (@code{pack_isam} stores all rows with length pointers of 1, 2 or 3
bytes.  In most normal cases, @code{pack_isam} can determine the right length
value before it begins packing the file, but it may notice during the packing
process that it could have used a shorter length. In this case,
@code{pack_isam} will print a note that the next time you pack the same file,
you could use a shorter record length.)

@item -s, --silent
Silent mode.  Write output only when errors occur.

@item -t, --test
Don't pack table, only test packing it.

@item -T dir_name, --tmp_dir=dir_name
Use the named directory as the location in which to write the temporary table.

@item -v, --verbose
Verbose mode.  Write info about progress and packing result.

@item -V, --version
Display version information and exit.

@item -w, --wait
Wait and retry if table is in use.
If the @code{mysqld} server was invoked with the @code{--skip-locking}
option, it is not a good idea to invoke @code{pack_isam} if the table might
be updated during the packing process.
@end table

The sequence of commands shown below illustrates a typical table compression
session:

@example
shell> ls -l station.*
-rw-rw-r--   1 monty    my         994128 Apr 17 19:00 station.ISD
-rw-rw-r--   1 monty    my          53248 Apr 17 19:00 station.ISM
-rw-rw-r--   1 monty    my           5767 Apr 17 19:00 station.frm

shell> isamchk -dvv station

ISAM file:     station
Isam-version:  2
Creation time: 1996-03-13 10:08:58
Recover time:  1997-02-02  3:06:43
Data records:              1192  Deleted blocks:              0
Datafile: Parts:           1192  Deleted data:                0
Datafile pointer (bytes):     2  Keyfile pointer (bytes):     2
Max datafile length:   54657023  Max keyfile length:   33554431
Recordlength:               834
Record format: Fixed length

table description:
Key Start Len Index   Type                       Root  Blocksize    Rec/key
1   2     4   unique  unsigned long              1024       1024          1
2   32    30  multip. text                      10240       1024          1

Field Start Length Type
1     1     1
2     2     4
3     6     4
4     10    1
5     11    20
6     31    1
7     32    30
8     62    35
9     97    35
10    132   35
11    167   4
12    171   16
13    187   35
14    222   4
15    226   16
16    242   20
17    262   20
18    282   20
19    302   30
20    332   4
21    336   4
22    340   1
23    341   8
24    349   8
25    357   8
26    365   2
27    367   2
28    369   4
29    373   4
30    377   1
31    378   2
32    380   8
33    388   4
34    392   4
35    396   4
36    400   4
37    404   1
38    405   4
39    409   4
40    413   4
41    417   4
42    421   4
43    425   4
44    429   20
45    449   30
46    479   1
47    480   1
48    481   79
49    560   79
50    639   79
51    718   79
52    797   8
53    805   1
54    806   1
55    807   20
56    827   4
57    831   4

shell> pack_isam station.ISM
Compressing station.ISM: (1192 records)
- Calculating statistics

normal:     20  empty-space:      16  empty-zero:        12  empty-fill:  11
pre-space:   0  end-space:        12  table-lookups:      5  zero:         7
Original trees:  57  After join: 17
- Compressing file
87.14%

shell> ls -l station.*
-rw-rw-r--   1 monty    my         127874 Apr 17 19:00 station.ISD
-rw-rw-r--   1 monty    my          55296 Apr 17 19:04 station.ISM
-rw-rw-r--   1 monty    my           5767 Apr 17 19:00 station.frm

shell> isamchk -dvv station

ISAM file:     station
Isam-version:  2
Creation time: 1996-03-13 10:08:58
Recover time:  1997-04-17 19:04:26
Data records:              1192  Deleted blocks:              0
Datafile: Parts:           1192  Deleted data:                0
Datafilepointer (bytes):      3  Keyfile pointer (bytes):     1
Max datafile length:   16777215  Max keyfile length:     131071
Recordlength:               834
Record format: Compressed

table description:
Key Start Len Index   Type                       Root  Blocksize    Rec/key
1   2     4   unique  unsigned long             10240       1024          1
2   32    30  multip. text                      54272       1024          1

Field Start Length Type                         Huff tree  Bits
1     1     1      constant                             1     0
2     2     4      zerofill(1)                          2     9
3     6     4      no zeros, zerofill(1)                2     9
4     10    1                                           3     9
5     11    20     table-lookup                         4     0
6     31    1                                           3     9
7     32    30     no endspace, not_always              5     9
8     62    35     no endspace, not_always, no empty    6     9
9     97    35     no empty                             7     9
10    132   35     no endspace, not_always, no empty    6     9
11    167   4      zerofill(1)                          2     9
12    171   16     no endspace, not_always, no empty    5     9
13    187   35     no endspace, not_always, no empty    6     9
14    222   4      zerofill(1)                          2     9
15    226   16     no endspace, not_always, no empty    5     9
16    242   20     no endspace, not_always              8     9
17    262   20     no endspace, no empty                8     9
18    282   20     no endspace, no empty                5     9
19    302   30     no endspace, no empty                6     9
20    332   4      always zero                          2     9
21    336   4      always zero                          2     9
22    340   1                                           3     9
23    341   8      table-lookup                         9     0
24    349   8      table-lookup                        10     0
25    357   8      always zero                          2     9
26    365   2                                           2     9
27    367   2      no zeros, zerofill(1)                2     9
28    369   4      no zeros, zerofill(1)                2     9
29    373   4      table-lookup                        11     0
30    377   1                                           3     9
31    378   2      no zeros, zerofill(1)                2     9
32    380   8      no zeros                             2     9
33    388   4      always zero                          2     9
34    392   4      table-lookup                        12     0
35    396   4      no zeros, zerofill(1)               13     9
36    400   4      no zeros, zerofill(1)                2     9
37    404   1                                           2     9
38    405   4      no zeros                             2     9
39    409   4      always zero                          2     9
40    413   4      no zeros                             2     9
41    417   4      always zero                          2     9
42    421   4      no zeros                             2     9
43    425   4      always zero                          2     9
44    429   20     no empty                             3     9
45    449   30     no empty                             3     9
46    479   1                                          14     4
47    480   1                                          14     4
48    481   79     no endspace, no empty               15     9
49    560   79     no empty                             2     9
50    639   79     no empty                             2     9
51    718   79     no endspace                         16     9
52    797   8      no empty                             2     9
53    805   1                                          17     1
54    806   1                                           3     9
55    807   20     no empty                             3     9
56    827   4      no zeros, zerofill(2)                2     9
57    831   4      no zeros, zerofill(1)                2     9
@end example

The information printed by @code{pack_isam} is described below:

@table @code
@item normal
The number of columns for which no extra packing is used.

@item empty-space
The number of columns containing
values that are only spaces; these will occupy 1 bit.

@item empty-zero
The number of columns containing
values that are only binary 0's; these will occupy 1 bit.

@item empty-fill
The number of integer columns that don't occupy the full byte range of their
type; these are changed to a smaller type (for example, an @code{INTEGER}
column may be changed to @code{MEDIUMINT}).

@item pre-space
The number of decimal columns that are stored with leading space. In this
case, each value will contain a count for the number of leading spaces.

@item end-space
The number of columns that have a lot of trailing space.  In this case, each
value will contain a count for the number of trailing spaces.

@item table-lookup
The column had only a small number of different values, and that were
converted to an @code{ENUM} before Huffman compression.

@item zero
The number of columns for which all values are zero.

@item Original trees
The initial number of Huffman trees.

@item After join
The number of distinct Huffman trees left after joining
trees to save some header space.
@end table

After a table has been compressed, @code{isamchk -dvv} prints additional
information about each field:

@table @code
@item Type
The field type may contain the following descriptors:

@table @code
@item constant
All rows have the same value.

@item no endspace
Don't store endspace.

@item no endspace, not_always
Don't store endspace and don't do end space compression for all values.

@item no endspace, no empty
Don't store endspace. Don't store empty values.

@item table-lookup
The column was converted to an @code{ENUM}.

@item zerofill(n)
The most significant @code{n} bytes in the value are always 0 and are not
stored.

@item no zeros
Don't store zeros.

@item always zero
0 values are stored in 1 bit.
@end table

@item Huff tree
The Huffman tree associated with the field

@item Bits
The number of bits used in the Huffman tree.
@end table

@node Maintenance, Adding functions, Tools, Top
@chapter Maintaining a @strong{MySQL} installation

@menu
* Table maintenance::           Using @code{isamchk} for table maintenance and crash recovery
* Maintenance regime::          Setting up a table maintenance regime
* Table-info::                  Getting information about a table
* Crash recovery::              Using @code{isamchk} for crash recovery
* Log files::                   Log file maintenance
@end menu

@node Table maintenance, Maintenance regime, Maintenance, Maintenance
@section Using @code{isamchk} for table maintenance and crash recovery

To check/repair ISAM tables (@code{.ISM} and @code{.ISD}) you should use the
@code{isamchk} utility. To check/repair MYISAM tables (@code{.MYI} and @code{.MYD})
you should use the @code{myisamchk} utility.
@xref{Table types}.

In the following text we will talk about @code{isamchk} but everything
also applies to @code{myisamchk}.

You can use the @code{isamchk} utility to get information about your database
tables, check and repair them or optimize them.  The following sections
describe how to invoke @code{isamchk} (including a description of its
options), how to set up a table maintenance schedule, and how to use
@code{isamchk} to perform its various functions.

If you run @code{mysqld} with @code{--skip-locking} (which is the default on
some systems, like Linux), you can't reliably use @code{isamchk} to
check a table when @code{mysqld} is using the same table.  If you
can be sure that no one is accessing the tables through @code{mysqld}
while you run @code{isamchk}, you only have to do @code{mysqladmin
flush-tables} before you start checking the tables.  If you can't
guarantee the above, then you must take down @code{mysqld} while you
check the tables.  If you run @code{isamchk} while @code{mysqld} is updating
the tables, you may get a warning that a table is corrupt even if it
isn't.

If you are not using @code{--skip-locking}, you can use @code{isamchk}
to check tables at any time.  While you do this, all clients that try
to update the table will wait until @code{isamchk} is ready before
continuing.

If you use @code{isamchk} to repair or optimize tables, you
@strong{MUST} always ensure that the @code{mysqld} server is not using
the table (this also applies if you are using @code{--skip-locking}).
If you don't take down @code{mysqld} you should at least do a
@code{mysqladmin flush-tables} before you run @code{isamchk}.

You can in most cases also use the command @code{OPTIMIZE TABLES} to
optimize and repair tables, but this is not as fast or reliable (in case
of real fatal errors) as @code{isamchk}.  On the other hand,
@code{OPTIMIZE TABLE} is easier to use and you don't have to worry about
flushing tables.
@xref{OPTIMIZE TABLE, , @code{OPTIMIZE TABLE}}.

@menu
* isamchk syntax::              @code{isamchk} invocation syntax
* isamchk memory::              @code{isamchk} memory usage
@end menu

@node isamchk syntax, isamchk memory, Table maintenance, Table maintenance
@subsection @code{isamchk} invocation syntax

@code{isamchk} is invoked like this:

@example
shell> isamchk [options] tbl_name
@end example

The @code{options} specify what you want @code{isamchk} to do.  They are
described below.  (You can also get a list of options by invoking
@code{isamchk --help}.)  With no options, @code{isamchk} simply checks your
table.  To get more information or to tell @code{isamchk} to take corrective
action, specify options as described below and in the following sections.

@code{tbl_name} is the database table you want to check.  If you run
@code{isamchk} somewhere other than in the database directory, you must
specify the path to the file, since @code{isamchk} has no idea where your
database is located.  Actually, @code{isamchk} doesn't care whether or not
the files you are working on are located in a database directory; you can
copy the files that correspond to a database table into another location and
perform recovery operations on them there.

You can name several tables on the @code{isamchk} command line if you
wish.  You can also specify a name as an index file
name (with the @file{.ISM} suffix), which allows you to specify all
tables in a directory by using the pattern @file{*.ISM}.
For example, if you are in a database directory, you can check all the
tables in the directory like this:

@example
shell> isamchk *.ISM
@end example

If you are not in the database directory, you can check all the tables there
by specifying the path to the directory:

@example
shell> isamchk /path/to/database_dir/*.ISM
@end example

You can even check all tables in all databases by specifying a wildcard
with the path to the @strong{MySQL} data directory:

@example
shell> isamchk /path/to/datadir/*/*.ISM
@end example

@code{isamchk} supports the following options:

@table @code
@item -a, --analyze	
Analyze the distribution of keys. This improves join performance by
enabling the join optimizer to better choose in which order it should
join the tables and which keys it should how use.

@item -#, --debug=debug_options
Output debug log. The @code{debug_options} string often is
@code{'d:t:o,filename'}.

@item -d, --description
Prints some information about the table.

@item -e, --extend-check
Check the table VERY thoroughly.  This is necessary only in extreme cases.
Normally, @code{isamchk} should find all errors even without this option.

@item -f, --force
Overwrite old temporary files.
If you use @code{-f} when checking tables (running @code{isamchk}
without @code{-r}), @code{isamchk} will automatically restart with @code{-r}
on any table for which an error occurs during checking.

@item --help
Display a help message and exit.

@item -i, --information
Print informational statistics about the table that is checked.

@item -k #, --keys-used=#
Used with @code{-r}. Tell the NISAM table handler to update only the first
@code{#} indexes.  Higher-numbered indexes are deactivated.  This can be used
to get faster inserts!  Deactivated indexes can be reactivated by using
@code{isamchk -r}.

@item -l, --no-symlinks
Do not follow symbolic links when repairing. Normally
@code{isamchk} repairs the table a symlink points at.

@item -q, --quick
Used with @code{-r} to get a faster repair. Normally, the original data file
isn't touched; you can specify a second @code{-q} to force
the original data file to be used.

@item -r, --recover
Recovery mode.
Can fix almost anything except unique keys that aren't unique.

@item -o, --safe-recover
Recovery mode.
Uses an old recovery method; this is slower than @code{-r}, but can
handle a couple of cases that @code{-r} cannot handle.

@item -O var=option, --set-variable var=option
Set the value of a variable.  The possible variables are listed below.

@item -s, --silent
Silent mode.  Write output only when errors occur.
You can use @code{-s} twice (@code{-ss}) to make @code{isamchk}
very silent.

@item -S, --sort-index
Sort the index tree blocks in high-low order.
This will optimize seeks and will make table scanning by key faster.

@item -R index_num, --sort-records=index_num
Sorts records according to an index.  This makes your data much more localized
and may speed up ranged @code{SELECT} and @code{ORDER BY} operations on
this index. (It may be VERY slow to do a sort the first time!)
To find out a table's index numbers, use @code{SHOW INDEX}, which shows a
table's indexes in the same order that @code{isamchk} sees them.  Indexes are
numbered beginning with 1.

@item -u, --unpack
Unpack a table that was packed with @code{pack_isam}.

@item -v, --verbose
Verbose mode.  Print more information. This can be used with @code{-d} and
@code{-e}. Use @code{-v} multiple times (@code{-vv}, @code{-vvv}) for more
verbosity!

@item -V, --version
Print the @code{isamchk} version and exit.

@item -w, --wait
Wait if the table is locked.
@end table

Possible variables for the @code{--set-variable} (@code{-O}) option are:

@example
key_buffer_size       current value: 16776192
read_buffer_size      current value: 262136
write_buffer_size     current value: 262136
sort_buffer_size      current value: 2097144
sort_key_blocks       current value: 16
decode_bits           current value: 9
@end example

@node isamchk memory,  , isamchk syntax, Table maintenance
@subsection @code{isamchk} memory usage

Memory allocation is important when you run @code{isamchk}.  @code{isamchk}
uses no more memory than you specify with the @code{-O} options.  If you are
going to use @code{isamchk} on very large files, you should first decide how
much memory you want it to use.  The default is to use only about 3M to fix
things.  By using larger values, you can get @code{isamchk} to operate
faster.  For example, if you have more than 32M RAM, you could use options
such as these (in addition to any other options you might specify):

@example
shell> isamchk -O sort=16M -O key=16M -O read=1M -O write=1M ...
@end example

Using @code{-O sort=16M} should
probably be enough for most cases.

Be aware that @code{isamchk} uses temporary files in @code{TMPDIR}. If
@code{TMPDIR} points to a memory file system, you may easily get out of
memory errors. If this happens, set @code{TMPDIR} to point at some directory
with more space and restart @code{isamchk}

@node Maintenance regime, Table-info, Table maintenance, Maintenance
@section Setting up a table maintenance regime

It is a good idea to perform table checks on a regular basis rather than
waiting for problems to occur.  For maintenance purposes, you can use
@code{isamchk -s} to check tables.  The @code{-s} option causes
@code{isamchk} to run in silent mode, printing messages only when errors
occur.

@tindex .pid (process ID) file
It's a good idea to check tables when the server starts up.
For example, whenever the machine has done a reboot in the middle of an
update, you usually need to check all the tables that could have been
affected. (This is an ``expected crashed table''.) You could add a test to
@code{safe_mysqld} that runs @code{isamchk} to check all tables that have
been modified during the last 24 hours if there is an old @file{.pid}
(process ID) file left after a reboot.  (The @file{.pid} file is created by
@code{mysqld} when it starts up and removed when it terminates normally.  The
presence of a @file{.pid} file at system startup time indicates that
@code{mysqld} terminated abnormally.)

An even better test would be to check any table whose last-modified time
is more recent than that of the @file{.pid} file.

You should also check your tables regularly during normal system operation.
At TcX, we run a @code{cron} job to check all our important tables once a week,
using a line like this in a @file{crontab} file:

@example
35 0 * * 0 /path/to/isamchk -s /path/to/datadir/*/*.ISM
@end example

This prints out information about crashed tables so we can examine and repair
them when needed.

As we haven't had any unexpectedly crashed tables (tables that become
corrupted for reasons other than hardware trouble)
for a couple of years now (this is really true), once a week is
more than enough for us.

We recommend that to start with, you execute @code{isamchk -s} each
night on all tables that have been updated during the last 24 hours,
until you come to trust @strong{MySQL} as much as we do.

@node Table-info, Crash recovery, Maintenance regime, Maintenance
@section Getting information about a table

To get a description of a table or statistics about it, use the commands shown
below. We explain some of the information in more detail later.

@table @code
@item isamchk -d tbl_name
Runs @code{isamchk} in ``describe mode'' to produce a description of your
table. If you start the @strong{MySQL} server using the @code{--skip-locking}
option, @code{isamchk} may report an error for a table that is updated while
it runs.  However, since @code{isamchk} doesn't change the table in describe
mode, there isn't any risk of destroying data.

@item isamchk -d -v tbl_name
To produce more information about what @code{isamchk} is doing, add @code{-v}
to tell it to run in verbose mode.

@item isamchk -eis tbl_name
Shows only the most important information from a table. It is slow since it
must read the whole table.

@item isamchk -eiv tbl_name
This is like @code{-eis}, but tells you what is being done.
@end table

Example of @code{isamchk -d} output:
@example
ISAM file:     company.ISM
Data records:           1403698  Deleted blocks:         0
Recordlength:               226
Record format: Fixed length

table description:
Key Start Len Index   Type
1   2     8   unique  double
2   15    10  multip. text packed stripped
3   219   8   multip. double
4   63    10  multip. text packed stripped
5   167   2   multip. unsigned short
6   177   4   multip. unsigned long
7   155   4   multip. text
8   138   4   multip. unsigned long
9   177   4   multip. unsigned long
    193   1           text
@end example

Example of @code{isamchk -d -v} output:
@example
ISAM file:     company.ISM
Isam-version:  2
Creation time: 1996-08-28 11:44:22
Recover time:  1997-01-12 18:35:29
Data records:           1403698  Deleted blocks:              0
Datafile: Parts:        1403698  Deleted data:                0
Datafilepointer (bytes):      3  Keyfile pointer (bytes):     3
Max datafile length: 3791650815  Max keyfile length: 4294967294
Recordlength:               226
Record format: Fixed length

table description:
Key Start Len Index   Type                      Root Blocksize Rec/key
1   2     8   unique  double                15845376      1024       1
2   15    10  multip. text packed stripped  25062400      1024       2
3   219   8   multip. double                40907776      1024      73
4   63    10  multip. text packed stripped  48097280      1024       5
5   167   2   multip. unsigned short        55200768      1024    4840
6   177   4   multip. unsigned long         65145856      1024    1346
7   155   4   multip. text                  75090944      1024    4995
8   138   4   multip. unsigned long         85036032      1024      87
9   177   4   multip. unsigned long         96481280      1024     178
    193   1           text
@end example

Example of @code{isamchk -eis} output:
@example
Checking ISAM file: company.ISM
Key:  1:  Keyblocks used:  97%  Packed:    0%  Max levels:  4
Key:  2:  Keyblocks used:  98%  Packed:   50%  Max levels:  4
Key:  3:  Keyblocks used:  97%  Packed:    0%  Max levels:  4
Key:  4:  Keyblocks used:  99%  Packed:   60%  Max levels:  3
Key:  5:  Keyblocks used:  99%  Packed:    0%  Max levels:  3
Key:  6:  Keyblocks used:  99%  Packed:    0%  Max levels:  3
Key:  7:  Keyblocks used:  99%  Packed:    0%  Max levels:  3
Key:  8:  Keyblocks used:  99%  Packed:    0%  Max levels:  3
Key:  9:  Keyblocks used:  98%  Packed:    0%  Max levels:  4
Total:    Keyblocks used:  98%  Packed:   17%

Records:          1403698    M.recordlength:     226   Packed:             0%
Recordspace used:     100%   Empty space:          0%  Blocks/Record:   1.00
Recordblocks:     1403698    Deleteblocks:         0
Recorddata:     317235748    Deleted data:         0
Lost space:             0    Linkdata:             0

User time 1626.51, System time 232.36
Maximum resident set size 0, Integral resident set size 0
Non physical pagefaults 0, Physical pagefaults 627, Swaps 0
Blocks in 0 out 0, Messages in 0 out 0, Signals 0
Voluntary context switches 639, Involuntary context switches 28966
@end example

Example of @code{isamchk -eiv} output:
@example
Checking ISAM file: company.ISM
Data records: 1403698   Deleted blocks:       0
- check file-size
- check delete-chain
index  1:
index  2:
index  3:
index  4:
index  5:
index  6:
index  7:
index  8:
index  9:
No recordlinks
- check index reference
- check data record references index: 1
Key:  1:  Keyblocks used:  97%  Packed:    0%  Max levels:  4
- check data record references index: 2
Key:  2:  Keyblocks used:  98%  Packed:   50%  Max levels:  4
- check data record references index: 3
Key:  3:  Keyblocks used:  97%  Packed:    0%  Max levels:  4
- check data record references index: 4
Key:  4:  Keyblocks used:  99%  Packed:   60%  Max levels:  3
- check data record references index: 5
Key:  5:  Keyblocks used:  99%  Packed:    0%  Max levels:  3
- check data record references index: 6
Key:  6:  Keyblocks used:  99%  Packed:    0%  Max levels:  3
- check data record references index: 7
Key:  7:  Keyblocks used:  99%  Packed:    0%  Max levels:  3
- check data record references index: 8
Key:  8:  Keyblocks used:  99%  Packed:    0%  Max levels:  3
- check data record references index: 9
Key:  9:  Keyblocks used:  98%  Packed:    0%  Max levels:  4
Total:    Keyblocks used:   9%  Packed:   17%

- check records and index references
[LOTS OF ROW NUMBERS DELETED]

Records:          1403698    M.recordlength:     226   Packed:             0%
Recordspace used:     100%   Empty space:          0%  Blocks/Record:   1.00
Recordblocks:     1403698    Deleteblocks:         0
Recorddata:     317235748    Deleted data:         0
Lost space:             0    Linkdata:             0

User time 1639.63, System time 251.61
Maximum resident set size 0, Integral resident set size 0
Non physical pagefaults 0, Physical pagefaults 10580, Swaps 0
Blocks in 4 out 0, Messages in 0 out 0, Signals 0
Voluntary context switches 10604, Involuntary context switches 122798
@end example

Here are the sizes of the data and index files for the table used in the
preceding examples:

@example
-rw-rw-r--   1 monty    tcx     317235748 Jan 12 17:30 company.ISD
-rw-rw-r--   1 davida   tcx      96482304 Jan 12 18:35 company.ISM
@end example

Explanations for the types of information @code{isamchk} produces are given
below.  The ``keyfile'' is the index file.  ``Record'' and ``row'' are
synonymous.

@table @code
@item ISAM file
Name of the ISAM (index) file.

@item Isam-version
Version of ISAM format. Currently always 2.

@item Creation time
When the data file was created.

@item Recover time
When the index/data file was last reconstructed.

@item Data records
How many records are in the table.

@item Deleted blocks
How many deleted blocks still have reserved space.
You can optimize your table to minimize this space.
@xref{Optimization}.

@item Datafile: Parts
For dynamic record format, this indicates how many data blocks there are. For
an optimized table without fragmented records, this is the same as @code{Data
records}.

@item Deleted data
How many bytes of non-reclaimed deleted data there are.
You can optimize your table to minimize this space.
@xref{Optimization}.

@item Datafile pointer
The size of the data file pointer, in bytes. It is usually 2, 3, 4 or 5
bytes. Most tables manage with 2 bytes, but this cannot be controlled
from @strong{MySQL} yet. For fixed tables, this is a record address. For
dynamic tables, this is a byte address.

@item Keyfile pointer
The size of the index file pointer, in bytes. It is usually 1, 2 or 3
bytes. Most tables manage with 2 bytes, but this is calculated
automatically by @strong{MySQL}. It is always a block address.

@item Max datafile length
How long the table's data file (@code{.ISD} file) can become, in bytes.

@item Max keyfile length
How long the table's key file (@code{.ISM} file) can become, in bytes.

@item Recordlength
How much space each record takes, in bytes.

@item Record format
The format used to store table rows.
The examples shown above use @code{Fixed length}.
Other possible values are @code{Compressed} and @code{Packed}.

@item table description
A list of all keys in the table. For each key, some low-level information
is presented:

@table @code
@item Key
This key's number.

@item Start
Where in the record this index part starts.

@item Len
How long this index part is. For packed numbers, this should always be
the full length of the column. For strings, it may be shorter than the full
length of the indexed column, because you can index a prefix of a string
column.

@item Index
@code{unique} or @code{multip.} (multiple). Indicates whether or not one value
can exist multiple times in this index.

@item Type
What data-type this index part has. This is an NISAM data-type
with the options @code{packed}, @code{stripped} or @code{empty}.

@item Root
Address of the root index block.

@item Blocksize
The size of each index block. By default this is 1024, but the value may be
changed at compile time.

@item Rec/key
This is a statistical value used by the optimizer. It tells how many
records there are per value for this key. A unique key always has a
value of 1. This may be updated after a table is loaded (or greatly
changed) with @code{isamchk -a}. If this is not updated at all, a default
value of 30 is given.
@end table

@item
In the first example above, the 9th key is a multi-part key with two parts.

@item Keyblocks used
What percentage of the keyblocks are used. Since the table used in the
examples had just been reorganized with @code{isamchk}, the values are very
high (very near the theoretical maximum).

@item Packed
@strong{MySQL} tries to pack keys with a common suffix. This can only be used
for @code{CHAR}/@code{VARCHAR}/@code{DECIMAL} keys. For long strings like
names, this can significantly reduce the space used. In the third example
above, the 4th key is 10 characters long and a 60% reduction in space is
achieved.

@item Max levels
How deep the B-tree for this key is. Large tables with long keys get high
values.

@item Records
How many rows are in the table.

@item M.recordlength
The average record length. For tables with fixed-length records, this is the
exact record length.

@item Packed
@strong{MySQL} strips spaces from the end of strings. The @code{Packed}
value indicates the percentage savings achieved by doing this.

@item Recordspace used
What percentage of the data file is used.

@item Empty space
What percentage of the data file is unused.

@item Blocks/Record
Average number of blocks per record (i.e., how many links a fragmented
record is composed of). This is always 1 for fixed-format tables. This value
should stay as close to 1.0 as possible. If it gets too big, you can
reorganize the table with @code{isamchk}.
@xref{Optimization}.

@item Recordblocks
How many blocks (links) are used. For fixed format, this is the same as the number
of records.

@item Deleteblocks
How many blocks (links) are deleted.

@item Recorddata
How many bytes in the data file are used.

@item Deleted data
How many bytes in the data file are deleted (unused).

@item Lost space
If a record is updated to a shorter length, some space is lost. This is
the sum of all such losses, in bytes.

@item Linkdata
When the dynamic table format is used, record fragments are linked with
pointers (4 to 7 bytes each). @code{Linkdata} is the sum of the amount of
storage used by all such pointers.
@end table

If a table has been compressed with @code{pack_isam}, @code{isamchk -d}
prints additional information about each table column.  See @ref{pack_isam, ,
@code{pack_isam}}, for an example of this information and a description of
what it means.

@node Crash recovery, Log files, Table-info, Maintenance
@section Using @code{isamchk} for crash recovery

The file format that @strong{MySQL} uses to store data has been extensively
tested, but there are always external circumstances that may cause database
tables to become corrupted:

@itemize @bullet
@item
The @code{mysqld} process being killed in the middle of a write
@item
Unexpected shutdown of the computer (for example, if the computer is turned
off)
@item
A hardware error
@end itemize

This chapter describes how to check for and deal with data corruption
in @strong{MySQL} databases.  If your tables get corrupted a lot you should
try to find the reason for this! @xref{Debugging server}.

When performing crash recovery, it is important to understand that each table
@code{tbl_name} in a database corresponds to three files in the database
directory:

@multitable @columnfractions .2 .8
@item @strong{File} @tab @strong{Purpose}
@item @file{tbl_name.frm} @tab Table definition (form) file
@item @file{tbl_name.ISD} @tab Data file
@item @file{tbl_name.ISM} @tab Index file
@end multitable

Each of these three file types is subject to corruption in various ways, but
problems occur most often in data files and index files.

@code{isamchk} works by creating a copy of the @file{.ISD} (data) file row by
row. It ends the repair stage by removing the old @file{.ISD} file and
renaming the new file to the original file name.  If you use @code{--quick},
@code{isamchk} does not create a temporary @file{.ISD} file, but instead
assumes that the @file{.ISD} file is correct and only generates a new index
file without touching the @file{.ISD} file. This is safe, because
@code{isamchk} automatically detects if the @file{.ISD} file is corrupt and
aborts the repair in this case.  You can also give two @code{--quick} options
to @code{isamchk}.  In this case, @code{isamchk} does not abort on some
errors (like duplicate key) but instead tries to resolve them by
modifying the @file{.ISD} file. Normally the use of two @code{--quick}
options is useful only if you have too little free disk space to perform a
normal repair.  In this case you should at least make a backup before running
@code{isamchk}.

@menu
* Check::                       How to check tables for errors
* Repair::                      How to repair tables
* Optimization::                Table optimization
@end menu

@cindex Checking tables for errors
@node Check, Repair, Crash recovery, Crash recovery
@subsection How to check tables for errors

To check a table, use the following commands:

@table @code
@item isamchk tbl_name
This finds 99.99% of all errors. What it can't find is corruption that
involves @strong{ONLY} the data file (which is very unusual). If you want
to check a table, you should normally run @code{isamchk} without options or
with either the @code{-s} or @code{--silent} option.

@item isamchk -e tbl_name
This does a complete and thorough check of all data (@code{-e} means
``extended check''). It does a check-read of every key for each row to verify
that they indeed point to the correct row.  This may take a LONG time on a
big table with many keys.  @code{isamchk} will normally stop after the first
error it finds. If you want to obtain more information, you can add the
@code{--verbose} (@code{-v}) option.  This causes @code{isamchk} to keep
going, up through a maximum of 20 errors.  In normal usage, a simple
@code{isamchk} (with no arguments other than the table name) is sufficient.

@item isamchk -e -i tbl_name
Like the previous command, but the @code{-i} option tells @code{isamchk} to
print some informational statistics, too.
@end table

@node Repair, Optimization, Check, Crash recovery
@subsection How to repair tables

The symptoms of a corrupted table are usually that queries abort unexpectedly
and that you observe errors such as these:

@itemize @bullet
@item
@file{tbl_name.frm} is locked against change
@item
Can't find file @file{tbl_name.ISM} (Errcode: ###)
@item
Got error ### from table handler (Error 135 is an exception in this case)
@item
Unexpected end of file
@item
Record file is crashed
@end itemize

In these cases, you must repair your tables. @code{isamchk}
can usually detect and fix most things that go wrong.

The repair process involves up to four stages, described below. Before you
begin, you should @code{cd} to the database directory and check the
permissions of the table files. Make sure they are readable by the Unix user
that @code{mysqld} runs as (and to you, since you need to access the files
you are checking).  If it turns out you need to modify files, they must also
be writable by you.

@noindent
@strong{Stage 1: Checking your tables}

Run @code{isamchk *.ISM} or (@code{isamchk -e *.ISM} if you have more time).
Use the @code{-s} (silent) option to suppress unnecessary information.

You have to repair only those tables for which @code{isamchk} announces an
error.  For such tables, proceed to Stage 2.

If you get weird errors when checking (such as @code{out of
memory} errors), or if @code{isamchk} crashes, go to Stage 3.

@noindent
@strong{Stage 2: Easy safe repair}

First, try @code{isamchk -r -q tbl_name} (@code{-r -q} means ``quick recovery
mode''). This will attempt to repair the index file without touching the data
file.  If the data file contains everything that it should and the delete
links point at the correct locations within the data file, this should work
and the table is fixed. Start repairing the next table.  Otherwise, use the
following procedure:

@enumerate
@item
Make a backup of the data file before continuing.

@item
Use @code{isamchk -r tbl_name} (@code{-r} means ``recovery mode''). This will
remove incorrect records and deleted records from the data file and
reconstruct the index file.

@item
If the preceding step fails, use @code{isamchk --safe-recover tbl_name}.
Safe recovery mode uses an old recovery method that handles a few cases that
regular recovery mode doesn't (but is slower).
@end enumerate

If you get weird errors when repairing (such as @code{out of
memory} errors), or if @code{isamchk} crashes, go to Stage 3.

@noindent
@strong{Stage 3: Difficult repair}

You should only reach this stage if the first 16K block in the index file is
destroyed or contains incorrect information, or if the index file is
missing.  In this case, it's necessary to create a new index file. Do so as
follows:

@enumerate
@item
Move the data file to some safe place.

@item
Use the table description file to create new (empty) data and index files:

@example
shell> mysql db_name
mysql> DELETE FROM tbl_name;
mysql> quit
@end example

@item
Copy the old data file back onto the newly created data file.
(Don't just move the old file back onto the new file; you want to retain
a copy in case something goes wrong.)
@end enumerate

Go back to Stage 2.  @code{isamchk -r -q} should work now.  (This shouldn't
be an endless loop).

@noindent
@strong{Stage 4: Very difficult repair}

You should reach this stage only if the description file has also
crashed. That should never happen, because the description file isn't changed
after the table is created.

@enumerate
@item
Restore the description file from a backup and go back to Stage 3.  You can
also restore the index file and go back to Stage 2.  In the latter case, you
should start with @code{isamchk -r}.

@item
If you don't have a backup but know exactly how the table was created, create
a copy of the table in another database.  Remove the new data file, then move
the description and index files from the other database to your crashed
database.  This gives you new description and index files, but leaves
the data file alone.  Go back to Stage 2 and attempt to reconstruct
the index file.
@end enumerate

@node Optimization,  , Repair, Crash recovery
@subsection Table optimization

To coalesce fragmented records and eliminate wasted space resulting from
deleting or updating records, run @code{isamchk} in recovery mode:

@example
shell> isamchk -r tbl_name
@end example

You can optimize a table in the same way using the SQL @code{OPTIMIZE TABLE}
statement.  @code{OPTIMIZE TABLE} is easier, but @code{isamchk} is faster.

@code{isamchk} also has a number of other options you can use to improve
the performance of a table:

@table @code
@item -S, --sort-index
@item -R index_num, --sort-records=index_num
@item -a, --analyze
@end table

For a full description of the option see @ref{isamchk syntax}.

@node Log files,  , Crash recovery, Maintenance
@section Log file maintenance

When using @strong{MySQL} with log files, you will from time to time
want to remove/backup old log files and tell @strong{MySQL} to start
logging on new files.  @xref{Update log}.

One a Linux (@code{Redhat}) installation, you can use the
@code{mysql-log-rotate} script for this. If you installed @strong{MySQL}
from an RPM distribution, the script should have been installed
automatically.

On other systems you must install a short script yourself that you
start from @code{cron} to handle log files.

You can force @strong{MySQL} to start using new log files by using
@code{mysqladmin flush-logs} or by using the SQL command @code{FLUSH LOGS}.
If you are using @strong{MySQL} 3.21 you must use @code{mysqladmin refresh}.

The above command does the following:

@itemize @bullet
@item
If standard logging (@code{--log}) is used, closes and reopens the log file.
(@file{mysql.log} as default).
@item
If update logging (@code{--log-update}) is used, closes the update log and
opens a new log file with a higher sequence number.
@end itemize

If you are using only an update log, you only have to flush the logs and then
move away the old update log files to a backup.
If you are using the normal logging, you can do something like:

@example
shell> cd mysql-data-directory
shell> mv mysql.log mysql.old
shell> mysqladmin flush-tables
@end example

and then take a backup and remove @file{mysql.old}.

@node Adding functions, Adding procedures, Maintenance, Top
@chapter Adding new functions to @strong{MySQL}

There are two ways to add new functions to @strong{MySQL}:

@itemize @bullet
@item You can add the function through the user-definable function (UDF)
interface.  User-definable functions are added and removed dynamically using
the @code{CREATE FUNCTION} and @code{DROP FUNCTION} statements.
@xref{CREATE FUNCTION, , @code{CREATE FUNCTION}}.

@item You can add the function as a native (built in) @strong{MySQL} function.
Native functions are compiled into the @code{mysqld} server and become
available on a permanent basis.
@end itemize

Each method has advantages and disadvantages:

@itemize @bullet
@item
If you write a user-definable function, you must install the object file
in addition to the server itself.  If you compile your function into the
server, you don't need to do that.
@item
You can add UDFs to a binary @strong{MySQL} distribution.  Native functions
require you to modify a source distribution.
@item
If you upgrade your @strong{MySQL} distribution, you can continue to use your
previously-installed UDFs.  For native functions, you must repeat your
modifications each time you upgrade.
@end itemize

Whichever method you use to add new functions, they may be used just like
native functions such as @code{ABS()} or @code{SOUNDEX()}.

@menu
* Adding UDF::                  Adding a new user-definable function
* Adding native function::      Adding a new native function
@end menu

@cindex Adding user-definable functions
@cindex User-definable functions, adding
@cindex Functions, user-definable, adding
@node Adding UDF, Adding native function, Adding functions, Adding functions
@section Adding a new user-definable function

@menu
* UDF calling sequences::       UDF calling sequences
* UDF arguments::               Argument processing
* UDF return values::           Return values and error handling
* UDF compiling::               Compiling and installing user-definable functions
@end menu

For the UDF mechanism to work, functions must be written in C or C++ and your
operating system must support dynamic loading.  The @strong{MySQL} source
distribution includes a file @file{sql/udf_example.cc} that defines 5 new
functions.  Consult this file to see how UDF calling conventions work.

For each function that you want to use in SQL statements, you should define
corresponding C (or C++) functions.  In the discussion below, the name
``xxx'' is used for an example function name.  To distinquish between SQL and
C/C++ usage, @code{XXX()} (uppercase) indicates a SQL function call, and
@code{xxx()} (lowercase) indicates a C/C++ function call.

The C/C++ functions that you write to implement the inferface for
@code{XXX()} are:

@table @asis
@item @code{xxx()} (required)
The main function.  This is where the function result is computed.
The correspondence between the SQL type and return type of your C/C++
function is shown below:

@multitable @columnfractions .2 .8
@item @strong{SQL type} @tab @strong{C/C++ type}
@item @code{STRING}     @tab @code{char *}
@item @code{INTEGER}    @tab @code{long long}
@item @code{REAL}       @tab @code{double}
@end multitable

@item @code{xxx_init()} (optional)
The initialization function for @code{xxx()}.  It can be used to:

@itemize @bullet
@item
Check the number of arguments to @code{XXX()}
@item
Check that the arguments are of a required type, or, alternatively,
tell @strong{MySQL} to coerce arguments to the types you want when
the main function is called
@item
Allocate any memory required by the main function
@item
Specify the maximum length of the result
@item
Specify (for @code{REAL} functions) the maximum number of decimals
@item
Specify whether or not the result can be @code{NULL}
@end itemize

@item @code{xxx_deinit()} (optional)
The deinitialization function for @code{xxx()}.  It should deallocate any
memory allocated by the initialization function.
@end table

When a SQL statement invokes @code{XXX()}, @strong{MySQL} calls the
initialization function @code{xxx_init()} to let it perform any required
setup, such as argument checking or memory allocation.  If @code{xxx_init()}
returns an error, the SQL statement is aborted with an error message and the
main and deinitialization functions are not called.  Otherwise, the main
function @code{xxx()} is called once for each row.  After all rows have been
processed, the deinitialization function @code{xxx_deinit()} is called so it
can perform any required cleanup.

All functions must be thread-safe (not just the main function,
but the initialization and deinitialization functions as well). This means
that you are not allowed to allocate any global or static variables that
change!  If you need memory, you should allocate it in @code{xxx_init()}
and free it in @code{xxx_deinit()}.

@node UDF calling sequences, UDF arguments, Adding UDF, Adding UDF
@subsection UDF calling sequences

The main function should be declared as shown below.  Note that the return
type and parameters differ, depending on whether you will declare the SQL
function @code{XXX()} to return @code{STRING}, @code{INTEGER} or @code{REAL}
in the @code{CREATE FUNCTION} statement:

@noindent
For @code{STRING} functions:

@example
char *xxx(UDF_INIT *initid, UDF_ARGS *args,
              char *result, unsigned long *length,
              char *is_null, char *error);
@end example

@noindent
For @code{INTEGER} functions:

@example
long long xxx(UDF_INIT *initid, UDF_ARGS *args,
              char *is_null, char *error);
@end example

@noindent
For @code{REAL} functions:

@example
double xxx(UDF_INIT *initid, UDF_ARGS *args,
              char *is_null, char *error);
@end example

The initialization and deinitialization functions are declared like this:

@example
my_bool xxx_init(UDF_INIT *initid, UDF_ARGS *args, char *message);

void xxx_deinit(UDF_INIT *initid);
@end example

The @code{initid} parameter is passed to all three functions.  It points to a
@code{UDF_INIT} structure that is used to communicate information between
functions.  The @code{UDF_INIT} structure members are listed below.  The
initialization function should fill in any members that it wishes to change.
(To use the default for a member, leave it unchanged.)

@table @code
@item my_bool maybe_null
@code{xxx_init()} should set @code{maybe_null} to @code{1} if @code{xxx()}
can return @code{NULL}.  The default value is @code{1} if any of the
arguments are declared @code{maybe_null}.

@item unsigned int decimals
Number of decimals.  The default value is the maximum number of decimals in
the arguments passed to the main function.  (For example, if the function is
passed @code{1.34}, @code{1.345} and @code{1.3}, the default would be 3,
since @code{1.345} has 3 decimals.

@item unsigned int max_length
The maximum length of the string result.  The default value differs depending
on the result type of the function.  For string functions, the default is the
length of the longest argument.  For integer functions, the default is 21
digits.  For real functions, the default is 13 plus the number of decimals
indicated by @code{initid->decimals}.  (For numeric functions, the length
includes any sign or decimal point characters.)

@item char *ptr
A pointer that the function can use for its own purposes.  For example,
functions can use @code{initid->ptr} to communicate allocated memory
between functions.  In @code{xxx_init()}, allocate the memory and assign it
to this pointer:

@example
initid->ptr = allocated_memory;
@end example

In @code{xxx()} and @code{xxx_deinit()}, refer to @code{initid->ptr} to use
or deallocate the memory.
@end table

@node UDF arguments, UDF return values, UDF calling sequences, Adding UDF
@subsection Argument processing

The @code{args} parameter points to a @code{UDF_ARGS} structure which has the
members listed below:

@table @code
@item unsigned int arg_count
The number of arguments.  Check this value in the initialization function
if you want your function to be called with a particular number of arguments.
For example:

@example
if (args->arg_count != 2)
@{
    strcpy(message,"XXX() requires two arguments");
    return 1;
@}
@end example


@item enum Item_result *arg_type
The types for each argument.  The possible type values are
@code{STRING_RESULT}, @code{INT_RESULT} and @code{REAL_RESULT}.

To make sure that arguments are of a given type and return an
error if they are not, check the @code{arg_type} array in the initialization
function.  For example:

@example
if (args->arg_type[0] != STRING_RESULT
      && args->arg_type[1] != INT_RESULT)
@{
    strcpy(message,"XXX() requires a string and an integer");
    return 1;
@}
@end example

As an alternative to requiring your function's arguments to be of particular
types, you can use the initialization function to set the @code{arg_type}
elements to the types you want.  This causes @strong{MySQL} to coerce
arguments to those types for each call to @code{xxx()}.  For example, to
specify coercion of the first two arguments to string and integer, do this in
@code{xxx_init()}:

@example
args->arg_type[0] = STRING_RESULT;
args->arg_type[1] = INT_RESULT;
@end example

@item char **args
@code{args->args} communicates information to the initialization function
about the general nature of the arguments your function was called with.  For a
constant argument @code{i}, @code{args->args[i]} points to the argument
value.  (See below for instructions on how to access the value properly.)
For a non-constant argument, @code{args->args[i]} is @code{0}.
A constant argument is an expression that uses only constants, such as
@code{3} or @code{4*7-2} or @code{SIN(3.14)}.  A non-constant argument is an
expression that refers to values that may change from row to row, such as
column names or functions that are called with non-constant arguments.

For each invocation of the main function, @code{args->args} contains the
actual arguments that are passed for the row currently being processed.

Functions can refer to an argument @code{i} as follows:

@itemize @bullet
@item
An argument of type @code{STRING_RESULT} is given as a string pointer plus a
length, to allow handling of binary data or data of arbitrary length.  The
string contents are available as @code{args->args[i]} and the string length
is @code{args->lengths[i]}.  You should not assume that strings are
null-terminated.

@item
For an argument of type @code{INT_RESULT}, you must cast
@code{args->args[i]} to a @code{long long} value:

@example
long long int_val;
int_val = *((long long*) args->args[i]);
@end example

@item
For an argument of type @code{REAL_RESULT}, you must cast
@code{args->args[i]} to a @code{double} value:

@example
double    real_val;
real_val = *((double*) args->args[i]);
@end example
@end itemize

@item unsigned long *lengths
For the initialization function, the @code{lengths} array indicates the
maximum string length for each argument.  For each invocation of the main
function, @code{lengths} contains the actual lengths of any string arguments
that are passed for the row currently being processed.  For arguments of
types @code{INT_RESULT} or @code{REAL_RESULT}, @code{lengths} still contains
the maximum length of the argument (as for the initialization function).
@end table

@node UDF return values, UDF compiling, UDF arguments, Adding UDF
@subsection Return values and error handling

The initialization function should return @code{0} if no error occurred and
@code{1} otherwise.  If an error occurs, @code{xxx_init()} should store a
null-terminated error message in the @code{message} parameter.  The message
will be returned to the client.  The message buffer is
@code{MYSQL_ERRMSG_SIZE} characters long, but you should try to keep the
message to less than 80 characters so that it fits the width of a standard
terminal screen.

The return value of the main function @code{xxx()} is the function value, for
@code{long long} and @code{double} functions.  For string functions, the
string is returned in the @code{result} and @code{length} arguments.
@code{result} is a buffer at least 255 bytes long.  Set these to the contents
and length of the return value.  For example:

@example
memcpy(result, "result string", 13);
*length = 13;
@end example

The string function return value normally also points to the result.

To indicate a return value of @code{NULL} in the main function, set
@code{is_null} to @code{1}:

@example
*is_null = 1;
@end example

To indicate an error return in the main function, set the @code{error}
parameter to @code{1}:

@example
*error = 1;
@end example

If @code{xxx()} sets @code{*error} to @code{1} for any row, the function
value is @code{NULL} for the current row and for any subsequent rows
processed by the statement in which @code{XXX()} was invoked.  (@code{xxx()}
will not even be called for subsequent rows.) @strong{Note:} In
@strong{MySQL} versions prior to 3.22.10, you should set both @code{*error}
and @code{*is_null}:

@example
*error = 1;
*is_null = 1;
@end example

@node UDF compiling,  , UDF return values, Adding UDF
@subsection Compiling and installing user-definable functions

Files implementing UDFs must be compiled and installed on the host where the
server runs.  This process is described below for the example UDF file
@file{udf_example.cc} that is included in the @strong{MySQL} source
distribution.  This file contains the following functions:

@itemize @bullet
@item
@code{metaphon()} returns a metaphon string of the string argument.
This is something like a soundex string, but it's more tuned for English.
@item
@code{myfunc_double()} returns the sum of the ASCII values of the
characters in its arguments, divided by the sum of the length of its arguments.
@item
@code{myfunc_int()} returns the sum of the length of its arguments.
@item
@code{lookup()} returns the IP number for a hostname.
@item
@code{reverse_lookup()} returns the hostname for an IP number.
The function may be called with a string @code{"xxx.xxx.xxx.xxx"} or
four numbers.
@end itemize

A dynamically-loadable file should be compiled as a sharable object file,
using a command something like this:

@example
shell> gcc -shared -o udf_example.so myfunc.cc
@end example

You can easily find out the correct compiler options for your system by
running this command in the @file{sql} directory of your @strong{MySQL}
source tree:

@example
shell> make udf_example.o
@end example

You should run a compile command similar to the one that @code{make} displays,
except that you should remove the @code{-c} option near the end of the line
and add @code{-o udf_example.so} to the end of the line.  (On some systems,
you may need to leave  the @code{-c} on the command.)

Once you compile a shared object containing UDFs, you must install it
and tell @strong{MySQL} about it.  Compiling a shared object from
@file{udf_example.cc} produces a file named something like
@file{udf_example.so} (the exact name may vary from platform to platform).
Copy this file to some directory searched by @code{ld}, such as
@file{/usr/lib}.  On many systems, you can set the @code{LD_LIBRARY} or
@code{LD_LIBRARY_PATH} environment variable to point at the directory where
you have your UDF function files. The @code{dopen} manual page tells you
which variable you should use on your system. You should set this in
@code{mysql.server} or @code{safe_mysqld} and restart @code{mysqld}.

After the library is installed, notify @code{mysqld} about the new
functions with these commands:

@example
mysql> CREATE FUNCTION metaphon RETURNS STRING SONAME "udf_example.so";
mysql> CREATE FUNCTION myfunc_double RETURNS REAL SONAME "udf_example.so";
mysql> CREATE FUNCTION myfunc_int RETURNS INTEGER SONAME "udf_example.so";
mysql> CREATE FUNCTION lookup RETURNS STRING SONAME "udf_example.so";
mysql> CREATE FUNCTION reverse_lookup RETURNS STRING SONAME "udf_example.so";
@end example

Functions can be deleted using @code{DROP FUNCTION}:

@example
mysql> DROP FUNCTION metaphon;
mysql> DROP FUNCTION myfunc_double;
mysql> DROP FUNCTION myfunc_int;
mysql> DROP FUNCTION lookup;
mysql> DROP FUNCTION reverse_lookup;
@end example

The @code{CREATE FUNCTION} and @code{DROP FUNCTION} statements update the
system table @code{func} in the @code{mysql} database.  The function's name,
type and shared library name are saved in the table.  You must have the
@strong{insert} and @strong{delete} privileges for the @code{mysql} database
to create and drop functions.

You should not use @code{CREATE FUNCTION} to add a function that has already
been created.  If you need to reinstall a function, you should remove it with
@code{DROP FUNCTION} and then reinstall it with @code{CREATE FUNCTION}.  You
would need to do this, for example, if you recompile a new version of your
function, so that @code{mysqld} gets the new version.  Otherwise the server
will continue to use the old version.

Active functions are reloaded each time the server starts, unless you start
@code{mysqld} with the @code{--skip-grant-tables} option.  In this case, UDF
initialization is skipped and UDFs are unavailable.  (An active function is
one that has been loaded with @code{CREATE FUNCTION} and not removed with
@code{DROP FUNCTION}.)

@cindex Adding native functions
@cindex Native functions, adding
@cindex Functions, native, adding
@node Adding native function,  , Adding UDF, Adding functions
@section Adding a new native function

The procedure for adding a new native function is described below.  Note that
you cannot add native functions to a binary distribution since the procedure
involves modifying @strong{MySQL} source code.  You must compile
@strong{MySQL} yourself from a source distribution.  Also note that if you
migrate to another version of @strong{MySQL} (e.g., when a new version is
released), you will need to repeat the procedure with the new version.

To add a new native @strong{MySQL} function, follow these steps:

@enumerate
@item
Add one line to @file{lex.h} that defines the function name in the
@code{sql_functions[]} array.
@item
Add two lines to @file{sql_yacc.yy}. One indicates the preprocessor
symbol that @code{yacc} should define (this should be added at the
beginning of the file). Then define the function parameters and add an
``item'' with these parameters to the @code{simple_expr} parsing rule.
For an example, check all occurrences of @code{SOUNDEX} in
@file{sql_yacc.yy} to see how this is done.
@item
In @file{item_func.h}, declare a class inheriting from @code{Item_num_func} or
@code{Item_str_func}, depending on whether your function returns a number or a
string.
@item
In @file{item_func.cc}, add one of the following declarations, depending
on whether you are defining a numeric or string function:
@example
double   Item_func_newname::val()
longlong Item_func_newname::val_int()
String  *Item_func_newname::Str(String *str)
@end example
@item
You should probably also define the following function:
@example
void Item_func_newname::fix_length_and_dec()
@end example
This function should at least calculate @code{max_length} based on the
given arguments. @code{max_length} is the maximum number of characters
the function may return.  This function should also set @code{maybe_null = 0}
if the main function can't return a @code{NULL} value.  The function can check
if any of the function arguments can return @code{NULL} by checking the
arguments @code{maybe_null} variable.
@end enumerate

All functions must be thread-safe.

For string functions, there are some additional considerations to be aware of:
@itemize @bullet
@item
The @code{String *str} argument provides a string
buffer that may be used to hold the result.
@item
The function should return the string that holds the result.
@item
All current string functions try to avoid allocating any memory unless
absolutely necessary!
@end itemize

@node Adding procedures, ODBC, Adding functions, Top
@chapter Adding new procedures to @strong{MySQL}

In @strong{MySQL}, you can define a procedure in C++ that can access and
modify the data in a query before sending it to a client.  The modification
can be done on row by row or @code{GROUP BY} level.

We have in @strong{MySQL} 3.23 created an example procedure to
show you what can be done.

@menu
* procedure analyse::           
* Writing a procedure::         
@end menu

@node procedure analyse, Writing a procedure, Adding procedures, Adding procedures
@section Procedure analyse

@code{analyse([max elements,[max memory]])}

This procedure is defined in the @file{sql/sql_analyse.cc}.  This
examines the result from your query and returns an analysis of the
results.

@itemize @bullet
@item
@code{max elements} (default 256) is the maximum number of distinct values
@code{analyse} will notice per column.  This is used by @code{analyse} to check if
the optimal column type should be of type @code{ENUM}.
@item
@code{max memory} (default 8192) is the maximum memory @code{analyse} should
allocate per column while trying to find all distinct values.
@end itemize

@example
SELECT ... FROM ... WHERE ... PROCEDURE ANALYSE([max elements,[max memory]])
@end example

@node Writing a procedure,  , procedure analyse, Adding procedures
@section Writing a procedure.

For the moment, the only documentation for this is the source. :(

You can find all information about procedures by examining the following files:

@itemize @bullet
@item @file{sql/sql_analyse.cc}
@item @file{sql/procedure.h}
@item @file{sql/procedure.cc}
@item @file{sql/sql_select.cc}
@end itemize

@cindex ODBC
@cindex Windows
@cindex MyODBC
@node ODBC, Problems, Adding procedures, Top
@chapter @strong{MySQL} ODBC Support

@menu
* Which ODBC OS::               Operating systems supported by @strong{MyODBC}
* ODBC Problems::               How to report problems with @strong{MySQL} ODBC
* MyODBC clients::              Programs known to work with @strong{MyODBC}
* ODBC administrator::          How to fill in the various fields in the ODBC administrator program
* ODBC and last_insert_id::     How to get the value of an @code{AUTO_INCREMENT} column in ODBC
@end menu

@strong{MySQL} provides support for ODBC by means of the @strong{MyODBC}
program.

@node Which ODBC OS, ODBC Problems, ODBC, ODBC
@section Operating systems supported by @strong{MyODBC}

@strong{MyODBC} is a 32-bit ODBC (2.50) level 0 driver for Windows95
and Windows NT. We hope somebody will port it to Windows 3.x.

@node ODBC Problems, MyODBC clients, Which ODBC OS, ODBC
@section How to report problems with @strong{MyODBC}

@strong{MyODBC} has been tested with Access, Admndemo.exe, C++-Builder, Centura
Team Developer (formerly Gupta SQL/Windows), ColdFusion (on Solaris),
Crystal Reports, Delphi, Excel, iHTML, FileMaker Pro, FoxPro, Notes
4.5/4.6, SBSS, Perl DBD-ODBC, Paradox, Powerbuilder, VC++ and Visual Basic.

If you know of any other application that works with @strong{MyODBC}, please
mail @email{myodbc@@lists.mysql.com} about this!

If you encounter difficulties, we would like to have the log file from the
ODBC manager (the log you get when requesting logs from ODBCADMIN) and a
@strong{MyODBC} log.  This will help shed some light on any problems.

To get a @strong{MyODBC} log, please tag the 'Trace MyODBC' option flag in
the @strong{MyODBC} connect/configure screen.
The log will be written to file @file{C:\myodbc.log}.
Note that you must use @code{MYSQL.DLL} and not @code{MYSQL2.DLL} for this
option to work!

@node MyODBC clients, ODBC administrator, ODBC Problems, ODBC
@section Programs known to work with @strong{MyODBC}

Most programs should work with @strong{MyODBC}, but for each of those
listed below, we have tested it
ourselves or gotten confirmation from some user that it works:

@table @asis
@item @strong{Program}
@strong{Comment}
@item Access
To make Access work:
@itemize @bullet
@item
You should have a primary key in the table.
@item
You should have a timestamp in all tables you want to be able to update..
@item
Only use double float fields. Access fails when comparing with single floats.
@item
Set the 'Return matching rows' option field when connecting to @strong{MySQL}.
@item
Access on NT will report @code{BLOB} columns as @code{OLE OBJECTS}. If
you want to have @code{MEMO} columns instead, you should change the
column to @code{TEXT} with @code{ALTER TABLE}.
@item
Access can't always handle @code{DATE} columns properly. If you have a problem
with these, change the columns to @code{DATETIME}.
@item
In some cases, Access may generate illegal SQL queries that
@strong{MySQL} can't understand. You can fix this by selecting
@code{"Query|SQLSpecific|Pass-Through"} from the Access menu.
@end itemize
@item Excel
Works. Some tips:
@itemize @bullet
@item
If you have problems with dates, try to select them as strings using the
@code{CONCAT()} function. For example:
@example
select CONCAT(rise_time), CONCAT(set_time)
    from sunrise_sunset;
@end example
Values retrieved as strings this way should be correctly recognized
as time values by Excel97.

The purpose of @code{CONCAT()} in this example is to fool ODBC into thinking
the column is of ``string type''. Without the @code{CONCAT()}, ODBC knows the
column is of time type, and Excel does not understand that.

Note that this is a bug in Excel, because it automatically converts a
string to a time. This would be great if the source was a text file, but
is plain stupid when the source is an ODBC connection that reports
exact types for each column.
@end itemize
@item odbcadmin
Test program for ODBC.
@item Delphi
You must use DBE 3.2 or newer.  Set the 'Don't optimize column width'
option field when connecting to @strong{MySQL}.

Also, here is some potentially useful delphi code that sets up both an
ODBC entry and a BDE entry for MyODBC (the BDE entry requires a BDE
Alias Editor which may be had for free at a Delphi Super Page near
you.):  (Thanks to Bryan Brunton @email{bryan@@flesherfab.com} for this)

@example
fReg:= TRegistry.Create;
  fReg.OpenKey('\Software\ODBC\ODBC.INI\DocumentsFab', True);
  fReg.WriteString('Database', 'Documents');
  fReg.WriteString('Description', ' ');
  fReg.WriteString('Driver', 'C:\WINNT\System32\myodbc.dll');
  fReg.WriteString('Flag', '1');
  fReg.WriteString('Password', '');
  fReg.WriteString('Port', ' ');
  fReg.WriteString('Server', 'xmark');
  fReg.WriteString('User', 'winuser');
  fReg.OpenKey('\Software\ODBC\ODBC.INI\ODBC Data Sources', True);
  fReg.WriteString('DocumentsFab', 'MySQL');
  fReg.CloseKey;
  fReg.Free;

  Memo1.Lines.Add('DATABASE NAME=');
  Memo1.Lines.Add('USER NAME=');
  Memo1.Lines.Add('ODBC DSN=DocumentsFab');
  Memo1.Lines.Add('OPEN MODE=READ/WRITE');
  Memo1.Lines.Add('BATCH COUNT=200');
  Memo1.Lines.Add('LANGDRIVER=');
  Memo1.Lines.Add('MAX ROWS=-1');
  Memo1.Lines.Add('SCHEMA CACHE DIR=');
  Memo1.Lines.Add('SCHEMA CACHE SIZE=8');
  Memo1.Lines.Add('SCHEMA CACHE TIME=-1');
  Memo1.Lines.Add('SQLPASSTHRU MODE=SHARED AUTOCOMMIT');
  Memo1.Lines.Add('SQLQRYMODE=');
  Memo1.Lines.Add('ENABLE SCHEMA CACHE=FALSE');
  Memo1.Lines.Add('ENABLE BCD=FALSE');
  Memo1.Lines.Add('ROWSET SIZE=20');
  Memo1.Lines.Add('BLOBS TO CACHE=64');
  Memo1.Lines.Add('BLOB SIZE=32');

  AliasEditor.Add('DocumentsFab','MySQL',Memo1.Lines);
@end example

@item C++Builder
Tested with BDE 3.0. The only known problem is that when the table
schema changes, query fields are not updated. BDE however does not seem
to recognize primary keys, only the index PRIMARY, though this has not
been a problem.
@item Visual basic
To be able to update a table, you must define a primary key for the table.
@end table

@node ODBC administrator, ODBC and last_insert_id, MyODBC clients, ODBC
@section How to fill in the various fields in the ODBC administrator program

There are three possibilities for specifying the server name on
Windows95:

@itemize @bullet
@item
Use the IP address of the server.
@item
Add a file @file{lmhosts} with the following info:

@example
ip hostname
@end example

For example:

@example
194.216.84.21 my
@end example

@item
Configure the PC to use DNS.
@end itemize

Example of how to fill in the ``ODBC setup'':
@example
Windows DSN name:   test
Description:        This is my test database
MySql Database:     test
Server:             194.216.84.21
User:               monty
Password:           my_password
Port:
@end example

The value for the @code{Windows DSN name} field is any name that is unique
in your windows ODBC setup.

You don't have to specify values for the @code{Server}, @code{User},
@code{Password} or @code{Port} fields in the ODBC setup screen.
However, if you do, the values will be used as the defaults later when
you attempt to make a connection.  You have the option of changing the
values at that time.

If the port number is not given, the default port (@value{default_port})
is used.

If you specify the option @code{Read options from C:\my.cnf}, the groups
@code{client} and @code{odbc} will be read from the @file{C:\my.cnf} file.
You can use all options that are usable by @code{mysql_options()}.
@xref{mysql_options}.

@node ODBC and last_insert_id,  , ODBC administrator, ODBC
@section How to get the value of an @code{AUTO_INCREMENT} column in ODBC

A common problem is how to get the value of an automatically-generated ID
from an @code{INSERT}. With ODBC, you can do something like this (assuming
that @code{auto} is an @code{AUTO_INCREMENT} field):

@example
INSERT INTO foo (auto,text) VALUES(NULL,'text');
SELECT LAST_INSERT_ID();
@end example

Or, if you are just going to insert the ID into another table, you can do this:

@example
INSERT INTO foo (auto,text) VALUES(NULL,'text');
INSERT INTO foo2 (id,text) VALUES(LAST_INSERT_ID(),'text');
@end example

For the benefit of some ODBC applications (at least Delphi and Access),
the following query can be used to find a newly-inserted row:
@example
SELECT * FROM tbl_name WHERE auto IS NULL;
@end example

@node Problems, Common problems, ODBC, Top
@chapter Problems and common errors

@menu
* Crashing::                    What to do if @strong{MySQL} keeps crashing
* Common errors::               Some common errors when using @strong{MySQL}
* Full disk::                   How @strong{MySQL} handles a full disk
* Multiple sql commands::       How to run SQL commands from a text file
* Temporary files::             Where @strong{MySQL} stores temporary files
* Problems with mysql.sock::    How to protect @file{/tmp/mysql.sock}
* Error Access denied::         @code{Access denied} error
* Changing MySQL user ::        How to run @strong{MySQL} as a normal user
* File permissions ::           Problems with file permissions
* Not enough file handles::     File not found
* Using DATE::                  Problems using @code{DATE} columns
* Timezone problems::           Timezone problems
* Case sensitivity::            Case sensitivity in searches
* Problems with NULL::          Problems with @code{NULL} values
* Problems with alias::         Problems with @code{alias}
* Deleting from related tables::  Deleting rows from related tables
* No matching rows::            Solving problems with no matching rows
* ALTER TABLE problems::        Problems with @code{ALTER TABLE}.
* Change column order::         How to change the order of columns in a table
@end menu

@node Crashing, Common errors, Problems, Problems
@section What to do if @strong{MySQL} keeps crashing

All @strong{MySQL} versions are tested on many platforms before they are
released.  This doesn't mean that there isn't any bugs in
@strong{MySQL}, but that if there are bugs they are very few and can be
hard to find.  If you have a problem, it will always help if you try to
find out exactly what crashes your system as you will have a much better
chance of getting this fixed quickly.

First you should try to find out whether the problem is that the
@code{mysqld} daemon dies or whether your problem has to do with your
client.  You can check how long your @code{mysqld} server has been up by
executing @code{mysqladmin version}.  If @code{mysqld} has died, you may
find the reason for this in the file
@file{mysql-data-directory/'hostname'.err}.

Since it is very difficult to know why something is crashing, first try to
check whether or not things that work for others crash for you.  Please try
the following things:

@itemize @bullet
@item
Take down the @code{mysqld} daemon with @code{mysqladmin shutdown}, run
@code{isamchk --silent --force */*.ISM} on all tables and restart the
@code{mysqld} daemon.  This will ensure that you are running from a clean
state.  @xref{Maintenance}.

@item
Use @code{mysqld --log} and try to determine from the information in the log
whether or not some specific query kills the server. 95% of all bugs are
related to a particular query!  Normally this is one of the last queries in
the log file just before @strong{MySQL} restarted.

You may be able to verify this using the following procedure:

@itemize @bullet
@item
Take down the @strong{MySQL} daemon (with @code{mysqladmin shutdown})
@item
Make a backup of files in the @strong{MySQL} database directory.
@item
Check the tables with @code{isamchk -s */*.ISM} to verify that all tables
are correct.  If any table is corrupted, repair it with
@code{isamchk -r path-to-table.ISM}.
@item
Remove (or move away) any old log files from the @strong{MySQL} data directory.
@item
Start the server with @code{safe_mysql --log}.
@item
If @code{mysqld} now dies, you can test if the problem is a specific
query by restoring the backup and executing @code{mysql <
mysql-log-file}.  You can of course do the last test in some other
directory than the standard @strong{MySQL} database directory by
starting another @strong{MySQL} server with @code{safe_mysqld
--data=path-to-backup-directory}.
@end itemize

@item
Have you tried the benchmarks?  They should test @strong{MySQL} rather well.
You can also add code that simulates your application!  The benchmarks can be
found in the @file{bench} directory in the source distribution, or, for a
binary distribution, in the @file{sql-bench} directory under your
@strong{MySQL} installation directory.

@item
Try @code{fork_test.pl} and @code{fork2_test.pl}.

@item
Check the file @file{mysql-data-directory/'hostname'.err} for any errors.

@item
If you configure @strong{MySQL} for debugging, it will be much easier to
gather information about possible errors if something goes wrong.
Reconfigure @strong{MySQL} with the @code{--with-debug} option to
@code{configure} and then recompile.  @xref{Debugging server}.

@item
Configuring @strong{MySQL} for debugging causes a safe memory allocator to be
included that can find some errors. It also provides a lot of output about
what is happening.

@item
Have you applied the latest patches for your operating system?

@item
Use the @code{--skip-locking} option to @code{mysqld}.  On some systems, the
@code{lockd} lock manager does not work properly; the @code{--skip-locking}
option tells @code{mysqld} not to use external locking.  (This means that you
cannot run 2 @code{mysqld} servers on the same data and that you must be
careful if you use @code{isamchk}, but it may be instructive to try the
option as a test.)

@item
Have you tried @code{mysqladmin -u root processlist} when @code{mysqld}
appears to be running but not responding?  Sometimes @code{mysqld} is not
comatose even though you might think so.  The problem may be that all
connections are in use, or there may be some internal lock problem.
@code{mysqladmin processlist} will usually be able to make a connection even
in these cases, and can provide useful information about the current number
of connections and their status.

@item
Run the command @code{mysqladmin -i 5 status}
in a separate window to produce statistics while you run your other queries.

@item
Try the following:
@enumerate
@item
Start @code{mysqld} from @code{gdb} (or another debugger).

@item
Run your test scripts.

@item
Do @code{back} (or the backtrace command in your debugger) when
@code{mysqld} core dumps.
@end enumerate

@item
Try to simulate your application with a Perl script to force
@strong{MySQL} to crash or misbehave.

@item
Or send a normal bug report. @xref{Bug reports}. But be even more detailed
than usual.  Since @strong{MySQL} works for many people, it may be that the
crash results from something that exists only on your computer (for example,
an error that is related to your particular system libraries).
@item
If you have a problem with table with dynamic length rows and you are
not using @code{BLOB/TEXT} columns (but only @code{VARCHAR} columns) you
can try to change all @code{VARCHAR} to @code{CHAR} with @code{ALTER
TABLE}.  This will force @strong{MySQL} to use fixed size rows.  Fixed
size rows take a little extra place, but are much more tolerant for
corruption!

The current dynamic row code has been in use at TCX for at least 3
years without any problems, but by nature dynamic length rows are more
prone to errors so it may be a good idea to try if the above helps!
@end itemize

@node Common errors, Full disk, Crashing, Problems
@section Some common errors when using @strong{MySQL}

@menu
* Gone away::                   @code{MySQL server has gone away} error
* Can not connect to server::   @code{Can't connect to [local] MySQL server} error
* Blocked host::                @code{Host '...' is blocked} error
* Out of memory::               @code{Out of memory} error
* Packet too large::            @code{Packet too large} error
* Full table::                  @code{The table is full} error
* Commands out of sync::        @code{Commands out of sync} error in client
* Ignoring user::               @code{Ignoring user} error
* Cannot find table::           @code{Table 'xxx' doesn't exist} error
@end menu

@node Gone away, Can not connect to server, Common errors, Common errors
@subsection @code{MySQL server has gone away} error

The most common reason for the @code{MySQL server has gone away} error
is that the server timed out and closed the connection. By default, the
server closes the connection after 8 hours if nothing has happened.

You can check that the @strong{MySQL} hasn't died by executing
@code{mysqladmin version} and examining the uptime.

If you have a script, you just have to issue the query again for the client
to do an automatic reconnection.

You normally can get the following error codes in this case
(which one you get is OS-dependent):

@multitable @columnfractions .3 .7
@item @code{CR_SERVER_GONE_ERROR} @tab The client couldn't send a question to the
server.
@item @code{CR_SERVER_LOST} @tab  The client didn't get an error when writing
to the server, but it didn't get a full answer (or any answer) to the question.
@end multitable

You can also get these errors if you send a query to the server that is
incorrect or too large. If @code{mysqld} gets a packet that is too large
or out of order, it assumes that something has gone wrong with the client and
closes the connection.  If you need big queries (for example, if you are
working with big @code{BLOB} columns), you can increase the query limit by
starting @code{mysqld} with the @code{-O max_allowed_packet=#} option
(default 1M). The extra memory is allocated on demand, so @code{mysqld} will
use more memory only when you issue a big query or when @code{mysqld} must
return a big result row!

@node Can not connect to server, Blocked host, Gone away, Common errors
@subsection @code{Can't connect to [local] MySQL server} error

A @strong{MySQL} client can connect to the @code{mysqld} server in two
different ways: Unix sockets, which connect through a file in the file
system (default @file{/tmp/mysqld.sock}), or TCP/IP, which connects
through a port number.  Unix sockets are faster than TCP/IP but can only
be used when connecting to a server on the same computer.  Unix sockets
are used if you don't specify a hostname or if you specify the special
hostname @code{localhost}.

The error @code{Can't connect to ...} normally means that there isn't a
@strong{MySQL} server running on the system or that you are using a wrong
socket file or TCP/IP port when trying to connect to the @code{mysqld}
server.

Start by check (using @code{ps}) that there is a process running named
@code{mysqld} on your server!  If there isn't any @code{mysqld} process, you
should start one. @xref{Starting server}

If a @code{mysqld} process is running, you can check the server by
trying these different connections (the port number and socket pathname
might be different in your setup, of course):

@example
shell> mysqladmin version
shell> mysqladmin -h `hostname` version
shell> mysqladmin -h `hostname` --port=3306 version
shell> mysqladmin -h 'ip for your host' version
shell> mysqladmin --socket=/tmp/mysql.sock version
@end example

Note the use of backquotes rather than forward quotes with the @code{hostname}
command; these cause the output of @code{hostname} (i.e., the current
hostname) to be substituted into the @code{mysqladmin} command.

Here are some reasons the @code{Can't connect to local MySQL server}
error might occur:

@itemize @bullet
@item @code{mysqld} is not running.
@item You are running on a system that uses MIT-pthreads.
If you are running on a system that doesn't have native threads, @code{mysqld}
uses the MIT-pthreads package.
@xref{Which OS}.
However, MIT-pthreads doesn't support Unix sockets, so on such a system you
must always specify the hostname explicitly when connecting to the server.
Try using this command to check the connection to the server:
@example
shell> mysqladmin -h `hostname` version
@end example
@item Someone has removed the Unix socket that @code{mysqld} uses (default
@file{/tmp/mysqld.sock}).  You might have a @code{cron} job that removes the
@strong{MySQL} socket (e.g., a job that removes old files from the @file{/tmp}
directory).  You can always run @code{mysqladmin version} and
check that the socket @code{mysqladmin} is trying to use really exists.
The fix in this case is to change the @code{cron} job to not remove
@file{mysqld.sock} or to place the socket somewhere else. You can specify
a different socket location at @strong{MySQL} configuration time with this
command:
@example
shell> ./configure --with-unix-socket-path=/path/to/socket
@end example
You can also start @code{safe_mysqld} with the
@code{--socket=/path/to/socket} option and set the environment variable
@code{MYSQL_UNIX_PORT} to the socket pathname before starting your
@strong{MySQL} clients.  @item You have started the @code{mysqld} server with
the @code{--socket=/path/to/socket} option.  If you change the socket
pathname for the server, you must also notify the @strong{MySQL} clients
about the new path. You can do this by setting the environment variable
@code{MYSQL_UNIX_PORT} to the socket pathname or by providing the socket path
as an argument to the clients. You can test the socket with this command:

@example
shell> mysqladmin --socket=/path/to/socket version
@end example
@item
You are using Linux and one thread has died (core dumped).  In this case
you must kill the other @code{mysqld} threads (for example with the
@code{mysql_zap} script before you can start a new @strong{MySQL}
server.  @xref{Crashing}
@end itemize

If you get the error message @code{Can't connect to MySQL server on
some_hostname}, you can try the following things to find out what is the
problem:

@itemize @bullet
@item 
Check if the server up by doing @code{telnet your-host-name
tcp-ip-port-number} and press @code{RETURN} a couple of times.  If there
is a @strong{MySQL} server running on this port you should get a
responses that includes the version number of the running @strong{MySQL}
server.  If you get an error like @code{telnet: Unable to connect to
remote host: Connection refused}, then there is no server running on the
used port.
@item
Try connecting to the @code{mysqld} daemon on the local machine and check
the TCP/IP port that mysqld it's configured to use (variable @code{port}) with
@code{mysqladmin variables}.
@item
Check that your @code{mysqld} server is not started with the
@code{--skip-networking} option.
@end itemize

@node Blocked host, Out of memory, Can not connect to server, Common errors
@subsection @code{Host '...' is blocked} error

If you get a error like this:

@example
Host 'hostname' is blocked because of many connection errors.
Unblock with 'mysqladmin flush-hosts'
@end example

This means that @code{mysqld} has gotten a lot (@code{max_connect_errors})
of connect requests from the host @code{'hostname'} that have been interrupted
in the middle. After @code{max_connect_errors} failed requests, @code{mysqld}
assumes that something is wrong (like a attack from a cracker), and
blocks the site from further connections until someone executes the command
@code{mysqladmin flush-hosts}.

By default, @code{mysqld} blocks a host after 10 connection errors.
You can easily adjust this by starting the server like this:

@example
shell> safe_mysqld -O max_connect_errors=10000 &
@end example

Note that if you get this error message for a given host, you should first
check that there isn't anything wrong with TCP/IP connections from that
host.  If your TCP/IP connections aren't working, it won't do you any good to
increase the value of the @code{max_connect_errors} variable!

@node Out of memory, Packet too large, Blocked host, Common errors
@subsection @code{Out of memory} error

If you issue a query and get something like the following error:

@example
mysql: Out of memory at line 42, 'malloc.c'
mysql: needed 8136 byte (8k), memory in use: 12481367 bytes (12189k)
ERROR 2008: MySQL client ran out of memory
@end example

Note that the error refers to the @strong{MySQL} client @code{mysql}. The
reason for this error is simply that the client does not have enough memory to
store the whole result.

To remedy the problem, first check that your query is correct. Is it
reasonable that it should return so many rows?  If so,
you can use @code{mysql --quick}, which uses @code{mysql_use_result()}
to retrieve the result set.  This places less of a load on the client (but
more on the server).

@node Packet too large, Full table, Out of memory, Common errors
@subsection @code{Packet too large} error

When a @strong{MySQL} client or the @code{mysqld} server gets a packet bigger
than @code{max_allowed_packet} bytes, it issues a @code{Packet too large}
error and closes the connection.

If you are using the @code{mysql} client, you may specify a bigger buffer by
starting the client with @code{mysql --set-variable=max_allowed_packet=8M}.

If you are using other clients that do not allow you to specify the maximum
packet size (such as @code{DBI}), you need to set the packet size when you
start the server.  You cau use a command-line option to @code{mysqld} to set
@code{max_allowed_packet} to a larger size.  For example, if you are
expecting to store the full length of a @code{BLOB} into a table, you'll need
to start the server with the @code{--set-variable=max_allowed_packet=24M}
option.

@cindex The table is full
@node Full table, Commands out of sync, Packet too large, Common errors
@subsection @code{The table is full} error

This error occurs when an in-memory temporary table becomes larger than
@code{tmp_table_size} bytes. To avoid this problem, you can use the
@code{-O tmp_table_size=#} option to @code{mysqld} to increase the
temporary table size, or use the SQL option @code{SQL_BIG_TABLES} before
you issue the problematic query. @xref{SET OPTION, , @code{SET OPTION}}.

You can also start @code{mysqld} with the @code{--big-tables} option.
This is exactly the same as using @code{SQL_BIG_TABLES} for all queries.

@cindex Commands out of sync
@node Commands out of sync, Ignoring user, Full table, Common errors
@subsection @code{Commands out of sync} error in client

If you get @code{Commands out of sync; You can't run this command now}
in your client code, you are calling client functions in the wrong order!

This can happen, for example, if you are using @code{mysql_use_result()} and
try to execute a new query before you have called @code{mysql_free_result()}.
It can also happen if you try to execute two queries that return data without
a @code{mysql_use_result()} or @code{mysql_store_result()} in between.

@node Ignoring user, Cannot find table, Commands out of sync, Common errors
@subsection @code{Ignoring user} error

If you get the following error:

@code{Found wrong password for user: 'some_user@@some_host'; Ignoring user}

This means that when @code{mysqld} was started or when it reloaded the
permissions tables, it found an entry in the @code{user} table with
an invalid password.  As a result, the entry is simply ignored by the
permission system.

Possible causes of and fixes for this problem:

@itemize @bullet
@item
You may be running a new version of @code{mysqld} with an old
@code{user} table.
You can check this by executing @code{mysqlshow mysql user} to see if
the password field is shorter than 16 characters. If so, you can correct this
condition by running the @code{scripts/add_long_password} script.

@item
The user has an old password (8 chararacters long) and you didn't start
@code{mysqld} with the @code{--old-protocol} option.
Update the user in the @code{user} table with a new password or
restart @code{mysqld} with @code{--old-protocol}.

@item
@findex PASSWORD()
You have specified a password in the @code{user} table without using the
@code{PASSWORD()} function.  Use @code{mysql} to update the user in the
@code{user} table with a new password. Make sure to use the @code{PASSWORD()}
function:

@example
mysql> update user set password=PASSWORD('your password')
           where user='XXX';
@end example
@end itemize

@node Cannot find table,  , Ignoring user, Common errors
@subsection @code{Table 'xxx' doesn't exist} error

If you get the error @code{Table 'xxx' doesn't exist} or @code{Can't
find file: 'xxx' (errno: 2)}, this means that no table exists
in the current database with the name @code{xxx}.

Note that as @strong{MySQL} uses directories and files to store databases and
tables, the database and table names are @strong{case sensitive}!
(On Win32 the databases and tables names are not case sensitive, but all
references to a given table within a query must use the same case!)

You can check which tables you have in the current database with
@code{SHOW TABLES}. @xref{SHOW, , @code{SHOW}}.

@cindex Full disk
@cindex Disk full
@node Full disk, Multiple sql commands, Common errors, Problems
@section How @strong{MySQL} handles a full disk

@noindent
When a disk full condition occurs, @strong{MySQL} does the following:

@itemize @bullet
@item
It checks once every minute to see whether or not there is enough space to
write the current row. If there is enough space, it continues as if nothing had
happened.
@item
Every 6 minutes it writes an entry to the log file warning about the disk
full condition.
@end itemize

@noindent
To alleviate the problem, you can take the following actions:

@itemize @bullet
@item
To continue, you only have to free enough disk space to insert all records.
@item
To abort the thread, you must send a @code{mysqladmin kill} to the thread.
The thread will be aborted the next time it checks the disk (in 1 minute).
@item
Note that other threads may be waiting for the table that caused the ``disk
full'' condition.  If you have several ``locked'' threads, killing the one
thread that is waiting on the disk full condition will allow the other
threads to continue.
@end itemize

@node Multiple sql commands, Temporary files, Full disk, Problems
@section How to run SQL commands from a text file

The @code{mysql} client typically is used interactively, like this:

@example
shell> mysql database
@end example

However, it's also possible to put your SQL commands in a file and tell
@code{mysql} to read its input from that file.  To do so, create a text
file @file{text_file} that contains the commands you wish to execute.
Then invoke @code{mysql} as shown below:

@example
shell> mysql database < text_file
@end example

You can also start your text file with a @code{USE db_name} statement.  In
this case, it is unnecessary to specify the database name on the command
line:

@example
shell> mysql < text_file
@end example

@xref{Programs}.

@node Temporary files, Problems with mysql.sock, Multiple sql commands, Problems
@section Where @strong{MySQL} stores temporary files

@strong{MySQL} uses the value of the @code{TMPDIR} environment variable as
the pathname of the directory in which to store temporary files.  If you don't
have @code{TMPDIR} set, @strong{MySQL} uses the system default, which is
normally @file{/tmp} or @file{/usr/tmp}.  If the file system containing your
temporary file directory is too small, you should edit @code{safe_mysqld} to
set @code{TMPDIR} to point to a directory in a file system where you have
enough space!  You can also set the temporary directory using the
@code{--tmpdir} option to @code{mysqld}.

@strong{MySQL} creates all temporary files as ``hidden files''. This ensures
that the temporary files will be removed if @code{mysqld} is terminated.  The
disadvantage of using hidden files is that you will not see a big temporary
file that fills up the file system in which the temporary file directory is
located.

When sorting (@code{ORDER BY} or @code{GROUP BY}), @strong{MySQL} normally
uses one or two temporary files. The maximum disk-space needed is:

@example
(length of what is sorted + sizeof(database pointer))
* number of matched rows
* 2
@end example

@code{sizeof(database pointer)} is usually 4, but may grow in the future for
really big tables.

For some @code{SELECT} queries, @strong{MySQL} also creates temporary SQL
tables. These are not hidden and have names of the form @file{SQL_*}.

@code{ALTER TABLE} and @code{OPTIMIZE TABLE} create a temporary table in the
same directory as the original table.

@node  Problems with mysql.sock, Error Access denied, Temporary files, Problems
@section How to protect @file{/tmp/mysql.sock} from being deleted

If you have problems with the fact that anyone can delete the
@strong{MySQL} communication socket @file{/tmp/mysql.sock}, you can,
on most versions of Unix, protect your @file{/tmp} file system by setting
the @code{sticky} bit on it.  Log in as @code{root} and do the following:

@example
shell> chmod +s /tmp
@end example

This will protect your @file{/tmp} file system so that files can be deleted
only by their owners or the superuser (@code{root}).

You can check if the @code{sticky} bit is set by executing @code{ls -ld /tmp}.
If the last permission bit is @code{t}, the bit is set.

@node Error Access denied, Changing MySQL user , Problems with mysql.sock, Problems
@section @code{Access denied} error

@xref{Privileges}. And especially see @ref{Access denied}.

@node Changing MySQL user , File permissions , Error Access denied, Problems
@section How to run @strong{MySQL} as a normal user

The @strong{MySQL} server @code{mysqld} can be started and run by any user.
In order to change @code{mysqld} to run as Unix user @code{user_name}, you must
do the following:

@enumerate
@item
Stop the server if it's running (use @code{mysqladmin shutdown}).

@item
Change the database directories and files so that @code{user_name} has
privileges to read and write files in them (you may need to do this as
the Unix @code{root} user):

@example
shell> chown -R user_name /path/to/mysql/datadir
@end example

If directories or files within the @strong{MySQL} data directory are
symlinks, you'll also need to follow those links and change the directories
and files they point to.  @code{chown -R} may not follow symlinks for
you.

@item
Start the server as user @code{user_name}, or, if you are using
@strong{MySQL} 3.22 or later, start @code{mysqld} as the Unix @code{root}
user and use the @code{--user=user_name} option.  @code{mysqld} will switch
to run as Unix user @code{user_name} before accepting any connections.

@item
If you are using the @code{mysql.server} script to start @code{mysqld} when
the system is rebooted, you should edit @code{mysql.server} to use @code{su}
to run @code{mysqld} as user @code{user_name}, or to invoke @code{mysqld}
with the @code{--user} option.  (No changes to @code{safe_mysqld} are
necessary.)
@end enumerate

At this point, your @code{mysqld} process should be running fine and dandy as
the Unix user @code{user_name}. One thing hasn't changed, though: the
contents of the permissions tables. By default (right after running the
permissions table install script @code{mysql_install_db}), the @strong{MySQL}
user @code{root} is the only user with permission to access the @code{mysql}
database or to create or drop databases.  Unless you have changed those
permissions, they still hold. This shouldn't stop you from accessing
@strong{MySQL} as the @strong{MySQL} @code{root} user when you're logged in
as a Unix user other than @code{root}; just specify the @code{-u root} option
to the client program.

Note that accessing @strong{MySQL} as @code{root}, by supplying @code{-u
root} on the command line, has @emph{nothing} to do with @strong{MySQL} running
as the Unix @code{root} user, or, indeed, as other Unix user. The access
permissions and user names of @strong{MySQL} are completely separate from
Unix user names. The only connection with Unix user names is that if you
don't provide a @code{-u} option when you invoke a client program, the client
will try to connect using your Unix login name as your @strong{MySQL} user
name.

If your Unix box itself isn't secured, you should probably at least put a
password on the @strong{MySQL} @code{root} users in the access tables.
Otherwise, any user with an account on that machine can run @code{mysql -u
root db_name} and do whatever he likes.

@node File permissions , Not enough file handles, Changing MySQL user , Problems
@section Problems with file permissions

If you have problems with file permissions, for example, if @code{mysql}
issues the following error message when you create a table:

@example
ERROR: Can't find file: 'path/with/filename.frm' (Errcode: 13)
@end example

Then the environment variable @code{UMASK} might be set incorrectly when
@code{mysqld} starts up.  The default umask value is @code{0660}. You can
change this behavior by starting @code{safe_mysqld} as follows:

@example
shell> UMASK=384  # = 600 in octal
shell> export UMASK
shell> /path/to/safe_mysqld &
@end example

@node Not enough file handles, Using DATE, File permissions , Problems
@section File not found

If you get @code{ERROR '...' not found (errno: 23)}, @code{Can't open
file: ... (errno: 24)} or any other error with @code{errno 23} or
@code{errno 24} from @strong{MySQL}, it means that you haven't allocated
enough file descriptors for @strong{MySQL}.  You can use the
@code{perror} utility to get a description of what the error number
means:

@example
shell> perror 23
File table overflow
shell> perror 24
Too many open files
@end example

The problem here is that @code{mysqld} is trying to keep open too many
files simultaneously.  You can either tell @code{mysqld} not to open so
many files at once, or increase the number of file descriptors
available to @code{mysqld}.

To tell @code{mysqld} to keep open fewer files at a time, you can make the
table cache smaller by using the @code{-O table_cache=32} option
to @code{safe_mysqld} (the default value is 64). Reducing the value of
@code{max_connections} will also reduce the number of open files (the default
value is 90).

To change the number of file descriptors available to @code{mysqld}, modify
the @code{safe_mysqld} script.  There is a commented-out line
@code{ulimit -n 256} in the script.  You can remove the @code{'#'} character
to uncomment this line, and change the number 256 to change the number of
file descriptors available to @code{mysqld}.

@code{ulimit} can increase the number of file descriptors, but only up to the
limit imposed by the operating system.  If you need to increase the OS limit
on the number of file descriptors available to each process, consult the
documentation for your operating system.

Note that if you run the @code{tcsh} shell, @code{ulimit} will not work!
@code{tcsh} will also report incorrect values when you ask for the current
limits!  In this case you should start @code{safe_mysqld} with @code{sh}!

@node Using DATE, Timezone problems, Not enough file handles, Problems
@section Problems using @code{DATE} columns

The format of a @code{DATE} value is @code{'YYYY-MM-DD'}. According to ANSI
SQL, no other format is allowed. You should use this format in @code{UPDATE}
expressions and in the WHERE clause of @code{SELECT} statements.  For
example:

@example
mysql> SELECT * FROM tbl_name WHERE date >= '1997-05-05';
@end example

As a convenience, @strong{MySQL} automatically converts a date to a number if
the date is used in a numeric context (and vice versa). It is also smart
enough to allow a ``relaxed'' string form when updating and in a @code{WHERE}
clause that compares a date to a @code{TIMESTAMP}, @code{DATE} or a
@code{DATETIME} column.  (Relaxed form means that any non-numeric character
may be used as the separator between parts. For example, @code{'1998-08-15'}
and @code{'1998#08#15'} are equivalent.) @strong{MySQL} can also convert a
string containing no separators (such as @code{'19980815'}), provided it
makes sense as a date.

The special date @code{'0000-00-00'} can be stored and retrieved as
@code{'0000-00-00'.} When using a @code{'0000-00-00'} date through
@strong{MyODBC}, it will automatically be converted to @code{NULL} in
@strong{MyODBC} 2.50.12 and above, because ODBC can't handle this kind of
date.

Since @strong{MySQL} performs the conversions described above, the following
statements work:

@example
mysql> INSERT INTO tbl_name (idate) VALUES (19970505);
mysql> INSERT INTO tbl_name (idate) VALUES ('19970505');
mysql> INSERT INTO tbl_name (idate) VALUES ('97-05-05');
mysql> INSERT INTO tbl_name (idate) VALUES ('1997.05.05');
mysql> INSERT INTO tbl_name (idate) VALUES ('1997 05 05');
mysql> INSERT INTO tbl_name (idate) VALUES ('0000-00-00');

mysql> SELECT idate FROM tbl_name WHERE idate >= '1997-05-05';
mysql> SELECT idate FROM tbl_name WHERE idate >= 19970505;
mysql> SELECT mod(idate,100) FROM tbl_name WHERE idate >= 19970505;
mysql> SELECT idate FROM tbl_name WHERE idate >= '19970505';
@end example

@noindent
However, the following will not work:

@example
mysql> SELECT idate FROM tbl_name WHERE STRCMP(idate,'19970505')=0;
@end example

@code{STRCMP()} is a string function, so it converts @code{idate} to
a string and performs a string comparison.  It does not convert
@code{'19970505'} to a date and perform a date comparison.

Note that @strong{MySQL} does no checking whether or not the date is
correct.  If you store an incorrect date, such as @code{'1998-2-31'}, the
wrong date will be stored. If the date cannot be converted to any reasonable
value, a @code{0} is stored in the @code{DATE} field.  This is mainly a speed
issue and we think it is up to the application to check the dates, and not
the server.

@cindex Timezone problems
@tindex TZ environment variable
@tindex Environment variable, TZ
@node Timezone problems, Case sensitivity, Using DATE, Problems
@section Timezone problems

If you have a problem with @code{SELECT NOW()} returning values in GMT and
not your local time, you have to set the @code{TZ} environment variable to
your current timezone.  This should be done for the environment in which
the server runs, for example in @code{safe_mysqld} or @code{mysql.server}.

@cindex Case sensitivity, in searches
@cindex Chinese
@cindex Big5 Chinese character encoding
@node Case sensitivity, Problems with NULL, Timezone problems, Problems
@section Case sensitivity in searches

By default, @strong{MySQL} searches are case-insensitive (although there are
some character sets that are never case insensitive, such as @code{czech}).
That means that if you search with @code{col_name LIKE 'a%'}, you will get all
column values that start with @code{A} or @code{a}. If you want to make this
search case-sensitive, use something like @code{INDEX(col_name, "A")=0} to
check a prefix. Or use @code{STRCMP(col_name, "A") = 0} if the column value
must be exactly @code{"A"}.

Simple comparison operations (@code{>=, >, = , < , <=}, sorting and
grouping) are based on each character's ``sort value''. Characters with
the same sort value (like E, e and @'e) are treated as the same character!

@code{LIKE} comparisons are done on the uppercase value of each character
(E == e but E <> @'e)

If you want a column always to be treated in case-sensitive fashion,
declare it as @code{BINARY}. @xref{CREATE TABLE, , @code{CREATE TABLE}}.

If you are using Chinese data in the so-called big5 encoding, you want to
make all character columns @code{BINARY}. This works because the sorting
order of big5 encoding characters is based on the order of ASCII codes.

@cindex @code{NULL} values vs. empty values
@tindex NULL
@node Problems with NULL, Problems with alias, Case sensitivity, Problems
@section Problems with @code{NULL} values

The concept of the @code{NULL} value is a common source of confusion for
newcomers to SQL, who often think that @code{NULL} is the same thing as an
empty string @code{''}.  This is not the case! For example, the following
statements are completely different:

@example
mysql> INSERT INTO my_table (phone) VALUES (NULL);
mysql> INSERT INTO my_table (phone) VALUES ("");
@end example

Both statements insert a value into the @code{phone} column, but the first
inserts a @code{NULL} value and the second inserts an empty string.  The
meaning of the first can be regarded as ``phone number is not known'' and the
meaning of the second can be regarded as ``she has no phone''.

In SQL, the @code{NULL} value is always false in comparison to any
other value, even @code{NULL}.  An expression that contains @code{NULL}
always produces a @code{NULL} value unless otherwise indicated in
the documentation for the operators and functions involved in the
expression. All columns in the following example return @code{NULL}:

@example
mysql> SELECT NULL,1+NULL,CONCAT('Invisible',NULL);
@end example

If you want to search for column values that are @code{NULL}, you
cannot use the @code{=NULL} test. The following statement returns no
rows, because @code{expr = NULL} is FALSE, for any expression:

@example
mysql> SELECT * FROM my_table WHERE phone = NULL;
@end example

To look for @code{NULL} values, you must use the @code{IS NULL} test.
The following shows how to find the @code{NULL} phone number and the
empty phone number:

@example
mysql> SELECT * FROM my_table WHERE phone IS NULL;
mysql> SELECT * FROM my_table WHERE phone = "";
@end example

In @strong{MySQL}, as in many other SQL servers, you can't index
columns that can have @code{NULL} values.  You must declare such columns
@code{NOT NULL}. Conversely, you cannot insert @code{NULL} into an indexed
column.

@findex LOAD DATA INFILE
When reading data with @code{LOAD DATA INFILE}, empty columns are updated
with @code{''}. If you want a @code{NULL} value in a column, you should use
@code{\N} in the text file. The literal word @code{'NULL'} may also be used
under some circumstances.
@xref{LOAD DATA, , @code{LOAD DATA}}.

When using @code{ORDER BY}, @code{NULL} values are presented first. If you
sort in descending order using @code{DESC}, @code{NULL} values are presented
last.  When using @code{GROUP BY}, all @code{NULL} values are regarded as
equal.

To help with @code{NULL} handling, you can use the @code{IS NULL} and
@code{IS NOT NULL} operators and the @code{IFNULL()} function.

@cindex @code{TIMESTAMP}, and @code{NULL} values
@cindex @code{AUTO_INCREMENT}, and @code{NULL} values
@cindex @code{NULL} values, and @code{TIMESTAMP} columns
@cindex @code{NULL} values, and @code{AUTO_INCREMENT} columns
For some column types, @code{NULL} values are handled specially.  If you
insert @code{NULL} into the first @code{TIMESTAMP} column of a table, the
current date and time is inserted.  If you insert @code{NULL} into an
@code{AUTO_INCREMENT} column, the next number in the sequence is inserted.

@tindex alias
@node Problems with alias, Deleting from related tables, Problems with NULL, Problems
@section Problems with @code{alias}

You can use alias to refer to a column in the @code{GROUP BY},
@code{ORDER BY} or in the @code{HAVING} part.  Aliases can also be used
to give columns more better names:

@example
SELECT SQRT(a*b) as rt FROM table_name GROUP BY rt HAVING rt > 0;
SELECT id,COUNT(*) AS cnt FROM table_name GROUP BY id HAVING cnt > 0;
SELECT id AS "Customer identity" FROM table_name;
@end example

Note that you ANSI SQL doesn't allow you to refer to an alias in a
@code{WHERE} clause.  This is because that when the @code{WHERE} code is
executed the column value may not yet be determinated. For example the
following query is @strong{illegal}:

@example
SELECT id,COUNT(*) AS cnt FROM table_name WHERE cnt > 0 GROUP BY id;
@end example

The @code{WHERE} statement is executed to determinate which rows should
be included in the @code{GROUP BY} part while @code{HAVING} is used to
decide which rows from the result set should be used.

@node Deleting from related tables, No matching rows, Problems with alias, Problems
@section Deleting rows from related tables

As @strong{MySQL} doesn't support sub-selects or use of more than one table
in the @code{DELETE} statement, you should use the following approach to
delete rows from 2 related tables:

@enumerate
@item
@code{SELECT} the rows based on some @code{WHERE} condition in the main table.
@item
@code{DELETE} the rows in the main table based on the same condition.
@item
@code{DELETE FROM related_table WHERE related_column IN (selected_rows)}
@end enumerate

If the total number of characters in the query with
@code{related_column} is more than 1,048,576 (the default value of
@code{max_allowed_packet}, you should split it into smaller parts and
execute multiple @code{DELETE} statements.  You will probably get the
fastest @code{DELETE} by only deleting 100-1000 @code{related_column}
id's per time if the @code{related_column} is an index.  If the
@code{related_column} isn't an index, the speed is independent of the
number of arguments in the @code{IN} clause.

@node No matching rows, ALTER TABLE problems, Deleting from related tables, Problems
@section Solving problems with no matching rows

If you have a complicated query with many tables that doesn't return any
rows, you should use the following procedure to find out what is wrong
with your query:

@enumerate
@item
Test the query with @code{EXPLAIN} and check if you can find something that is
obviously wrong. @xref{EXPLAIN, , @code{EXPLAIN}}.

@item
Select only those fields that are used in the @code{WHERE} clause.

@item
Remove one table at a time from the query until it returns some rows.
If the tables are big, it's a good idea to use @code{LIMIT 10} with the query.

@item
Do a @code{SELECT} for the column that should have matched a row,
against the table that was last removed from the query.

@item
If you are comparing @code{FLOAT} or @code{DOUBLE} columns with numbers that
have decimals, you can't use @code{=}!  This problem is common in most
computer languages because floating point values are not exact values.

@example
mysql> SELECT * FROM table_name WHERE float_column=3.5;
   ->
mysql> SELECT * FROM table_name WHERE float_column between 3.45 and 3.55;
@end example

In most cases, changing the @code{FLOAT} to a @code{DOUBLE} will fix this!

@item
If you still can't find out what's wrong, create a minimal test that can
be run with @code{mysql test < query.sql} that shows your problems.
You can create a test file with @code{mysqldump --quick database tables > query.sql}. Take the file up in a editor, remove some insert lines (if there are
too many of these) and add your select statement last in the file.

Test that you still have your problem by doing:

@example
shell> mysqladmin create test2
shell> mysql test2 < query.sql
@end example

Post the test file using @code{mysqlbug} to @email{mysql@@lists.mysql.com}.
@end enumerate

@node ALTER TABLE problems, Change column order, No matching rows, Problems
@section Problems with @code{ALTER TABLE}.

If @code{ALTER TABLE} dies with an error like this:

@example
Error on rename of './database/name.frm' to './database/B-a.frm' (Errcode: 17)
@end example

The problem may be that @strong{MySQL} has crashed in a previous @code{ALTER
TABLE} and there is an old table named @file{A-something} or
@file{B-something} lying around.  In this case, go to the @strong{MySQL} data
directory and delete all files that have names starting with @code{A-} or
@code{B-}.  (You may want to move them elsewhere instead of deleting them).

@code{ALTER TABLE} works the following way:

@itemize @bullet
@item Create a new table named @file{A-xxx} with the requested changes.
@item All rows from the old table are copied to @file{A-xxx}.
@item The old table is renamed @file{B-xxx}.
@item @file{A-xxx} is renamed to your old table name.
@item @file{B-xxx} is deleted.
@end itemize

If something goes wrong with the renaming operation, @strong{MySQL} tries to
undo the changes.  If something goes seriously wrong (this shouldn't happen,
of course), @strong{MySQL} may leave the old table as @file{B-xxx} but a
simple rename should get your data back.

@node Change column order,  , ALTER TABLE problems, Problems
@section How to change the order of columns in a table

The whole point of SQL is to abstract the application from the data
storage format.  You should always specify the order in wish you wish to
retrieve your data.  For example:

@example
SELECT col_name1, col_name2, col_name3 FROM tbl_name;
@end example

will return columns in the order @code{col_name1}, @code{col_name2}, @code{col_name3}, whereas:

@example
SELECT col_name1, col_name3, col_name2 FROM tbl_name;
@end example

will return columns in the order @code{col_name1}, @code{col_name3}, @code{col_name2}.

You should @strong{NEVER}, in an application, use @code{SELECT *} and
retrieve the columns based on their position, because the order in which columns are
returned @strong{CANNOT} be guaranteed over time; A simple change to
your database may cause your application to fail rather dramatically.

If you want to change the order of columns anyway, you can do it as follows:

@enumerate
@item
Create a new table with the columns in the right order.
@item
Execute
@code{INSERT INTO new_table SELECT fields-in-new_table-order FROM old_table}.
@item
Drop or rename @code{old_table}
@item
@code{ALTER TABLE new_table RENAME old_table}
@end enumerate

@node Common problems, Clients, Problems, Top
@chapter Solving some common problems with @strong{MySQL}

@cindex Replication
@menu
* Replication::                 Database replication
* Backup::                      Database backups
* Multiple servers::            Running multiple @strong{MySQL} servers on the same machine
@end menu

@cindex Database replication
@cindex Replication, database
@node Replication, Backup, Common problems, Common problems
@section Database replication

The most general way to replicate a database is to use the update
log. @xref{Update log}. This requires one database that acts as a master
(to which data changes are made) and one or more other databases that act
as slaves. To update a slave, just run @code{mysql < update_log}.
Supply host, user and password options that are appropriate for the slave
database, and use the update log from the master database as input.

If you never delete anything from a table, you can use a @code{TIMESTAMP}
column to find out which rows have been inserted or changed in the table
since the last replication (by comparing to the time when you did the
replication last time) and only copy these rows to the mirror.

It is possible to make a two-way updating system using both the update
log (for deletes) and timestamps (on both sides). But in that case you
must be able to handle conflicts when the same data have been changed in
both ends. You probably want to keep the old version to help with
deciding what has been updated.

Because replication in this case is done with SQL statements, you should not
use the following functions in statements that update the database; they may
not return the same value as in the original database:

@itemize @bullet
@item @code{DATABASE()}
@item @code{GET_LOCK()} and @code{RELEASE_LOCK()}
@item @code{RAND()}
@item @code{USER()}, @code{SYSTEM_USER()} or @code{SESSION_USER()}
@item @code{VERSION()}
@end itemize

All time functions are safe to use, as the timestamp is sent to the
mirror if needed. @code{LAST_INSERT_ID()} is also safe to use.

@cindex Backups
@node Backup, Multiple servers, Replication, Common problems
@section Database backups

Since @strong{MySQL} tables are stored as files, it is easy to do a
backup. To get a consistent backup, do a @code{LOCK TABLES} on the
relevant tables. @xref{LOCK TABLES, , @code{LOCK TABLES}}. You only need a
read lock; this allows other threads to continue to query the tables while
you are making a copy of the files in the database directory. If you want to
make a SQL level backup, you can use @code{SELECT INTO OUTFILE}.

Another way to backup a database is to use the @code{mysqldump} program:

@enumerate
@item
Do a full backup of your databases:

@example
shell> mysqldump --tab=/path/to/some/dir --lock-tables --opt
@end example

You can also simply copy all table files (@file{*.frm}, @file{*.ISD} and
@file{*.ISM} files), as long as the server isn't updating anything.

@item
@cindex Log file, names
Stop @code{mysqld} if it's running, then start it with the
@code{--log-update} option.  You will get log files with names of the
form @file{@kbd{hostname}.n}, where @code{n} is a number that is
incremented each time you execute @code{mysqladmin refresh} or
@code{mysqladmin flush-logs}, the @code{FLUSH LOGS} statement, or
restart the server.  These log files provide you with the information
you need to replicate changes to the database that are made subsequent
to the point at which you executed @code{mysqldump}.
@end enumerate

If you have to restore something, try to recover your tables using
@code{isamchk -r} first.  That should work in 99.9% of all cases.  If
@code{isamchk} fails, try the following procedure:

@enumerate
@item
Restore the original @code{mysqldump} backup.
@item
Execute the following command to re-run the updates in the update logs:
@example
shell> ls -1 -t -r hostname.[0-9]* | xargs cat | mysql
@end example
@end enumerate

@code{ls} is used to get all the log files in the right order.

You can also do selective backups with @code{SELECT * INTO OUTFILE 'file_name'
FROM tbl_name} and restore with @code{LOAD DATA INFILE 'file_name' REPLACE
...} To avoid duplicate records, you need a @code{PRIMARY KEY} or a
@code{UNIQUE} key in the table. The @code{REPLACE} keyword causes old records
to be replaced with new ones when a new record duplicates an old record on
a unique key value.

@cindex Multiple servers
@node Multiple servers,  , Backup, Common problems
@section Running multiple @strong{MySQL} servers on the same machine

There are circumstances when you might want to run multiple servers on the same
machine.  For example, you might want to test a new @strong{MySQL} release
while leaving your existing production setup undisturbed.  Or you might
be an Internet service provider that wants to provide independent
@strong{MySQL} installations for different customers.

If you want to run multiple servers, the easiest way is to compile the servers
with different TCP/IP ports and socket files so they are not
both listening to the same TCP/IP port or socket file.

Assume an existing server is configured for the default port number and
socket file.  Then configure the new server with a @code{configure} command
something like this:

@example
shell> ./configure  --with-tcp-port=port_number \
             --with-unix-socket=file_name \
             --prefix=/usr/local/mysql-3.22.9
@end example

Here @code{port_number} and @code{file_name} should be different than the
default port number and socket file pathname, and the @code{--prefix} value
should specify an installation directory different than the one under which
the existing @strong{MySQL} installation is located.

You can check the socket and port used by any currently-executing
@strong{MySQL} server with this command:

@example
shell> mysqladmin -h hostname --port=port_number variables
@end example

If you have a @strong{MySQL} server running on the port you used, you will
get a list of some of the most important configurable variables in
@strong{MySQL}, including the socket name.

You should also edit the initialization script for your machine (probably
@file{mysql.server}) to start and kill multiple @code{mysqld} servers.

You don't have to recompile a new @strong{MySQL} server just to start with
a different port and socket.  You can change the port and socket to be used
by specifying them at runtime as options to @code{safe_mysqld}:

@example
shell> /path/to/safe_mysqld --socket=file_name --port=port_number
@end example

If you run the new server on the same database directory as another server
with logging enabled, you should also specify the name of the log files
to @code{safe_mysqld} with @code{--log} and @code{--log-update}.  Otherwise,
both servers may be trying to write to the same log file.

@strong{Warning}: Normally you should never have two servers that update
data in the same database!  If your OS doesn't support fault-free system
locking, this may lead to unpleasant surprises!

If you want to use another database directory for the second server, you
can use the @code{--datadir=path} option to @code{safe_mysqld}.

When you want to connect to a @strong{MySQL} server that is running with
a different port than the port that is compiled into your client, you
can use one of the following methods:

@itemize @bullet
@item
Start the client with @code{--host 'hostname' --port=port_numer} or
@code{[--host localhost] --socket=file_name}.

@item
In your C or Perl programs, you can give the port and socket arguments
when connecting to the @strong{MySQL} server.

@item
@tindex MYSQL_UNIX_PORT environment variable
@tindex MYSQL_TCP_PORT environment variable
@tindex Environment variable, MYSQL_UNIX_PORT
@tindex Environment variable, MYSQL_TCP_PORT
Set the @code{MYSQL_UNIX_PORT} and @code{MYSQL_TCP_PORT} environment variables
to point to the Unix socket and TCP/IP port before you start your clients.
If you normally use a specific socket or port, you should place commands
to set these environment variables in your @file{.login} file.
@xref{Programs}.

@item
@tindex .my.cnf file
Specify the default socket and TCP/IP port in the @file{.my.cnf} file in your
home directory. @xref{Option files}.
@end itemize

@node Clients, Comparisons, Common problems, Top
@chapter @strong{MySQL} client tools and APIs

@menu
* C::                           @strong{MySQL} C API
* C API datatypes::             C API datatypes
* C API function overview::     C API function Overview
* C API functions::             C API function descriptions
* Perl::                        @strong{MySQL} Perl API
* Java::                        @strong{MySQL} Java connectivity (JDBC)
* PHP::                         @strong{MySQL} PHP API
* Cplusplus::                   @strong{MySQL} C++ APIs
* Python::                      @strong{MySQL} Python APIs
* TCL::                         @strong{MySQL} TCL APIs
@end menu

@node C, C API datatypes, Clients, Clients
@section @strong{MySQL} C API

The C API code is distributed with @strong{MySQL}. It is included in the
@code{mysqlclient} library and allows C programs to access a database.

Many of the clients in the MySQL source distribution are written in C.  If
you are looking for examples that demonstrate how to use the C API, take a
look at these clients.

Most of the other client APIs (all except Java) use the @code{mysqlclient}
library to communicate with the @strong{MySQL} server. This means that, for
example, you can take advantage of many of the same environment variables
that are used by other client programs, because they are referenced from the
library.  See @ref{Programs}, for a list of these variables.

The client has a maximum communication buffer size. The size of the buffer
that is allocated initially (16K bytes) is automatically increased up to the
maximum size (the default maximum is 24M). Since buffer sizes are increased
only as demand warrants, simply increasing the default maximum limit does not
in inself cause more resources to be used. This size check is mostly a check
for erroneous queries and communication packets.

The communication buffer must be large enough to contain a single SQL
statement (for client-to-server traffic) and one row of returned data (for
server-to-client traffic).  Each thread's communication buffer is dynamically
enlarged to handle any query or row up to the maximum limit.  For example, if
you have @code{BLOB} values that contain up to 16M of data, you must have a
communication buffer limit of at least 16M (in both server and client).  The
client's default maximum is 24M, but the default maximum in the server is
1M.  You can increase this by changing the value of the
@code{max_allowed_packet} parameter when the server is started.  @xref{Server
parameters}.

The @strong{MySQL} server shrinks each communication buffer to
@code{net_buffer_length} bytes after each query.  For clients, the size of
the buffer associated with a connection is not decreased until the connection
is closed, at which time client memory is reclaimed.

@node C API datatypes, C API function overview, C, Clients
@section C API datatypes
@table @code

@tindex MYSQL C type
@item MYSQL
This structure represents a handle to one database connection. It is
used for almost all @strong{MySQL} functions.

@tindex MYSQL_RES C type
@item MYSQL_RES
This structure represents the result of a query that returns rows
(@code{SELECT}, @code{SHOW}, @code{DESCRIBE}, @code{EXPLAIN}).  The
information returned from a query is called the @emph{result set} in the
remainder of this section.

@tindex MYSQL_ROW C type
@item MYSQL_ROW
This is a type-safe representation of one row of data. It is currently
implemented as an array of counted byte strings.  (You cannot treat these as
null-terminated strings if field values may contain binary data, because such
values may contain null bytes internally.)  Rows are obtained by calling
@code{mysql_fetch_row()}.

@tindex MYSQL_FIELD C type
@item MYSQL_FIELD
This structure contains information about a field, such as the field's
name, type and size. Its members are described in more detail below.
You may obtain the @code{MYSQL_FIELD} structures for each field by
calling @code{mysql_fetch_field()} repeatedly.  Field values are not part of
this structure; they are contained in a @code{MYSQL_ROW} structure.


@tindex MYSQL_FIELD_OFFSET C type
@item MYSQL_FIELD_OFFSET
This is a type-safe representation of an offset into a @strong{MySQL} field
list.  (Used by @code{mysql_field_seek()}.)  Offsets are field numbers
within a row, beginning at zero.

@tindex my_ulonglong C type
@tindex my_ulonglong values, printing
@item my_ulonglong
The type used for the number of rows and for @code{mysql_affected_rows()},
@code{mysql_num_rows()} and @code{mysql_insert_id()}. This type provides a
range of @code{0} to @code{1.84e19}.

On some systems, attempting to print a value of type @code{my_ulonglong}
will not work.  To print such a value, convert it to @code{unsigned long}
and use a @code{%lu} print format.  Example:
@example
printf (Number of rows: %lu\n", (unsigned long) mysql_num_rows(result));
@end example
@end table

@noindent
The @code{MYSQL_FIELD} structure contains the members listed below:

@table @code
@item char * name
The name of the field.

@item char * table
The name of the table containing this field, if it isn't a calculated field.
For calculated fields, the @code{table} value is a @code{NULL} pointer.

@item char * def
The default value of this field (set only if you use
@code{mysql_list_fields()}).

@item enum enum_field_types type
The type of the field.
The @code{type} value may be one of the following:

@multitable @columnfractions .3 .55
@item @strong{Type value}                @tab @strong{Type meaning}
@item @code{FIELD_TYPE_TINY}            @tab @code{TINYINT} field
@item @code{FIELD_TYPE_SHORT}           @tab @code{SMALLINT} field
@item @code{FIELD_TYPE_LONG}            @tab @code{INTEGER} field
@item @code{FIELD_TYPE_INT24}           @tab @code{MEDIUMINT} field
@item @code{FIELD_TYPE_LONGLONG}        @tab @code{BIGINT} field
@item @code{FIELD_TYPE_DECIMAL}         @tab @code{DECIMAL} or @code{NUMERIC} field
@item @code{FIELD_TYPE_FLOAT}           @tab @code{FLOAT} field
@item @code{FIELD_TYPE_DOUBLE}          @tab @code{DOUBLE} or @code{REAL} field
@item @code{FIELD_TYPE_TIMESTAMP}       @tab @code{TIMESTAMP} field
@item @code{FIELD_TYPE_DATE}            @tab @code{DATE} field
@item @code{FIELD_TYPE_TIME}            @tab @code{TIME} field
@item @code{FIELD_TYPE_DATETIME}        @tab @code{DATETIME} field
@item @code{FIELD_TYPE_YEAR}            @tab @code{YEAR} field
@item @code{FIELD_TYPE_STRING}          @tab String (@code{CHAR} or @code{VARCHAR}) field
@item @code{FIELD_TYPE_BLOB}            @tab @code{BLOB} or @code{TEXT} field (use @code{max_length} to determine the maximum length)
@item @code{FIELD_TYPE_SET}             @tab @code{SET} field
@item @code{FIELD_TYPE_ENUM}            @tab @code{ENUM} field
@item @code{FIELD_TYPE_NULL}            @tab @code{NULL}-type field
@item @code{FIELD_TYPE_CHAR}            @tab Deprecated: use @code{FIELD_TYPE_TINY} instead
@end multitable

You can use the @code{IS_NUM()} macro to test whether or not a field has a
numeric type.  Pass the @code{type} value to @code{IS_NUM()} and it
will evaluate to TRUE if the field is numeric:

@example
if (IS_NUM(field->type))
    printf("Field is numeric\n");
@end example

@item unsigned int length
The width of the field.

@item unsigned int max_length
The maximum width of the field for the result set. If you used
@code{mysql_list_fields()}, this contains the maximum length for the field.

@item unsigned int flags
Different bit-flags for the field.  The @code{flags} value may have zero
or more of the following bits set:

@multitable @columnfractions .3 .55
@item @strong{Flag value}         @tab @strong{Flag meaning}
@item @code{NOT_NULL_FLAG}       @tab Field can't be @code{NULL}
@item @code{PRI_KEY_FLAG}        @tab Field is part of a primary key
@item @code{UNIQUE_KEY_FLAG}     @tab Field is part of a unique key
@item @code{MULTIPLE_KEY_FLAG}   @tab Field is part of a key
@item @code{UNSIGNED_FLAG}       @tab Field has the @code{UNSIGNED} attribute
@item @code{ZEROFILL_FLAG}       @tab Field has the @code{ZEROFILL} attribute
@item @code{BINARY_FLAG}         @tab Field has the @code{BINARY} attribute
@item @code{AUTO_INCREMENT_FLAG} @tab Field has the @code{AUTO_INCREMENT} attribute
@item @code{ENUM_FLAG}           @tab Field is an @code{ENUM} (deprecated)
@item @code{BLOB_FLAG}           @tab Field is a @code{BLOB} or @code{TEXT} (deprecated)
@item @code{TIMESTAMP_FLAG}      @tab Field is a @code{TIMESTAMP} (deprecated)
@end multitable

Use of the @code{BLOB_FLAG}, @code{ENUM_FLAG} and @code{TIMESTAMP_FLAG} flags
is deprecated because they indicate the type of a field rather than an
attribute of its type.  It is preferable to test @code{field->type} against
@code{FIELD_TYPE_BLOB}, @code{FIELD_TYPE_ENUM} or @code{FIELD_TYPE_TIMESTAMP}
instead.

@noindent
The example below illustrates a typical use of the @code{flags} value:

@example
if (field->flags & NOT_NULL_FLAG)
    printf("Field can't be null\n");
@end example

You may use the following convenience macros to determine the boolean
status of the @code{flags} value:

@multitable @columnfractions .3 .5
@item @code{IS_NOT_NULL(flags)} @tab True if this field is defined as @code{NOT NULL}
@item @code{IS_PRI_KEY(flags)}  @tab True if this field is a primary key
@item @code{IS_BLOB(flags)}     @tab True if this field is a @code{BLOB} or @code{TEXT} (deprecated; test @code{field->type} instead)
@end multitable

@item unsigned int decimals
The number of decimals for numeric fields.
@end table

@node C API function overview, C API functions, C API datatypes, Clients
@section C API function overview

The functions available in the C API are listed below and are described in
greater detail in the next section.
@xref{C API functions}.

@multitable @columnfractions .3 .7
@item @strong{mysql_affected_rows()} @tab
Returns the number of rows affected by the last @code{UPDATE}, @code{DELETE} or
@code{INSERT} query.

@item @strong{mysql_close()} @tab
Closes a server connection.

@item @strong{mysql_connect()} @tab
Connects to a @strong{MySQL} server. This function is deprecated; use
@code{mysql_real_connect()} instead.

@item @strong{mysql_create_db()} @tab
Creates a database. This function is deprecated; use the SQL command
@code{CREATE DATABASE} instead.

@item @strong{mysql_data_seek()} @tab
Seeks to an arbitrary row in a query result set.

@item @strong{mysql_debug()} @tab
Does a @code{DBUG_PUSH} with the given string.

@item @strong{mysql_drop_db()} @tab
Drops a database. This function is deprecated; use the SQL command
@code{DROP DATABASE} instead.

@item @strong{mysql_dump_debug_info()} @tab
Makes the server write debug information to the log.

@item @strong{mysql_eof()} @tab
Determines whether or not the last row of a result set has been read.
This function is deprecated; @code{mysql_errno()} or @code{mysql_error()}
may be used instead.

@item @strong{mysql_errno()} @tab
Returns the error number for the most recently invoked @strong{MySQL} function.

@item @strong{mysql_error()} @tab
Returns the error message for the most recently invoked @strong{MySQL} function.

@item @strong{mysql_escape_string()} @tab
Escapes special characters in a string for use in a SQL statement.

@item @strong{mysql_fetch_field()} @tab
Returns the type of the next table field.

@item @strong{mysql_fetch_field_direct()} @tab
Returns the type of a table field, given a field number.

@item @strong{mysql_fetch_fields()} @tab
Returns an array of all field structures.

@item @strong{mysql_fetch_lengths()} @tab
Returns the lengths of all columns in the current row.

@item @strong{mysql_fetch_row()} @tab
Fetches the next row from the result set.

@item @strong{mysql_field_seek()} @tab
Puts the column cursor on a specified column.

@item @strong{mysql_field_tell()} @tab
Returns the position of the field cursor used for the last
@code{mysql_fetch_field()}.

@item @strong{mysql_free_result()} @tab
Frees memory used by a result set.

@item @strong{mysql_get_client_info()} @tab
Returns client version information.

@item @strong{mysql_get_host_info()} @tab
Returns a string describing the connection.

@item @strong{mysql_get_proto_info()} @tab
Returns the protocol version used by the connection.

@item @strong{mysql_get_server_info()} @tab
Returns the server version number.

@item @strong{mysql_info()} @tab
Returns information about the most recently executed query.

@item @strong{mysql_init()} @tab
Gets or initializes a @code{MYSQL} structure.

@item @strong{mysql_insert_id()} @tab
Returns the ID generated for an @code{AUTO_INCREMENT} column by the previous
query.

@item @strong{mysql_kill()} @tab
Kill a given thread.

@item @strong{mysql_list_dbs()} @tab
Returns database names matching a simple regular expression.

@item @strong{mysql_list_fields()} @tab
Returns field names matching a simple regular expression.

@item @strong{mysql_list_processes()} @tab
Returns a list of the current server threads.

@item @strong{mysql_list_tables()} @tab
Returns table names matching a simple regular expression.

@item @strong{mysql_num_fields()} @tab
Returns the number of columns in a result set.

@item @strong{mysql_num_rows()} @tab
Returns the number of rows in a result set.

@item @strong{mysql_options()} @tab
Set connect options for @code{mysql_connect()}.

@item @strong{mysql_ping()} @tab
Checks whether or not the connection to the server is working, reconnecting
as necessary.

@item @strong{mysql_query()} @tab
Executes a SQL query specified as a null-terminated string.

@item @strong{mysql_real_connect()} @tab
Connects to a @strong{MySQL} server.

@item @strong{mysql_real_query()} @tab
Executes a SQL query specified as a counted string.

@item @strong{mysql_reload()} @tab
Tells the server to reload the grant tables.

@item @strong{mysql_row_seek()} @tab
Seeks to a row in a result set, using value returned from
@code{mysql_row_tell()}.

@item @strong{mysql_row_tell()} @tab
Returns the row cursor position.

@item @strong{mysql_select_db()} @tab
Connects to a database.

@item @strong{mysql_shutdown()} @tab
Shuts down the database server.

@item @strong{mysql_stat()} @tab
Returns the server status as a string.

@item @strong{mysql_store_result()} @tab
Retrieves a complete result set to the client.

@item @strong{mysql_thread_id()} @tab
Returns the current thread ID.

@item @strong{mysql_use_result()} @tab
Initiates a row-by-row result set retrieval.
@end multitable

To connect to the server, call @code{mysql_init()} to initialize a connection
handler, then call @code{mysql_real_connect()} with that handler (along with
other information such as the hostname, user name and password).  When you
are done with the connection, call @code{mysql_close()} to terminate it.

While a connection is active, the client may send SQL queries to the server
using @code{mysql_query()} or @code{mysql_real_query()}.  The difference
between the two is that @code{mysql_query()} expects the query to be
specified as a null-terminated string whereas @code{mysql_real_query()}
expects a counted string.  If the string contains binary data (which may
include null bytes), you must use @code{mysql_real_query()}.

For each non-@code{SELECT} query (e.g., @code{INSERT}, @code{UPDATE},
@code{DELETE}), you can found out how many rows were affected (changed)
by calling @code{mysql_affected_rows()}.

For @code{SELECT} queries, you retrieve the selected rows as a result set.
(Note that some statements are @code{SELECT}-like in that they return rows.
These include @code{SHOW}, @code{DESCRIBE} and @code{EXPLAIN}.  They should
be treated the same way as @code{SELECT} statements.)

There are two ways for a client to process result sets.  One way is to
retrieve the entire result set all at once by calling
@code{mysql_store_result()}.  This function acquires from the server all the
rows returned by the query and stores them in the client.  The second way is
for the client to initiate a row-by-row result set retrieval by calling
@code{mysql_use_result()}.  This function initializes the retrieval, but does
not actually get any rows from the server.

In both cases, you access rows by calling @code{mysql_fetch_row()}.  With
@code{mysql_store_result()}, @code{mysql_fetch_row()} accesses rows that have
already been fetched from the server.  With @code{mysql_use_result()},
@code{mysql_fetch_row()} actually retrieves the row from the server.
Information about as the size of the data values in each row is available by
calling @code{mysql_fetch_lengths()}.

After you are done with a result set, call @code{mysql_free_result()}
to free the memory used for it.

The two retrieval mechanisms are complementary.  Client programs should
choose the approach that is most appropriate for their requirements.
In practice, clients tend to use @code{mysql_store_result()} more
commonly.

An advantage of @code{mysql_store_result()} is that since the rows have all
been fetched to the client, you not only can access rows sequentially, you
can move back and forth in the result set using @code{mysql_data_seek()} or
@code{mysql_row_seek()} to change the current row position within the result
set.  You can also find out how many rows there are by calling
@code{mysql_num_rows()}.  On the other hand, the memory requirements for
@code{mysql_store_result()} may be very high for large result sets and you
are more likely to encounter out-of-memory conditions.

An advantage of @code{mysql_use_result()} is that the client requires less
memory for the result set since it maintains only one row at a time (and
since there is less allocation overhead, @code{mysql_use_result()} can be
faster).  Disadvantages are that you must process each row quickly to avoid
tying up the server, you don't have random access to rows within the result
set (you can only access rows sequentially), and you don't know how many rows
are in the result set until you have retrieved them all.  Furthermore, you
@emph{must} retrieve all the rows even if you determine in mid-retrieval that
you've found the information you were looking for.

The API makes it possible for clients to respond appropriately to queries
(retrieving rows only as necessary) without knowing whether or not the query
is a @code{SELECT}.  You can do this by calling @code{mysql_store_result()}
after each @code{mysql_query()} (or @code{mysql_real_query()}).  If the
result set call succeeds, the query was a @code{SELECT} and you can read the
rows.  If the result set call fails, call @code{mysql_num_fields()} to
determine whether or not a result was actually to be expected.  If
@code{mysql_num_fields()} returns zero, the query returned no data
(indicating that it was an @code{INSERT}, @code{UPDATE}, @code{DELETE},
etc.), and thus not expected to return rows.  If @code{mysql_num_fields()} is
non-zero, the query should have returned rows, but didn't.  This indicates
that the query was a @code{SELECT} that failed.  See the description for
@code{mysql_num_fields()} for an example of how this can be done.

Both @code{mysql_store_result()} and @code{mysql_use_result()} allow you to
obtain information about the fields that make up the result set (the number
of fields, their names and types, etc.).  You can access field information
sequentially within the row by calling @code{mysql_fetch_field()} repeatedly,
or by field number within the row by calling
@code{mysql_fetch_field_direct()}.  The current field cursor position may be
changed by calling @code{mysql_field_seek()}.  Setting the field cursor
affects subsequent calls to @code{mysql_fetch_field()}.  You can also get
information for fields all at once by calling @code{mysql_fetch_fields()}.

For detecting and reporting errors, @strong{MySQL} provides access to error
information by means of the @code{mysql_errno()} and @code{mysql_error()}
functions.  These return the error code or error message for the most
recently invoked function that can succeed or fail, allowing you to determine
when an error occurred and what it was.

@node C API functions, Perl, C API function overview, Clients
@section C API function descriptions

@menu
* mysql_affected_rows::         @code{mysql_affected_rows()}
* mysql_close::                 @code{mysql_close()}
* mysql_connect::               @code{mysql_connect()}
* mysql_create_db::             @code{mysql_create_db()}
* mysql_data_seek::             @code{mysql_data_seek()}
* mysql_debug::                 @code{mysql_debug()}
* mysql_drop_db::               @code{mysql_drop_db()}
* mysql_dump_debug_info::       @code{mysql_dump_debug_info()}
* mysql_eof::                   @code{mysql_eof()}
* mysql_errno::                 @code{mysql_errno()}
* mysql_error::                 @code{mysql_error()}
* mysql_escape_string::         @code{mysql_escape_string()}
* mysql_fetch_field::           @code{mysql_fetch_field()}
* mysql_fetch_fields::          @code{mysql_fetch_fields()}
* mysql_fetch_field_direct::    @code{mysql_fetch_field_direct()}
* mysql_fetch_lengths::         @code{mysql_fetch_lengths()}
* mysql_fetch_row::             @code{mysql_fetch_row()}
* mysql_field_seek::            @code{mysql_field_seek()}
* mysql_field_tell::            @code{mysql_field_tell()}
* mysql_free_result::           @code{mysql_free_result()}
* mysql_get_client_info::       @code{mysql_get_client_info()}
* mysql_get_host_info::         @code{mysql_get_host_info()}
* mysql_get_proto_info::        @code{mysql_get_proto_info()}
* mysql_get_server_info::       @code{mysql_get_server_info()}
* mysql_info::                  @code{mysql_info()}
* mysql_init::                  @code{mysql_init()}
* mysql_insert_id::             @code{mysql_insert_id()}
* mysql_kill::                  @code{mysql_kill()}
* mysql_list_dbs::              @code{mysql_list_dbs()}
* mysql_list_fields::           @code{mysql_list_fields()}
* mysql_list_processes::        @code{mysql_list_processes()}
* mysql_list_tables::           @code{mysql_list_tables()}
* mysql_num_fields::            @code{mysql_num_fields()}
* mysql_num_rows::              @code{mysql_num_rows()}
* mysql_options::               @code{mysql_options()}
* mysql_ping::                  @code{mysql_ping()}
* mysql_query::                 @code{mysql_query()}
* mysql_real_connect::          @code{mysql_real_connect()}
* mysql_real_query::            @code{mysql_real_query()}
* mysql_reload::                @code{mysql_reload()}
* mysql_row_seek::              @code{mysql_row_seek()}
* mysql_row_tell::              @code{mysql_row_tell()}
* mysql_select_db::             @code{mysql_select_db()}
* mysql_shutdown::              @code{mysql_shutdown()}
* mysql_stat::                  @code{mysql_stat()}
* mysql_store_result::          @code{mysql_store_result()}
* mysql_thread_id::             @code{mysql_thread_id()}
* mysql_use_result::            @code{mysql_use_result()}
* NULL mysql_store_result::     Why is it that after @code{mysql_query()} returns success, @code{mysql_store_result()} sometimes returns @code{NULL?}
* Query results::               What results can I get from a query?
* Getting unique ID::           How can I get the unique ID for the last inserted row?
* C API linking problems::      Problems linking with the C API
* Thread-safe clients::         How to make a thread-safe client
@end menu

In the descriptions below, a parameter or return value of @code{NULL} means
@code{NULL} in the sense of the C programming language, not a
@strong{MySQL} @code{NULL} value.

Functions that return a value generally return a pointer or an integer.
Unless specified otherwise, functions returning a pointer return a
non-@code{NULL} value to indicate success or a @code{NULL} value to indicate
an error, and functions returning an integer return zero to indicate success
or non-zero to indicate an error.  Note that ``non-zero'' means just that.
Unless the function description says otherwise, do not test against a value
other than zero:

@example
if (result)                   /* correct */
    ... error ...

if (result < 0)               /* incorrect */
    ... error ...

if (result == -1)             /* incorrect */
    ... error ...
@end example

When a function returns an error, the @strong{Errors} subsection of the
function description lists the possible types of errors.  You can
find out which of these occurred by calling @code{mysql_errno()}.
A string representation of the error may be obtained by calling
@code{mysql_error()}.

@findex @code{mysql_affected_rows()}
@node mysql_affected_rows, mysql_close, C API functions, C API functions
@subsection @code{mysql_affected_rows()}

@code{my_ulonglong mysql_affected_rows(MYSQL *mysql)}

@subsubheading Description

Returns the number of rows affected (changed) by the last @code{UPDATE},
@code{DELETE} or @code{INSERT} query. May be called immediately after
@code{mysql_query()} for @code{UPDATE}, @code{DELETE} or @code{INSERT}
statements.  For @code{SELECT} statements, @code{mysql_affected_rows()}
works like @code{mysql_num_rows()}.

@code{mysql_affected_rows()} is currently implemented as a macro.

@subsubheading Return values

An integer greater than zero indicates the number of rows affected or
retrieved.  Zero indicates that no records matched the @code{WHERE} clause in
the query or that no query has yet been executed.  -1 indicates that the
query returned an error or that, for a @code{SELECT} query,
@code{mysql_affected_rows()} was called prior to calling
@code{mysql_store_result()}.

@subsubheading Errors

None.

@subsubheading Example

@example
mysql_query(&mysql,"UPDATE products SET cost=cost*1.25 WHERE group=10");
printf("%d products updated",mysql_affected_rows(&mysql));
@end example

@findex @code{mysql_close()}
@node mysql_close, mysql_connect, mysql_affected_rows, C API functions
@subsection @code{mysql_close()}

@code{void mysql_close(MYSQL *mysql)}

@subsubheading Description
Closes a previously opened connection.  @code{mysql_close()} also deallocates
the connection handle pointed to by @code{mysql} if the handle was allocated
automatically by @code{mysql_init()} or @code{mysql_real_connect()}.

@subsubheading Return values

None.

@subsubheading Errors

@table @code
@item CR_COMMANDS_OUT_OF_SYNC
Commands were executed in an improper order.

@item CR_SERVER_GONE_ERROR
The @strong{MySQL} server has gone away.

@item CR_SERVER_LOST
The connection to the server was lost during the query.

@item CR_UNKNOWN_ERROR
An unknown error occurred.
@end table

@findex @code{mysql_connect()}
@node mysql_connect, mysql_create_db, mysql_close, C API functions
@subsection @code{mysql_connect()}

@code{MYSQL *mysql_connect(MYSQL *mysql, const char *host, const char *user, const char *passwd)}

@subsubheading Description

This function is deprecated.  It is preferable to use
@code{mysql_real_connect()} instead.

@code{mysql_connect()} attempts to establish a connection to a @strong{MySQL}
database engine running on @code{host}.  @code{mysql_connect()} must complete
successfully before you can execute any of the other API functions, with the
exception of @code{mysql_get_client_info()}.

The meanings of the parameters are the same as for the corresponding
parameters for @code{mysql_real_connect()}.  See the description of that
function for more information.

@subsubheading Return values

Same as for @code{mysql_real_connect()}.

@subsubheading Errors

Same as for @code{mysql_real_connect()}.

@findex @code{mysql_create_db()}
@node mysql_create_db, mysql_data_seek, mysql_connect, C API functions
@subsection @code{mysql_create_db()}

@code{int mysql_create_db(MYSQL *mysql, const char *db)}

@subsubheading Description
Creates the database named by the @code{db} parameter.

This function is deprecated.  It is preferable to use @code{mysql_query()}
to issue a SQL @code{CREATE DATABASE} statement instead.

@subsubheading Return values

Zero if the database was created successfully. Non-zero if an error
occurred.

@subsubheading Errors
@table @code

@item CR_COMMANDS_OUT_OF_SYNC
Commands were executed in an improper order.

@item CR_SERVER_GONE_ERROR
The @strong{MySQL} server has gone away.

@item CR_SERVER_LOST
The connection to the server was lost during the query.

@item CR_UNKNOWN_ERROR
An unknown error occurred.
@end table

@subsubheading Example

@example
if(mysql_create_db(&mysql, "my_database"))
@{
   fprintf(stderr, "Failed to create new database.  Error: %s\n",
           mysql_error(&mysql));
@}
@end example

@findex @code{mysql_data_seek()}
@node mysql_data_seek, mysql_debug, mysql_create_db, C API functions
@subsection @code{mysql_data_seek()}

@code{void mysql_data_seek(MYSQL_RES *result, unsigned int offset)}

@subsubheading Description
Seeks to an arbitrary row in a query result set.  This requires that the
result set structure contains the entire result of the query, so
@code{mysql_data_seek()} may be used in conjunction only with
@code{mysql_store_result()}, not with @code{mysql_use_result()}.

The offset should be a value in the range from 0 to
@code{mysql_num_rows(result)-1}.

@subsubheading Return values

None.

@subsubheading Errors
None.

@findex @code{mysql_debug()}
@node mysql_debug, mysql_drop_db, mysql_data_seek, C API functions
@subsection @code{mysql_debug()}

@code{void mysql_debug(char *debug)}

@subsubheading Description
Does a @code{DBUG_PUSH} with the given string. @code{mysql_debug()} uses the
Fred Fish debug library. To use this function, you must compile the client
library to support debugging.
@xref{Debugging server}. @xref{Debugging client}.

@subsubheading Return values

None.

@subsubheading Errors
None.

@subsubheading Example

The call shown below causes the client library to generate a trace file in
@file{/tmp/client.trace} on the client machine:

@example
mysql_debug("d:t:O,/tmp/client.trace");
@end example

@findex @code{mysql_drop_db()}
@node mysql_drop_db, mysql_dump_debug_info, mysql_debug, C API functions
@subsection @code{mysql_drop_db()}

@code{int mysql_drop_db(MYSQL *mysql, const char *db)}

@subsubheading Description
Drops the database named by the @code{db} parameter.

This function is deprecated.  It is preferable to use @code{mysql_query()}
to issue a SQL @code{DROP DATABASE} statement instead.

@subsubheading Return values

Zero if the database was dropped successfully. Non-zero if an error
occurred.

@subsubheading Errors

@table @code
@item CR_COMMANDS_OUT_OF_SYNC
Commands were executed in an improper order.
@item CR_SERVER_GONE_ERROR
The @strong{MySQL} server has gone away.
@item CR_SERVER_LOST
The connection to the server was lost during the query.
@item CR_UNKNOWN_ERROR
An unknown error occurred.
@end table

@subsubheading Example

@example
if(mysql_drop_db(&mysql, "my_database"))
  fprintf(stderr, "Failed to drop the database: Error: %s\n",
          mysql_error(&mysql));
@end example

@findex @code{mysql_dump_debug_info()}
@node mysql_dump_debug_info, mysql_eof, mysql_drop_db, C API functions
@subsection @code{mysql_dump_debug_info()}

@code{int mysql_dump_debug_info(MYSQL *mysql)}

@subsubheading Description

Instructs the server to write some debug information to the log.  The
connected user must have the @strong{process} privilege for this to work.

@subsubheading Return values

Zero if the command was successful. Non-zero if an error occurred.

@subsubheading Errors
@table @code
@item CR_COMMANDS_OUT_OF_SYNC
Commands were executed in an improper order.
@item CR_SERVER_GONE_ERROR
The @strong{MySQL} server has gone away.
@item CR_SERVER_LOST
The connection to the server was lost during the query.
@item CR_UNKNOWN_ERROR
An unknown error occurred.
@end table

@findex @code{mysql_eof()}
@node mysql_eof, mysql_errno, mysql_dump_debug_info, C API functions
@subsection @code{mysql_eof()}

@code{my_bool mysql_eof(MYSQL_RES *result)}

@subsubheading Description

This function is deprecated.  @code{mysql_errno()} or @code{mysql_error()}
may be used instead.

@code{mysql_eof()} determines whether or not the last row of a result
set has been read.

If you acquire a result set from a successful call to
@code{mysql_store_result()}, the client receives the entire set in one
operation.  In this case, a @code{NULL} return from @code{mysql_fetch_row()}
always means the end of the result set has been reached and it is
unnecessary to call @code{mysql_eof()}.

On the other hand, if you use @code{mysql_use_result()} to initiate a result
set retrieval, the rows of the set are obtained from the server one by one as
you call @code{mysql_fetch_row()} repeatedly.  Because an error may occur on
the connection during this process, a @code{NULL} return value from
@code{mysql_fetch_row()} does not necessarily mean the end of the result set
was reached normally.  In this case, you can use @code{mysql_eof()} to
determine what happened.  @code{mysql_eof()} returns a non-zero value if the
end of the result set was reached and zero if an error occurred.

Historically, @code{mysql_eof()} predates the standard @strong{MySQL} error
functions @code{mysql_errno()} and @code{mysql_error()}.  Since those error
functions provide the same information, their use is preferred over
@code{mysql_eof()}, which is now deprecated.  (In fact, they provide more
information, since @code{mysql_eof()} returns only a boolean value whereas
the error functions indicate a reason for the error when one occurs.)

@subsubheading Return values

Zero if an error occurred. Non-zero if the end of the result set has been
reached.

@subsubheading Errors
None.

@subsubheading Example

The following example shows how you might use @code{mysql_eof()}:

@example
mysql_query(&mysql,"SELECT * FROM some_table");
result = mysql_use_result(&mysql);
while((row = mysql_fetch_row(result)))
@{
    // do something with data
@}
if(!mysql_eof(result))  // mysql_fetch_row() failed due to an error
@{
    fprintf(stderr, "Error: %s\n", mysql_error(&mysql));
@}
@end example

However, you can achieve the same effect with the standard @strong{MySQL}
error functions:

@example
mysql_query(&mysql,"SELECT * FROM some_table");
result = mysql_use_result(&mysql);
while((row = mysql_fetch_row(result)))
@{
    // do something with data
@}
if(mysql_errno(&mysql))  // mysql_fetch_row() failed due to an error
@{
    fprintf(stderr, "Error: %s\n", mysql_error(&mysql));
@}
@end example

@findex @code{mysql_errno()}
@node mysql_errno, mysql_error, mysql_eof, C API functions
@subsection @code{mysql_errno()}

@code{unsigned int mysql_errno(MYSQL *mysql)}

@subsubheading Description

For the connection specified by @code{mysql}, @code{mysql_errno()} returns
the error code for the most recently invoked API function that can succeed
or fail.  A return value of zero means that no error occurred. Client error
message numbers are listed in the @strong{MySQL} @file{errmsg.h} header file.
Server error message numbers are listed in @file{mysqld_error.h}

@subsubheading Return values:

An error code value. Zero if no error occurred.

@subsubheading Errors
None.

@findex @code{mysql_error()}
@node mysql_error, mysql_escape_string, mysql_errno, C API functions
@subsection @code{mysql_error()}

@code{char *mysql_error(MYSQL *mysql)}

@subsubheading Description

For the connection specified by @code{mysql}, @code{mysql_error()} returns
the error message for the most recently invoked API function that can succeed
or fail.  An empty string (@code{""}) is returned if no error occurred.
This means the following two tests are equivalent:

@example
if(mysql_errno(&mysql))
@{
    // an error occurred
@}

if(mysql_error(&mysql)[0] != '\0')
@{
    // an error occurred
@}
@end example

The language of the client error messages may be changed by
recompiling the @strong{MySQL} client library. Currently you can choose
error messages in several different languages.
@xref{Languages}.

@subsubheading Return values

A character string that describes the error.  An empty string if no error
occurred.

@subsubheading Errors
None.

@findex @code{mysql_escape_string()}
@node mysql_escape_string, mysql_fetch_field, mysql_error, C API functions
@subsection @code{mysql_escape_string()}

@code{unsigned int mysql_escape_string(char *to, const char *from, unsigned int length)}

@subsubheading Description

Encodes the string in @code{from} to an escaped SQL string that can be sent
to the server in a SQL statement, and places the result in @code{to}.
Characters encoded are @code{NUL} (ASCII 0), @samp{\n}, @samp{\r}, @samp{\}
and @samp{'} (@pxref{Literals}).

The string pointed to by @code{from} must be @code{length} bytes long (not
including the terminating null byte). You must allocate the @code{to} buffer
to be at least @code{length*2+1} bytes long. When
@code{mysql_escape_string()} returns, the contents of @code{to} will be a
null-terminated string.  The return value is the length of the encoded
string, not including the terminating null character.

Although the string written into @code{to} is null-terminated, you should not
assume that it can be used with functions such as @code{strlen()} or
@code{strcpy()}.  If the @code{from} string contains null bytes,
@code{mysql_escape_string()} will escape them with a leading @samp{\}
character in the @code{to} string, but they will still appear to those
functions as terminating nulls.

Such internal null bytes will also be seen as terminating nulls by
@code{mysql_query()} and it will not handle the query properly.  Therefore,
when you construct a query using @code{mysql_escape_string()}, you should
send the query to the server using @code{mysql_real_query()} rather than with
@code{mysql_query()}.


@subsubheading Example

@example
char query[1000],*end;

end = strmov(query,"INSERT INTO test_table values(");
*end++ = '\'';
end += mysql_escape_string(query,"What's this",11);
*end++ = '\'';
*end++ = ',';
*end++ = '\'';
end += mysql_escape_string(query,"binary data: \0\r\n",16);
*end++ = '\'';
*end++ = ')';

if (mysql_real_query(&mysql,query,(unsigned int) (end - query)))
@{
   fprintf(stderr, "Failed to insert row, Error: %s\n",
           mysql_error(&mysql));
@}
@end example

The @code{strmov()} function used in the example is included in the
@code{mysqlclient} library and works like @code{strcpy()} but returns a
pointer to the terminating null of the first parameter.

@subsubheading Return values

The length of the value placed into @code{to}, not including the
terminating null character.

@subsubheading Errors
None.

@findex @code{mysql_fetch_field()}
@node mysql_fetch_field, mysql_fetch_fields, mysql_escape_string, C API functions
@subsection @code{mysql_fetch_field()}

@code{MYSQL_FIELD *mysql_fetch_field(MYSQL_RES *result)}

@subsubheading Description

Returns the definition of one column of a result set as a @code{MYSQL_FIELD}
structure. Call this function repeatedly to retrieve information about all
columns in the result set.  @code{mysql_fetch_field()} returns @code{NULL}
when no more fields are left.

@code{mysql_fetch_field()} is reset to return information about the first
field each time you execute a new @code{SELECT} query.  The field returned by
@code{mysql_fetch_field()} is also affected by calls to
@code{mysql_field_seek()}.

If you've called @code{mysql_query()} to perform a @code{SELECT} on a table
but have not called @code{mysql_store_result()}, @strong{MySQL} returns the
default blob length (8K bytes) if you call @code{mysql_fetch_field()} to ask
for the length of a @code{BLOB} field.  (The 8K size is chosen because
@strong{MySQL} doesn't know the maximum length for the @code{BLOB}. This
should be made configurable sometime.) Once you've retrieved the result set,
@code{field->max_length} contains the length of the largest value for this
column in the specific query.

@subsubheading Return values

The @code{MYSQL_FIELD} structure for the current column. @code{NULL}
if no columns are left.

@subsubheading Errors
None.

@subsubheading Example

@example
MYSQL_FIELD *field;

while((field = mysql_fetch_field(result)))
@{
    printf("field name %s\n", field->name);
@}
@end example

@findex @code{mysql_fetch_fields()}
@node mysql_fetch_fields, mysql_fetch_field_direct, mysql_fetch_field, C API functions
@subsection @code{mysql_fetch_fields()}

@code{MYSQL_FIELD *mysql_fetch_fields(MYSQL_RES *result)}

@subsubheading Description

Returns an array of all @code{MYSQL_FIELD} structures for a result set.
Each structure provides the field definition for one column of the result
set.

@subsubheading Return values

An array of @code{MYSQL_FIELD} structures for all columns of a result set.

@subsubheading Errors
None.

@subsubheading Example

@example
unsigned int num_fields;
unsigned int i;
MYSQL_FIELD *fields;

num_fields = mysql_num_fields(result);
fields = mysql_fetch_fields(result);
for(i = 0; i < num_fields; i++)
@{
   printf("Field %u is %s\n", i, fields[i].name);
@}
@end example

@findex @code{mysql_fetch_field_direct()}
@node mysql_fetch_field_direct, mysql_fetch_lengths, mysql_fetch_fields, C API functions
@subsection @code{mysql_fetch_field_direct()}

@code{MYSQL_FIELD *mysql_fetch_field_direct(MYSQL_RES *result, unsigned int fieldnr)}

@subsubheading Description

Given a field number @code{fieldnr} for a column within a result set, returns
that column's field definition as a @code{MYSQL_FIELD} structure. You may use
this function to retrieve the definition for an arbitrary column.  The value
of @code{fieldnr} should be in the range from 0 to
@code{mysql_num_fields(result)-1}.

@subsubheading Return values

The @code{MYSQL_FIELD} structure for the specified column.

@subsubheading Errors
None.

@subsubheading Example

@example
unsigned int num_fields;
unsigned int i;
MYSQL_FIELD *field;

num_fields = mysql_num_fields(result);
for(i = 0; i < num_fields; i++)
@{
    field = mysql_fetch_field_direct(result, i);
    printf("Field %u is %s\n", i, field->name);
@}
@end example

@findex @code{mysql_fetch_lengths()}
@node mysql_fetch_lengths, mysql_fetch_row, mysql_fetch_field_direct, C API functions
@subsection @code{mysql_fetch_lengths()}

@code{unsigned long *mysql_fetch_lengths(MYSQL_RES *result)}

@subsubheading Description

Returns the lengths of the columns of the current row within a result set.
If you plan to copy field values, this length information is also useful for
optimization, because you can avoid calling @code{strlen()}.  In addition, if
the result set contains binary data, you @emph{must} use this function to
determine the size of the data, because @code{strlen()} returns incorrect
results for any field containing null characters.

The length for empty columns and for columns containing @code{NULL} values is
zero.  To see how to distinguish these two cases, see the description for
@code{mysql_fetch_row()}.

@subsubheading Return values

An array of unsigned long integers representing the size of each column (not
including any terminating null characters).
@code{NULL} if an error occurred.

@subsubheading Errors
@code{mysql_fetch_lengths()} is valid only for the current row of the result
set.  It returns @code{NULL} if you call it before calling
@code{mysql_fetch_row()} or after retrieving all rows in the result.

@subsubheading Example

@example
MYSQL_ROW row;
unsigned long *lengths;
unsigned int num_fields;
unsigned int i;

row = mysql_fetch_row(result);
if (row)
@{
    num_fields = mysql_num_fields(result);
    lengths = mysql_fetch_lengths(result);
    for(i = 0; i < num_fields; i++)
    @{
         printf("Column %u is %lu bytes in length.\n", i, lengths[i]);
    @}
@}
@end example

@findex @code{mysql_fetch_row()}
@node mysql_fetch_row, mysql_field_seek, mysql_fetch_lengths, C API functions
@subsection @code{mysql_fetch_row()}

@code{MYSQL_ROW mysql_fetch_row(MYSQL_RES *result)}

@subsubheading Description

Retrieves the next row of a result set. When used after
@code{mysql_store_result()}, @code{mysql_fetch_row()} returns @code{NULL}
when there are no more rows to retrieve.  When used after
@code{mysql_use_result()}, @code{mysql_fetch_row()} returns @code{NULL} when
there are no more rows to retrieve or if an error occurred.

The number of values in the row is given by @code{mysql_num_fields(result)}.
If @code{row} holds the return value from a call to @code{mysql_fetch_row()},
pointers to the values are accessed as @code{row[0]} to
@code{row[mysql_num_fields(result)-1]}.  @code{NULL} values in the row are
indicated by @code{NULL} pointers.

The lengths of the field values in the row may be obtained by calling
@code{mysql_fetch_lengths()}.  Empty fields and fields containing
@code{NULL} both have length 0; you can distinguish these by checking
the pointer for the field value.  If the pointer is @code{NULL}, the field
is @code{NULL}; otherwise the field is empty.

@subsubheading Return values

A @code{MYSQL_ROW} structure for the next row.  @code{NULL} if
there are no more rows to retrieve or if an error occurred.

@subsubheading Errors

@table @code
@item CR_SERVER_LOST
The connection to the server was lost during the query.
@item CR_UNKNOWN_ERROR
An unknown error occurred.
@end table

@subsubheading Example

@example
MYSQL_ROW row;
unsigned int num_fields;
unsigned int i;

num_fields = mysql_num_fields(result);
while ((row = mysql_fetch_row(result)))
@{
   unsigned long *lengths;
   lengths = mysql_fetch_lengths(result);
   for(i = 0; i < num_fields; i++)
   @{
       printf("[%.*s] ", (int) lengths[i], row[i] ? row[i] : "NULL");
   @}
   printf("\n");
@}
@end example

@findex @code{mysql_field_seek()}
@node mysql_field_seek, mysql_field_tell, mysql_fetch_row, C API functions
@subsection @code{mysql_field_seek()}

@code{MYSQL_FIELD_OFFSET mysql_field_seek(MYSQL_RES *result, MYSQL_FIELD_OFFSET offset)}

@subsubheading Description

Sets the field cursor to the given offset.   The next call to
@code{mysql_fetch_field()} will retrieve the field definition of the column
associated with that offset.

To seek to the beginning of a row, pass an @code{offset} value of zero.

@subsubheading Return values

The previous value of the field cursor.

@subsubheading Errors
None.

@findex @code{mysql_field_tell()}
@node mysql_field_tell, mysql_free_result, mysql_field_seek, C API functions
@subsection @code{mysql_field_tell()}

@code{MYSQL_FIELD_OFFSET mysql_field_tell(MYSQL_RES *result)}

@subsubheading Description

Returns the position of the field cursor used for the last
@code{mysql_fetch_field()}. This value can be used as an argument to
@code{mysql_field_seek()}.

@subsubheading Return values

The current offset of the field cursor.

@subsubheading Errors
None.

@findex @code{mysql_free_result()}
@node mysql_free_result, mysql_get_client_info, mysql_field_tell, C API functions
@subsection @code{mysql_free_result()}

@code{void mysql_free_result(MYSQL_RES *result)}

@subsubheading Description

Frees the memory allocated for a result set by @code{mysql_store_result()},
@code{mysql_use_result()}, @code{mysql_list_dbs()}, etc.  When you are done
with a result set, you must free the memory it uses by calling
@code{mysql_free_result()}.

@subsubheading Return values

None.

@subsubheading Errors
None.

@findex @code{mysql_get_client_info()}
@node mysql_get_client_info, mysql_get_host_info, mysql_free_result, C API functions
@subsection @code{mysql_get_client_info()}

@code{char *mysql_get_client_info(void)}

@subsubheading Description

Returns a string that represents the client library version.

@subsubheading Return values

A character string that represents the @strong{MySQL} client library version.

@subsubheading Errors
None.

@findex @code{mysql_get_host_info()}
@node mysql_get_host_info, mysql_get_proto_info, mysql_get_client_info, C API functions
@subsection @code{mysql_get_host_info()}

@code{char *mysql_get_host_info(MYSQL *mysql)}

@subsubheading Description

Returns a string describing the type of connection in use, including the
server host name.

@subsubheading Return values

A character string representing the server host name and the connection type.

@subsubheading Errors
None.

@findex @code{mysql_get_proto_info()}
@node mysql_get_proto_info, mysql_get_server_info, mysql_get_host_info, C API functions
@subsection @code{mysql_get_proto_info()}

@code{unsigned int mysql_get_proto_info(MYSQL *mysql)}

@subsubheading Description

Returns the protocol version used by current connection.

@subsubheading Return values

An unsigned integer representing the protocol version used by the current
connection.

@subsubheading Errors
None.

@findex @code{mysql_get_server_info()}
@node mysql_get_server_info, mysql_info, mysql_get_proto_info, C API functions
@subsection @code{mysql_get_server_info()}

@code{char *mysql_get_server_info(MYSQL *mysql)}

@subsubheading Description

Returns a string that represents the server version number.

@subsubheading Return values

A character string that represents the server version number.

@subsubheading Errors
None.

@findex @code{mysql_info()}
@node mysql_info, mysql_init, mysql_get_server_info, C API functions
@subsection @code{mysql_info()}

@code{char *mysql_info(MYSQL *mysql)}

@subsubheading Description

Retrieves a string providing information about the most recently executed
query, but only for the statements listed below.  For other statements,
@code{mysql_info()} returns @code{NULL}.  The format of the string varies
depending on the type of query, as described below.  The numbers are
illustrative only; the string will contain values appropriate for the query.

@table @code
@item INSERT INTO ... SELECT ...
String format: @code{Records: 100 Duplicates: 0 Warnings: 0}
@item INSERT INTO ... VALUES (...),(...),(...)...
String format: @code{Records: 3  Duplicates: 0  Warnings: 0}
@item LOAD DATA INFILE ...
String format: @code{Records: 1 Deleted: 0 Skipped: 0 Warnings: 0}
@item ALTER TABLE
String format: @code{Records: 3 Duplicates: 0 Warnings: 0}
@end table

Note that @code{mysql_info()} returns a non-@code{NULL} value for the
@code{INSERT ... VALUES} statement only if multiple value lists are
specified in the statement.

@subsubheading Return values

A character string representing additional information about the most
recently executed query.  @code{NULL} if no information is available for the
query.

@subsubheading Errors
None.

@findex @code{mysql_init()}
@node mysql_init, mysql_insert_id, mysql_info, C API functions
@subsection @code{mysql_init()}

@code{MYSQL *mysql_init(MYSQL *mysql)}

@subsubheading Description

Allocates or initializes a @code{MYSQL} object suitable for
@code{mysql_real_connect()}.  If @code{mysql} is a @code{NULL} pointer, the
function allocates, initializes and returns a new object.  Otherwise the
object is initialized and the address of the object is returned.  If
@code{mysql_init()} allocates a new object, it will be freed when
@code{mysql_close()} is called to close the connection.

@subsubheading Return values

An initialized @code{MYSQL*} handle.  @code{NULL} if there was
insufficient memory to allocate a new object.

@subsubheading Errors
In case of insufficient memory, @code{NULL} is returned.

@findex @code{mysql_insert_id()}
@node mysql_insert_id, mysql_kill, mysql_init, C API functions
@subsection @code{mysql_insert_id()}

@code{my_ulonglong mysql_insert_id(MYSQL *mysql)}

@subsubheading Description

Returns the ID generated for an @code{AUTO_INCREMENT} column by the previous
query.  Use this function after you have performed an @code{INSERT} query
into a table that contains an @code{AUTO_INCREMENT} field.

Note that @code{mysql_insert_id()} returns @code{0} if the previous query
does not generate an @code{AUTO_INCREMENT} value.  If you need to save
the value for later, be sure to call @code{mysql_insert_id()} immediately
after the query that generates the value.

Also note that the value of the SQL @code{LAST_INSERT_ID()} function always
contains the most recently generated @code{AUTO_INCREMENT} value, and is
not reset between queries since the value of that function is maintained
in the server.

@subsubheading Return values

The value of the @code{AUTO_INCREMENT} field that was updated by the previous
query.  Returns zero if there was no previous query on the connection or if
the query did not update an @code{AUTO_INCREMENT} value.

@subsubheading Errors
None.

@findex @code{mysql_kill()}
@node mysql_kill, mysql_list_dbs, mysql_insert_id, C API functions
@subsection @code{mysql_kill()}

@code{int mysql_kill(MYSQL *mysql, unsigned long pid)}

@subsubheading Description

Asks the server to kill the thread specified by @code{pid}.

@subsubheading Return values

Zero for success.  Non-zero if an error occurred.

@subsubheading Errors

@table @code
@item CR_COMMANDS_OUT_OF_SYNC
Commands were executed in an improper order.
@item CR_SERVER_GONE_ERROR
The @strong{MySQL} server has gone away.
@item CR_SERVER_LOST
The connection to the server was lost during the query.
@item CR_UNKNOWN_ERROR
An unknown error occurred.
@end table

@findex @code{mysql_list_dbs()}
@node mysql_list_dbs, mysql_list_fields, mysql_kill, C API functions
@subsection @code{mysql_list_dbs()}

@code{MYSQL_RES *mysql_list_dbs(MYSQL *mysql, const char *wild)}

@subsubheading Description

Returns a result set consisting of database names on the server that match
the simple regular expression specified by the @code{wild} parameter.
@code{wild} may contain the wildcard characters @samp{%} or @samp{_}, or may
be a @code{NULL} pointer to match all databases.  Calling
@code{mysql_list_dbs()} is similar to executing the query @code{SHOW
databases [LIKE wild]}.

You must free the result set with @code{mysql_free_result()}.

@subsubheading Return values

A @code{MYSQL_RES} result set for success.  @code{NULL} if an error occurred.

@subsubheading Errors

@table @code
@item CR_COMMANDS_OUT_OF_SYNC
Commands were executed in an improper order.
@item CR_OUT_OF_MEMORY
Out of memory.
@item CR_SERVER_GONE_ERROR
The @strong{MySQL} server has gone away.
@item CR_SERVER_LOST
The connection to the server was lost during the query.
@item CR_UNKNOWN_ERROR
An unknown error occurred.
@end table

@findex @code{mysql_list_fields()}
@node mysql_list_fields, mysql_list_processes, mysql_list_dbs, C API functions
@subsection @code{mysql_list_fields()}

@code{MYSQL_RES *mysql_list_fields(MYSQL *mysql, const char *table, const char *wild)}

@subsubheading Description

Returns a result set consisting of field names in the given table that match
the simple regular expression specified by the @code{wild} parameter.
@code{wild} may contain the wildcard characters @samp{%} or @samp{_}, or may
be a @code{NULL} pointer to match all fields.  Calling
@code{mysql_list_fields()} is similar to executing the query @code{SHOW
COLUMNS FROM tbl_name [LIKE wild]}.

Note that it's recommended that you use @code{SHOW COLUMNS FROM tbl_name}
instead of @code{mysql_list_fields()}.

You must free the result set with @code{mysql_free_result()}.

@subsubheading Return values

A @code{MYSQL_RES} result set for success.  @code{NULL} if an error occurred.

@subsubheading Errors

@table @code
@item CR_COMMANDS_OUT_OF_SYNC
Commands were executed in an improper order.
@item CR_SERVER_GONE_ERROR
The @strong{MySQL} server has gone away.
@item CR_SERVER_LOST
The connection to the server was lost during the query.
@item CR_UNKNOWN_ERROR
An unknown error occurred.
@end table

@findex @code{mysql_list_processes()}
@node mysql_list_processes, mysql_list_tables, mysql_list_fields, C API functions
@subsection @code{mysql_list_processes()}

@code{MYSQL_RES *mysql_list_processes(MYSQL *mysql)}

@subsubheading Description

Returns a result set describing the current server threads.  This is the same
kind of information as that reported by @code{mysqladmin processlist}.

You must free the result set with @code{mysql_free_result()}.

@subsubheading Return values

A @code{MYSQL_RES} result set for success.  @code{NULL} if an error occurred.

@subsubheading Errors

@table @code
@item CR_COMMANDS_OUT_OF_SYNC
Commands were executed in an improper order.
@item CR_SERVER_GONE_ERROR
The @strong{MySQL} server has gone away.
@item CR_SERVER_LOST
The connection to the server was lost during the query.
@item CR_UNKNOWN_ERROR
An unknown error occurred.
@end table

@findex @code{mysql_list_tables()}
@node mysql_list_tables, mysql_num_fields, mysql_list_processes, C API functions
@subsection @code{mysql_list_tables()}

@code{MYSQL_RES *mysql_list_tables(MYSQL *mysql, const char *wild)}

@subsubheading Description

Returns a result set consisting of table names in the current database that
match the simple regular expression specified by the @code{wild} parameter.
@code{wild} may contain the wildcard characters @samp{%} or @samp{_}, or may
be a @code{NULL} pointer to match all tables.  Calling
@code{mysql_list_tables()} is similar to executing the query @code{SHOW
tables [LIKE wild]}.

You must free the result set with @code{mysql_free_result()}.

@subsubheading Return values

A @code{MYSQL_RES} result set for success.  @code{NULL} if an error occurred.

@subsubheading Errors

@table @code
@item CR_COMMANDS_OUT_OF_SYNC
Commands were executed in an improper order.
@item CR_SERVER_GONE_ERROR
The @strong{MySQL} server has gone away.
@item CR_SERVER_LOST
The connection to the server was lost during the query.
@item CR_UNKNOWN_ERROR
An unknown error occurred.
@end table

@findex @code{mysql_num_fields()}
@node mysql_num_fields, mysql_num_rows, mysql_list_tables, C API functions
@subsection @code{mysql_num_fields()}

@code{unsigned int mysql_num_fields(MYSQL_RES *result)}

or

@code{unsigned int mysql_num_fields(MYSQL *mysql)}

@subsubheading Description

Returns the number of columns in a result set.

Note that you can call @code{mysql_num_fields()} with either a pointer to a
result set or to a connection handle.  You would use the connection handle if
@code{mysql_store_result()} returned @code{NULL} (and thus you have no result
set pointer).  In this case, you can call @code{mysql_num_fields()} to
determine whether or not @code{mysql_store_result()} should have produced a
non-empty result.  This allows the client program to take proper action
without knowing whether or not the query was a @code{SELECT} (or
@code{SELECT}-like) statement.  The example shown below illustrates how this
may be done.

@xref{NULL mysql_store_result, , @code{NULL mysql_store_result()}}.

@subsubheading Return values

An unsigned integer representing the number of fields in a result set.

@subsubheading Errors
None.

@subsubheading Example

@example
MYSQL_RES *result;
unsigned int num_fields;
unsigned int num_rows;

if (mysql_query(&mysql,query_string))
@{
    // error
@}
else // query succeeded, process any data returned by it
@{
    result = mysql_store_result(&mysql);
    if (result)  // there are rows
    @{
        num_fields = mysql_num_fields(result);
        // retrieve rows, then call mysql_free_result(result)
    @}
    else  // mysql_store_result() returned nothing; should it have?
    @{
        if(mysql_num_fields(&mysql) == 0)
        @{
            // query does not return data
            // (it was not a SELECT)
            num_rows = mysql_affected_rows(&mysql);
        @}
        else // mysql_store_result() should have returned data
        @{
            fprintf(stderr, "Error: %s\n", mysql_error(&mysql));
        @}
    @}
@}
@end example

An alternative is to replace the @code{mysql_num_fields(&mysql)} call with
@code{mysql_errno(&mysql)}.  In this case, you are checking directly for an
error from @code{mysql_store_result()} rather than inferring from the value
of @code{mysql_num_fields()} whether or not the statement was a
@code{SELECT}.

@findex @code{mysql_num_rows()}
@node mysql_num_rows, mysql_options, mysql_num_fields, C API functions
@subsection @code{mysql_num_rows()}

@code{my_ulonglong mysql_num_rows(MYSQL_RES *result)}

@subsubheading Description

Returns the number of rows in the result set.

The use of @code{mysql_num_rows()} depends on whether you use
@code{mysql_store_result()} or @code{mysql_use_result()} to return the result
set.  If you use @code{mysql_store_result()}, @code{mysql_num_rows()} may be
called immediately.  If you use @code{mysql_use_result()},
@code{mysql_num_rows()} will not return the correct value until all the rows
in the result set have been retrieved.

@subsubheading Return values

The number of rows in the result set.

@subsubheading Errors
None.

@findex @code{mysql_options()}
@node mysql_options, mysql_ping, mysql_num_rows, C API functions
@subsection @code{mysql_options()}

@code{int mysql_options(MYSQL *mysql, enum mysql_option option, const char *arg)}

@subsubheading Description

Can be used to set extra connect options and affect behavior for a connection.

Should be called after @code{mysql_init()} and before
@code{mysql_connect()} or @code{mysql_real_connect()}.

The @code{option} argument is the option that you want to set;  The @code{arg}
argument is the value for the option. If the option is an integer, then
@code{arg} should point to the value of the integer.

Possible options values:

@multitable @columnfractions .25 .25 .5
@item @strong{Option} @tab @strong{Argument type} @tab @strong{Function}
@item @code{MYSQL_OPT_CONNECT_TIMEOUT} @tab unsigned int * @tab Connect timeout in seconds.
@item @code{MYSQL_OPT_COMPRESS} @tab Not used @tab Use the compressed client/server protocol.
@item @code{MYSQL_OPT_NAMED_PIPE} @tab Not used @tab Use named pipes to connect to a @strong{MySQL} server on NT.
@item @code{MYSQL_INIT_COMMAND} @tab char * @tab Command to execute when connecting to @strong{MySQL} server. Will automatically be re-executed when reconnecting.
@item @code{MYSQL_READ_DEFAULT_FILE} @tab char * @tab Read options from the named option file instead of from @file{my.cnf}.
@item @code{MYSQL_READ_DEFAULT_GROUP} @tab char * @tab Read options from the named group from @file{my.cnf}.or the file specified with @code{MYSQL_READ_DEFAULT_FILE}.
@end multitable

Note that the group @code{client} is always read if you use
@code{MYSQL_READ_DEFAULT_FILE} or @code{MYSQL_READ_DEFAULT_GROUP}.

The specified group in the option file may contain the following options:

@multitable @columnfractions .3 .7
@item compress @tab Use the compressed client/server protocol.
@item database @tab Connect to this database if there was no database in the connect command
@item debug @tab Debug options
@item host @tab Default host name
@item init-command @tab Command to execute when connecting to @strong{MySQL} server. Will automatically be re-executed when reconnecting.
@item password @tab Default password
@item pipe @tab Use named pipes to connect to a @strong{MySQL} server on NT.
@item port @tab Default port number
@item return-found-rows @tab Tell @code{mysql_info()} to return found rows instead of updated rows when using @code{UPDATE}. 
@item socket @tab Default socket number
@item timeout @tab Connect timeout in seconds.
@item user @tab Default user
@end multitable

For more information about option files, see @ref{Option files}.

@subsubheading Return values

Zero for success.  Non-zero if you used an unknown option.

@subsubheading Example

@example
MYSQL mysql;

mysql_init(&mysql);
mysql_options(&mysql,MYSQL_OPT_COMPRESS,0);
mysql_options(&mysql,MYSQL_READ_DEFAULT_GROUP,"odbc");
if (!mysql_real_connect(&mysql,"host","user","passwd","database",0,NULL,0))
@{
    fprintf(stderr, "Failed to connect to database: Error: %s\n",
          mysql_error(&mysql));
@}
@end example

The above requests the client to use the compressed client/server protocol and
read the additional options from the @code{odbc} section in the @code{my.cnf}
file.

@findex @code{mysql_ping()}
@node mysql_ping, mysql_query, mysql_options, C API functions
@subsection @code{mysql_ping()}

@code{int mysql_ping(MYSQL *mysql)}

@subsubheading Description

Checks whether or not the connection to the server is working. If it has gone
down, an automatic reconnection is attempted.

This function can be used by clients that remain idle for a long while,
to check whether or not the server has closed the connection and reconnect
if necessary.

@subsubheading Return values

Zero if the server is alive. Non-zero if an error occurred.

@subsubheading Errors

@table @code
@item CR_COMMANDS_OUT_OF_SYNC
Commands were executed in an improper order.
@item CR_SERVER_GONE_ERROR
The @strong{MySQL} server has gone away.
@item CR_UNKNOWN_ERROR
An unknown error occurred.
@end table

@findex @code{mysql_query()}
@node mysql_query, mysql_real_connect, mysql_ping, C API functions
@subsection @code{mysql_query()}

@code{int mysql_query(MYSQL *mysql, const char *query)}

@subsubheading Description
Executes the SQL query pointed to by the null-terminated string @code{query}.
The query must consist of a single SQL statement.  You should not add
a terminating semicolon (@samp{;}) or @code{\g} to the statement.

@code{mysql_query()} cannot be used for queries that contain binary data; you
should use @code{mysql_real_query()} instead.  (Binary data may contain the
@samp{\0} character, which @code{mysql_query()} interprets as the end of the
query string.)

@subsubheading Return values

Zero if the query was successful. Non-zero if an error occurred.

@subsubheading Errors

@table @code
@item CR_COMMANDS_OUT_OF_SYNC
Commands were executed in an improper order.
@item CR_SERVER_GONE_ERROR
The @strong{MySQL} server has gone away.
@item CR_SERVER_LOST
The connection to the server was lost during the query.
@item CR_UNKNOWN_ERROR
An unknown error occurred.
@end table

@findex @code{mysql_real_connect()}
@node mysql_real_connect, mysql_real_query, mysql_query, C API functions
@subsection @code{mysql_real_connect()}

@code{MYSQL *mysql_real_connect(MYSQL *mysql, const char *host,
                          const char *user, const char *passwd, const char *db,
                          unsigned int port, const char *unix_socket,
                          unsigned int client_flag)}

@subsubheading Description

@code{mysql_real_connect()} attempts to establish a connection to a
@strong{MySQL} database engine running on @code{host}.
@code{mysql_real_connect()} must complete successfully before you can execute
any of the other API functions, with the exception of
@code{mysql_get_client_info()}.

The parameters are specified as follows:

@itemize @bullet
@item
@code{mysql} is a pointer to a @code{MYSQL} connection structure, or
@code{NULL}.

If @code{mysql} is @code{NULL}, the C API allocates memory for the
connection structure automatically and frees it when you call
@code{mysql_close()}. The disadvantage of this approach is that you can't
retrieve an error message if the connection fails.  (To get error information
from @code{mysql_errno()} or @code{mysql_error()}, you must provide a valid
@code{MYSQL} pointer.)

If the first parameter is not @code{NULL}, it should be the address of an
existing @code{MYSQL} structure.  In this case, before calling
@code{mysql_real_connect()} you must call @code{mysql_init()} to initialize
the @code{MYSQL} structure.  See the example below.

@item
The value of @code{host} may be either a hostname or an IP address.  If
@code{host} is @code{NULL} or the string @code{"localhost"}, a connection to
the local host is assumed. If the OS supports sockets (Unix) or named pipes
(Win32), they are used instead of TCP/IP to connect to the server.

@item
The @code{user} parameter contains the user's @strong{MySQL} login ID.  If
@code{user} is @code{NULL}, the current user is assumed.  Under Unix, this is
the current login name.  Under Windows ODBC, the current user name must be
specified explicitly.
@xref{ODBC administrator}.

@item
The @code{passwd} parameter contains the password for @code{user}.  If
@code{passwd} is @code{NULL}, only entries in the @code{user} table for the
user that have a blank password field will be checked for a match. This
allows the database administrator to set up the @strong{MySQL} privilege
system in such a way that users get different privileges depending on whether
or not they have specified a password.

Note: Do not attempt to encrypt the password before calling
@code{mysql_real_connect()}; password encryption is handled automatically by
the client API.

@item
@code{db} is the database name.
If @code{db} is not @code{NULL}, the connection will set the default
database to this value.

@item
If @code{port} is not 0, the value will be used as the port number
for the TCP/IP connection.  Note that the @code{host} parameter
determines the type of the connection.

@item
If @code{unix_socket} is not @code{NULL}, the string specifies the
socket or named pipe that should be used.  Note that the @code{host}
parameter determines the type of the connection.

@item
The value of @code{client_flag} is usually 0, but can be set to a combination
of the following flags in very special circumstances:

@multitable @columnfractions .25 .7
@item @strong{Flag name}       @tab @strong{Flag meaning}
@item @code{CLIENT_FOUND_ROWS} @tab Return the number of found rows, not the number of affected rows
@item @code{CLIENT_NO_SCHEMA}  @tab Don't allow the
@code{db_name.tbl_name.col_name} syntax.  This is for ODBC; it causes the
parser to generate an error if you use that syntax, which is is useful for
trapping bugs in some ODBC programs.
@item @code{CLIENT_COMPRESS}   @tab Use compression protocol
@item @code{CLIENT_ODBC}       @tab The client is an ODBC client. This changes
@code{mysqld} to be more ODBC-friendly.
@end multitable
@end itemize

@subsubheading Return values

A @code{MYSQL*} connection handle if the connection was successful.
@code{NULL} if the connection was unsuccessful.  For a successful connection,
the return value is the same as the value of the first parameter, unless you
pass @code{NULL} for that parameter.

@subsubheading Errors

@table @code
@item CR_CONN_HOST_ERROR
Failed to connect to the @strong{MySQL} server.

@item CR_CONNECTION_ERROR
Failed to connect to the local @strong{MySQL} server.

@item CR_IPSOCK_ERROR
Failed to create an IP socket.

@item CR_OUT_OF_MEMORY
Out of memory.

@item CR_SOCKET_CREATE_ERROR
Failed to create a Unix socket.

@item CR_UNKNOWN_HOST
Failed to find the IP address for the hostname.

@item CR_VERSION_ERROR
A protocol mismatch resulted from attempting to connect to a server with a
client library that uses a different protocol version.  This can happen if you
use a very old client library to connect to a new server that wasn't started
with the @code{--old-protocol} option.

@item CR_NAMEDPIPEOPEN_ERROR;
Failed to create a named pipe on Win32.

@item CR_NAMEDPIPEWAIT_ERROR;
Failed to wait for a named pipe on Win32.

@item CR_NAMEDPIPESETSTATE_ERROR;
Failed to get a pipe handler on Win32.
@end table

@subsubheading Example

@example
MYSQL mysql;

mysql_init(&mysql);
if (!mysql_real_connect(&mysql,"host","user","passwd","database",0,NULL,0))
@{
    fprintf(stderr, "Failed to connect to database: Error: %s\n",
          mysql_error(&mysql));
@}
@end example

@findex @code{mysql_real_query()}
@node mysql_real_query, mysql_reload, mysql_real_connect, C API functions
@subsection @code{mysql_real_query()}

@code{int mysql_real_query(MYSQL *mysql, const char *query, unsigned int length)}

@subsubheading Description

Executes the SQL query pointed to by query, which should be a string
@code{length} bytes long.  The query must consist of a single SQL statement.
You should not add a terminating semicolon (@samp{;}) or @code{\g} to the
statement.

You @emph{must} use @code{mysql_real_query()} rather than
@code{mysql_query()} for queries that contain binary data, since binary data
may contain the @samp{\0} character.  In addition, @code{mysql_real_query()}
is faster than @code{mysql_query()} since it does not call @code{strlen()} on
the query string.

@subsubheading Return values

Zero if the query was successful. Non-zero if an error occurred.

@subsubheading Errors

@table @code
@item CR_COMMANDS_OUT_OF_SYNC
Commands were executed in an improper order.
@item CR_SERVER_GONE_ERROR
The @strong{MySQL} server has gone away.
@item CR_SERVER_LOST
The connection to the server was lost during the query.
@item CR_UNKNOWN_ERROR
An unknown error occurred.
@end table

@findex @code{mysql_reload()}
@node mysql_reload, mysql_row_seek, mysql_real_query, C API functions
@subsection @code{mysql_reload()}

@code{int mysql_reload(MYSQL *mysql)}

@subsubheading Description

Asks the @strong{MySQL} server to reload the grant tables. The
connected user must have the @strong{reload} privilege.

This function is deprecated.  It is preferable to use @code{mysql_query()}
to issue a SQL @code{FLUSH PRIVILEGES} statement instead.

@subsubheading Return values

Zero for success.  Non-zero if an error occurred.

@subsubheading Errors

@table @code
@item CR_COMMANDS_OUT_OF_SYNC
Commands were executed in an improper order.
@item CR_SERVER_GONE_ERROR
The @strong{MySQL} server has gone away.
@item CR_SERVER_LOST
The connection to the server was lost during the query.
@item CR_UNKNOWN_ERROR
An unknown error occurred.
@end table

@findex @code{mysql_row_seek()}
@node mysql_row_seek, mysql_row_tell, mysql_reload, C API functions
@subsection @code{mysql_row_seek()}

@code{MYSQL_ROW_OFFSET mysql_row_seek(MYSQL_RES *result, MYSQL_ROW_OFFSET offset)}

@subsubheading Description
Sets the row cursor to an arbitrary row in a query result set.  This requires
that the result set structure contains the entire result of the query, so
@code{mysql_row_seek()} may be used in conjunction only with
@code{mysql_store_result()}, not with @code{mysql_use_result()}.

The offset should be a value returned from a call to @code{mysql_row_tell()}
or to @code{mysql_row_seek()}.  This value is not simply a row number; if you
want to seek to a row within a result set using a row number, use
@code{mysql_data_seek()} instead.

@subsubheading Return values

The previous value of the row cursor.  This value may be passed to a
subsequent call to @code{mysql_row_seek()}.

@subsubheading Errors
None.

@findex @code{mysql_row_tell()}
@node mysql_row_tell, mysql_select_db, mysql_row_seek, C API functions
@subsection @code{mysql_row_tell()}

@code{MYSQL_ROW_OFFSET mysql_row_tell(MYSQL_RES *result)}

@subsubheading Description

Returns the current position of the row cursor for the last
@code{mysql_fetch_row()}. This value can be used as an argument to
@code{mysql_row_seek()}.

You should use @code{mysql_row_tell()} only after @code{mysql_store_result()},
not after @code{mysql_use_result()}.

@subsubheading Return values

The current offset of the row cursor.

@subsubheading Errors
None.

@findex @code{mysql_select_db()}
@node mysql_select_db, mysql_shutdown, mysql_row_tell, C API functions
@subsection @code{mysql_select_db()}

@code{int mysql_select_db(MYSQL *mysql, const char *db)}

@subsubheading Description

Causes the database specified by @code{db} to become the default (current)
database on the connection specified by @code{mysql}.  In subsequent queries,
this database is the default for table references that do not include an
explicit database specifier.

@code{mysql_select_db()} fails unless the connected user can be authenticated
as having permission to use the database.

@subsubheading Return values

Zero for success.  Non-zero if an error occurred.

@subsubheading Errors

@table @code
@item CR_COMMANDS_OUT_OF_SYNC
Commands were executed in an improper order.
@item CR_SERVER_GONE_ERROR
The @strong{MySQL} server has gone away.
@item CR_SERVER_LOST
The connection to the server was lost during the query.
@item CR_UNKNOWN_ERROR
An unknown error occurred.
@end table

@findex @code{mysql_shutdown()}
@node mysql_shutdown, mysql_stat, mysql_select_db, C API functions
@subsection @code{mysql_shutdown()}

@code{int mysql_shutdown(MYSQL *mysql)}

@subsubheading Description

Asks the database server to shutdown. The connected user must have
@strong{shutdown} privileges.

@subsubheading Return values

Zero for success.  Non-zero if an error occurred.

@subsubheading Errors

@table @code
@item CR_COMMANDS_OUT_OF_SYNC
Commands were executed in an improper order.
@item CR_SERVER_GONE_ERROR
The @strong{MySQL} server has gone away.
@item CR_SERVER_LOST
The connection to the server was lost during the query.
@item CR_UNKNOWN_ERROR
An unknown error occurred.
@end table

@findex @code{mysql_stat()}
@node mysql_stat, mysql_store_result, mysql_shutdown, C API functions
@subsection @code{mysql_stat()}

@code{char *mysql_stat(MYSQL *mysql)}

@subsubheading Description

Returns a character string containing information similar to that provided by
the @code{mysqladmin status} command.  This includes uptime in seconds and
the number of running threads, questions, reloads and open tables.

@subsubheading Return values

A character string describing the server status. @code{NULL} if an
error occurred.

@subsubheading Errors

@table @code
@item CR_COMMANDS_OUT_OF_SYNC
Commands were executed in an improper order.
@item CR_SERVER_GONE_ERROR
The @strong{MySQL} server has gone away.
@item CR_SERVER_LOST
The connection to the server was lost during the query.
@item CR_UNKNOWN_ERROR
An unknown error occurred.
@end table

@findex @code{mysql_store_result()}
@node mysql_store_result, mysql_thread_id, mysql_stat, C API functions
@subsection @code{mysql_store_result()}

@code{MYSQL_RES *mysql_store_result(MYSQL *mysql)}

@subsubheading Description

You must call
@code{mysql_store_result()} or @code{mysql_use_result()} for every query
which successfully retrieves data (@code{SELECT}, @code{SHOW},
@code{DESCRIBE}, @code{EXPLAIN}).

@code{mysql_store_result()} reads the entire result of a query to the client,
allocates a @code{MYSQL_RES} structure, and places the result into this
structure.

An empty result set is returned if there are no rows returned.  (An empty
result set differs from a @code{NULL} return value.)

Once you have called @code{mysql_store_result()}, you may call
@code{mysql_num_rows()} to find out how many rows are in the result set.

You can call @code{mysql_fetch_row()} to fetch rows from the result set,
or @code{mysql_row_seek()} and @code{mysql_row_tell()} to obtain or
set the current row position within the result set.

You must call @code{mysql_free_result()} once you are done with the result
set.

@xref{NULL mysql_store_result, , @code{NULL mysql_store_result()}}.

@subsubheading Return values

A @code{MYSQL_RES} result structure with the results. @code{NULL} if
an error occurred.

@subsubheading Errors

@table @code
@item CR_COMMANDS_OUT_OF_SYNC
Commands were executed in an improper order.
@item CR_OUT_OF_MEMORY
Out of memory.
@item CR_SERVER_GONE_ERROR
The @strong{MySQL} server has gone away.
@item CR_SERVER_LOST
The connection to the server was lost during the query.
@item CR_UNKNOWN_ERROR
An unknown error occurred.
@end table

@findex @code{mysql_thread_id()}
@node mysql_thread_id, mysql_use_result, mysql_store_result, C API functions
@subsection @code{mysql_thread_id()}

@code{unsigned long mysql_thread_id(MYSQL *mysql)}

@subsubheading Description

Returns the thread ID of the current connection.  This value can be used as
an argument to @code{mysql_kill()} to kill the thread.

If the connection is lost and you reconnect with @code{mysql_ping()}, the
thread ID will change.  This means you should not get the thread ID and store
it for later, you should get it when you need it.

@subsubheading Return values

The thread ID of the current connection.

@subsubheading Errors
None.

@findex @code{mysql_use_result()}
@node mysql_use_result, NULL mysql_store_result, mysql_thread_id, C API functions
@subsection @code{mysql_use_result()}

@code{MYSQL_RES *mysql_use_result(MYSQL *mysql)}

@subsubheading Description

You must call @code{mysql_store_result()} or @code{mysql_use_result()} for
every query which successfully retrieves data (@code{SELECT}, @code{SHOW},
@code{DESCRIBE}, @code{EXPLAIN}).

@code{mysql_use_result()} initiates a result set retrieval but does not
actually read the result set into the client like @code{mysql_store_result()}
does.  Instead, each row must be retrieved individually by making calls to
@code{mysql_fetch_row()}.  This reads the result of a query directly from the
server without storing it in a temporary table or local buffer, which is
somewhat faster and uses much less memory than @code{mysql_store_result()}.
The client will only allocate memory for the current row and a communication
buffer that may grow up to @code{max_allowed_packet} bytes.

On the other hand, you shouldn't use @code{mysql_use_result()} if you are
doing a lot of processing for each row on the client side, or if the output
is sent to a screen on which the user may type a @code{^S} (stop scroll).
This will tie up the server and prevent other threads from updating any
tables from which the data are fetched.

When using @code{mysql_use_result()}, you must execute
@code{mysql_fetch_row()} until a @code{NULL} value is returned, otherwise the
unfetched rows will be returned as part of the result set for your next
query. The C API will give the error @code{Commands out of sync; You can't
run this command now} if you forget to do this!

You may not use @code{mysql_data_seek()}, @code{mysql_row_seek()},
@code{mysql_row_tell()}, @code{mysql_num_rows()} or
@code{mysql_affected_rows()} with a result returned from
@code{mysql_use_result()}, nor may you issue other queries until the
@code{mysql_use_result()} has finished.  (However, after you have fetched all
the rows, @code{mysql_num_rows()} will accurately return the number of rows
fetched.)

You must call @code{mysql_free_result()} once you are done with the result
set.

@subsubheading Return values

A @code{MYSQL_RES} result structure. @code{NULL} if an error occurred.

@subsubheading Errors

@table @code
@item CR_COMMANDS_OUT_OF_SYNC
Commands were executed in an improper order.
@item CR_OUT_OF_MEMORY
Out of memory.
@item CR_SERVER_GONE_ERROR
The @strong{MySQL} server has gone away.
@item CR_SERVER_LOST
The connection to the server was lost during the query.
@item CR_UNKNOWN_ERROR
An unknown error occurred.
@end table

@node NULL mysql_store_result, Query results, mysql_use_result, C API functions
@subsection Why is it that after @code{mysql_query()} returns success, @code{mysql_store_result()} sometimes returns @code{NULL?}

It is possible for @code{mysql_store_result()} to return @code{NULL}
following a successful call to @code{mysql_query()}.  When this happens, it
means one of the following conditions occurred:

@itemize @bullet
@item
There was a @code{malloc()} failure (for example, if the result set was too
large).

@item
The data couldn't be read (an error occurred on the connection).

@item
The query returned no data (e.g., it was an @code{INSERT}, @code{UPDATE}
or @code{DELETE}).
@end itemize

You can always check whether or not the statement should have produced a
non-empty result by calling @code{mysql_num_fields()}.  If
@code{mysql_num_fields()} returns zero, the result is empty and the last
query was a statement that does not return values (for example, an
@code{INSERT} or a @code{DELETE}).  If @code{mysql_num_fields()} returns a
non-zero value, the statement should have produced a non-empty result.
See the description of the @code{mysql_num_fields()} function for an
example.

You can also test for an error by calling @code{mysql_error()} or
@code{mysql_errno()}.

@node Query results, Getting unique ID, NULL mysql_store_result, C API functions
@subsection What results can I get from a query?

In addition to the result set returned by a query, you can also get the
following information:

@itemize @bullet
@item
@code{mysql_affected_rows()} returns the number of rows affected by the last
query when doing an @code{INSERT}, @code{UPDATE} or @code{DELETE}. An
exception is that if @code{DELETE} is used without a @code{WHERE} clause, the
table is truncated, which is much faster! In this case,
@code{mysql_affected_rows()} returns zero for the number of records
affected.

@item
@code{mysql_num_rows()} returns the number of rows in a result set.  With
@code{mysql_store_result()}, @code{mysql_num_rows()} may be called as soon as
@code{mysql_store_result()} returns.  With @code{mysql_use_result()},
@code{mysql_num_rows()} may be called only after you have fetched all the
rows with @code{mysql_fetch_row()}.

@item
@code{mysql_insert_id()} returns the ID generated by the last
query that inserted a row into a table with an @code{AUTO_INCREMENT} index.
@xref{mysql_insert_id, , @code{mysql_insert_id()}}.

@item
Some queries (@code{LOAD DATA INFILE ...}, @code{INSERT INTO
... SELECT ...}, @code{UPDATE}) return additional info.  The result is
returned by @code{mysql_info()}.  See the description for @code{mysql_info()}
for the format of the string that it returns.  @code{mysql_info()} returns a
@code{NULL} pointer if there is no additional information.
@end itemize

@node Getting unique ID, C API linking problems, Query results, C API functions
@subsection How can I get the unique ID for the last inserted row?

If you insert a record in a table containing a column that has the
@code{AUTO_INCREMENT} attribute, you can get the most recently generated
ID by calling the @code{mysql_insert_id()} function.

You can also retrieve the ID by using the @code{LAST_INSERT_ID()} function in
a query string that you pass to @code{mysql_query()}.

You can check if an @code{AUTO_INCREMENT} index is used by executing
the following code. This also checks if the query was an @code{INSERT} with
an @code{AUTO_INCREMENT} index:

@example
if (mysql_error(&mysql)[0] == 0 &&
    mysql_num_fields(result) == 0 &&
    mysql_insert_id(&mysql) != 0)
@{
    used_id = mysql_insert_id(&mysql);
@}
@end example

The most recently generated ID is maintained in the server on a
per-connection basis.  It will not be changed by another client. It will not
even be changed if you update another @code{AUTO_INCREMENT} column with a
non-magic value (that is, a value that is not @code{NULL} and not @code{0}).

If you want to use the ID that was generated for one table and insert
it into a second table, you can use SQL statements like this:

@example
INSERT INTO foo (auto,text)
    VALUES(NULL,'text');              # generate ID by inserting NULL
INSERT INTO foo2 (id,text)
    VALUES(LAST_INSERT_ID(),'text');  # use ID in second table
@end example

@node C API linking problems, Thread-safe clients, Getting unique ID, C API functions
@subsection Problems linking with the C API

When linking with the C API, the following errors may occur on some systems:

@example
gcc -g -o client test.o -L/usr/local/lib/mysql -lmysqlclient -lsocket -lnsl

Undefined        first referenced
 symbol          in file
floor            /usr/local/lib/mysql/libmysqlclient.a(password.o)
ld: fatal: Symbol referencing errors. No output written to client
@end example

If this happens on your system, you must include the math library by
adding @code{-lm} to the end of the compile/link line.

@node Thread-safe clients,  , C API linking problems, C API functions
@subsection How to make a thread-safe client

The client is ``almost'' thread-safe. The biggest problem is that the
subroutines in @file{net.c} that read from sockets are not interrupt-safe.
This was done with the thought that you might want to have your own alarm
that can break a long read to a server.

The standard client libraries are not compiled with the thread options.

To get a thread-safe client, use the @code{-lmysys}, @code{-lstring} and
@code{-ldbug} libraries and @code{net_serv.o} that the server uses.

When using a threaded client, you can make great use of the routines in
the @file{thr_alarm.c} file.  If you are using routines from the
@code{mysys} library, the only thing you must remember is to call
@code{my_init()} first!

All functions except @code{mysql_real_connect()} are currently thread-safe.
The following notes describe how to compile a thread-safe client library and
use it in a thread-safe manner.  (The notes below for
@code{mysql_real_connect()} actually apply to @code{mysql_connect()} as well,
but since @code{mysql_connect()} is deprecated, you should be using
@code{mysql_real_connect()} anyway.)

To make @code{mysql_real_connect()} thread-safe, you must recompile the client
library with this command:

@example
shell> CPPFLAGS=-DTHREAD_SAFE_CLIENT ./configure ...
@end example

You may get some errors because of undefined symbols when linking the
standard client, because the pthread libraries are not included by
default.

The resulting @file{libmysqld.a} library is now thread-safe.  What this means
is that client code is thread-safe as long as two threads don't query the
same connection handle returned by @code{mysql_real_connect()} at the same
time; the client/server protocol allows only one request at a time on a given
connection.  If you want to use multiple threads on the same connection, you
must have a mutex lock around your @code{mysql_query()} and
@code{mysql_store_result()} call combination.  Once
@code{mysql_store_result()} is ready, the lock can be released and other
threads may query the same connection.  (In other words, different threads
can use different @code{MYSQL_RES} pointers that were created with
@code{mysql_store_result()}, as long as they use the proper locking
protocol.) If you program with POSIX threads, you can use
@code{pthread_mutex_lock()} and @code{pthread_mutex_unlock()} to establish
and release a mutex lock.

If you used @code{mysql_use_result()} rather than @code{mysql_store_result()},
the lock would need to surround @code{mysql_use_result()} and the calls
to @code{mysql_fetch_row()}.  However, it really is best for threaded
clients not to use @code{mysql_use_result()}.

@node Perl, Java, C API functions, Clients
@section @strong{MySQL} Perl API

This section documents the Perl @code{DBI} interface.  The former interface
was called @code{mysqlperl}.  Since @code{DBI}/@code{DBD} now is the
recommended Perl interface, @code{mysqlperl} is obsolete and is not
documented here.

@menu
* DBI with DBD::                @code{DBI} with @code{DBD::mysql}
* Perl DBI Class::              The @code{DBI} interface
* DBI-info::                    More @code{DBI}/@code{DBD} information
@end menu

@node DBI with DBD, Perl DBI Class, Perl, Perl
@subsection @code{DBI} with @code{DBD::mysql}

@code{DBI} is a generic interface for many databases. That means that
you can write a script that works with many different database engines
without change. You need a DataBase Driver (DBD) defined for each
database type. For @strong{MySQL}, this driver is called
@code{DBD::mysql}.

For more information on the Perl5 DBI, please visit the @code{DBI} web
page and read the documentation:
@example
@uref{http://www.symbolstone.org/technology/perl/DBI/index.html}
@end example
For more information on Object Oriented Programming
(OOP) as defined in Perl5, see the Perl OOP page:
@example
@uref{http://language.perl.com/info/documentation.html}
@end example

Installation instructions for @strong{MySQL} Perl support are given in
@ref{Perl support}.

@cindex @code{DBI} Perl module
@node Perl DBI Class, DBI-info, DBI with DBD, Perl
@subsection The @code{DBI} interface

@noindent
@strong{Portable DBI methods}

@multitable @columnfractions .3 .7
@item @code{connect} @tab Establishes a connection to a database server
@item @code{disconnect} @tab Disconnects from the database server
@item @code{prepare} @tab Prepares a SQL statement for execution
@item @code{execute} @tab Executes prepared statements
@item @code{do}      @tab Prepares and executes a SQL statement
@item @code{quote}   @tab Quotes string or @code{BLOB} values to be inserted
@item @code{fetchrow_array} @tab Fetches the next row as an array of fields.
@item @code{fetchrow_arrayref} @tab Fetches next row as a reference array of fields
@item @code{fetchrow_hashref} @tab Fetches next row as a reference to a hashtable
@item @code{fetchall_arrayref} @tab Fetches all data as an array of arrays
@item @code{finish}  @tab Finishes a statement and let the system free resources
@item @code{rows}    @tab Returns the number of rows affected
@item @code{data_sources} @tab Returns an array of databases available on localhost
@item @code{ChopBlanks} @tab Controls whether @code{fetchrow_*} methods trim spaces
@item @code{NUM_OF_PARAMS} @tab The number of placeholders in the prepared statement
@item @code{NULLABLE} @tab Which columns can be @code{NULL}
@item @code{trace}    @tab Perform tracing for debugging
@end multitable

@noindent
@strong{MySQL-specific methods}

@multitable @columnfractions .3 .7
@item @code{insertid} @tab The latest @code{AUTO_INCREMENT} value
@item @code{is_blob} @tab Which column are @code{BLOB} values
@item @code{is_key} @tab Which columns are keys
@item @code{is_num} @tab Which columns are numeric
@item @code{is_pri_key} @tab Which columns are primary keys
@item @code{is_not_null} @tab Which columns CANNOT be @code{NULL}. See @code{NULLABLE}.
@item @code{length} @tab Maximum possible column sizes
@item @code{max_length} @tab Maximum column sizes actually present in result
@item @code{NAME} @tab Column names
@item @code{NUM_OF_FIELDS} @tab Number of fields returned
@item @code{table} @tab Table names in returned set
@item @code{type} @tab All column types
@end multitable

The Perl methods are described in more detail in the following sections.
Variables used for method return values have these meanings:

@table @code
@item $dbh
Database handle

@item $sth
Statement handle

@item $rc
Return code (often a status)

@item $rv
Return value (often a row count)
@end table

@noindent
@strong{Portable DBI methods}

@table @code

@findex DBI->connect()
@findex connect() DBI method
@item connect($data_source, $username, $password)
Use the @code{connect} method to make a database connection to the data
source. The @code{$data_source} value should begin with
@code{DBI:driver_name:}.
Example uses of @code{connect} with the @code{DBD::mysql} driver:
@example
$dbh = DBI->connect("DBI:mysql:$database", $user, $password);
$dbh = DBI->connect("DBI:mysql:$database:$hostname",
                    $user, $password);
$dbh = DBI->connect("DBI:mysql:$database:$hostname:$port",
                    $user, $password);
@end example
If the user name and/or password are undefined, @code{DBI} uses the
values of the @code{DBI_USER} and @code{DBI_PASS} environment variables,
respectively. If you don't specify a hostname, it defaults to
@code{'localhost'}. If you don't specify a port number, it defaults to the
default @strong{MySQL} port (@value{default_port}).

As of @code{Msql-Mysql-modules} version 1.2009,
the @code{$data_source} value allows certain modifiers:

@table @code
@item mysql_read_default_file=file_name
Read @file{filename} as an option file.  For information on option files,
see @ref{Option files}.

@item mysql_read_default_group=group_name
The default group when reading an option file is normally the
@code{[client]} group.  By specifying the @code{mysql_read_default_group}
option, the default group becomes the @code{[group_name]} group.

@item mysql_compression=1
Use compressed communication between the client and server (@strong{MySQL}
3.22.3 or later).

@item mysql_socket=/path/to/socket
Specify the pathname of the Unix socket that is used to connect
to the server (@strong{MySQL} 3.21.15 or later).
@end table

Multiple modifiers may be given; each must be preceded by a semicolon.

For example, if you want to avoid hardcoding the user name and password into
a @code{DBI} script, you can take them from the user's @file{~/.my.cnf}
option file instead by writing your @code{connect} call like this:

@example
$dbh = DBI->connect("DBI:mysql:$database"
                . ";mysql_read_default_file=$ENV@{HOME@}/.my.cnf",
                $user, $password);
@end example

This call will read options defined for the @code{[client]} group in the
option file.  If you wanted to do the same thing, but use options specified
for the @code{[perl]} group instead, you could use this:

@example
$dbh = DBI->connect("DBI:mysql:$database"
                . ";mysql_read_default_file=$ENV@{HOME@}/.my.cnf"
                . ";mysql_read_default_group=perl",
                $user, $password);
@end example

@findex DBI->disconnect
@findex disconnect DBI method
@item disconnect
The @code{disconnect} method disconnects the database handle from the database.
This is typically called right before you exit from the program.
Example:
@example
$rc = $dbh->disconnect;
@end example

@findex DBI->prepare()
@findex prepare() DBI method
@item prepare($statement)
Prepares a SQL statement for execution by the database engine
and returns a statement handle @code{($sth)} which you can use to invoke
the @code{execute} method.
Typically you handle @code{SELECT} statements (and @code{SELECT}-like statements
such as @code{SHOW}, @code{DESCRIBE} and @code{EXPLAIN}) by means of
@code{prepare} and @code{execute}.
Example:
@example
$sth = $dbh->prepare($statement)
    or die "Can't prepare $statement: $dbh->errstr\n";
@end example

@findex DBI->execute
@findex execute DBI method
@item execute
The @code{execute} method executes a prepared statement. For
non-@code{SELECT} statements, @code{execute} returns the number of rows
affected.  If no rows are affected, @code{execute} returns @code{"0E0"},
which Perl treats as zero but regards as true.  For @code{SELECT} statements,
@code{execute} only starts the SQL query in the database; you need to use one
of the @code{fetch_*} methods described below to retrieve the data.
Example:
@example
$rv = $sth->execute
          or die "can't execute the query: $sth->errstr;
@end example

@findex DBI->do()
@findex do() DBI method
@item do($statement)
The @code{do} method prepares and executes a SQL statement and returns the
number of rows affected.  If no rows are affected, @code{do} returns
@code{"0E0"}, which Perl treats as zero but regards as true.  This method is
generally used for non-@code{SELECT} statements which cannot be prepared in
advance (due to driver limitations) or which do not need to executed more
than once (inserts, deletes, etc.). Example:
@example
$rv = $dbh->do($statement)
        or die "Can't execute $statement: $dbh- >errstr\n";
@end example

@findex DBI->quote()
@findex quote() DBI method
@cindex Quoting strings
@cindex Strings, quoting
@item quote($string)
The @code{quote} method is used to "escape" any special characters contained in
the string and to add the required outer quotation marks.
Example:
@example
$sql = $dbh->quote($string)
@end example

@findex DBI->fetchrow_array
@findex fetchrow_array DBI method
@item fetchrow_array
This method fetches the next row of data and returns it as an array of
field values.  Example:
@example
while(@@row = $sth->fetchrow_array) @{
        print qw($row[0]\t$row[1]\t$row[2]\n);
@}
@end example

@findex DBI->fetchrow_arrayref
@findex fetchrow_arrayref DBI method
@item fetchrow_arrayref
This method fetches the next row of data and returns it as a reference
to an array of field values. Example:
@example
while($row_ref = $sth->fetchrow_arrayref) @{
        print qw($row_ref->[0]\t$row_ref->[1]\t$row_ref->[2]\n);
@}
@end example

@findex DBI->fetchrow_hashref
@findex fetchrow_hashref DBI method
@item fetchrow_hashref
This method fetches a row of data and returns a reference to a hash
table containing field name/value pairs. This method is not nearly as
efficient as using array references as demonstrated above. Example:
@example
while($hash_ref = $sth->fetchrow_hashref) @{
        print qw($hash_ref->@{firstname@}\t$hash_ref->@{lastname@}\t\
                $hash_ref- > title@}\n);
@}
@end example

@findex DBI->fetchall_arrayref
@findex fetchall_arrayref DBI method
@item fetchall_arrayref
This method is used to get all the data (rows) to be returned from the
SQL statement. It returns a reference to an array of arrays of
references to each row. You access or print the data by using a nested
loop. Example:
@example
my $table = $sth->fetchall_arrayref
                or die "$sth->errstr\n";
my($i, $j);
for $i ( 0 .. $#@{$table@} ) @{
        for $j ( 0 .. $#@{$table->[$i]@} ) @{
                print "$table->[$i][$j]\t";
        @}
        print "\n";
@}
@end example

@findex DBI->finish
@findex finish DBI method
@item finish
Indicates that no more data will be fetched from this statement
handle. You call this method to free up the statement handle and any
system resources it may be holding.  Example:
@example
$rc = $sth->finish;
@end example

@findex DBI->rows
@findex rows DBI method
@item rows
Returns the number of rows changed (updated, deleted, etc.) by the last
command.  This is usually used after a non-@code{SELECT} @code{execute}
statement.  Example:
@example
$rv = $sth->rows;
@end example

@findex DBI->@{NULLABLE@}
@findex NULLABLE DBI method
@item NULLABLE
Returns a reference to an array of boolean values; for each element of
the array, a value of TRUE indicates that this
column may contain @code{NULL} values.
Example:
@example
$null_possible = $sth->@{NULLABLE@};
@end example

@findex DBI->@{NUM_OF_FIELDS@}
@findex NUM_OF_FIELDS DBI method
@item NUM_OF_FIELDS
This attribute indicates
the number of fields returned by a @code{SELECT} or @code{SHOW FIELDS}
statement.  You may use this for checking whether a statement returned a
result: A zero value indicates a non-@code{SELECT} statement like
@code{INSERT}, @code{DELETE} or @code{UPDATE}.
Example:
@example
$nr_of_fields = $sth->@{NUM_OF_FIELDS@};
@end example

@findex DBI->data_sources()
@findex data_sources() DBI method
@item data_sources($driver_name)
This method returns an array containing names of databases available to the
@strong{MySQL} server on the host @code{'localhost'}.
Example:
@example
@@dbs = DBI->data_sources("mysql");
@end example

@findex DBI->@{ChopBlanks@}
@findex ChopBlanks DBI method
@item ChopBlanks
This attribute determines whether the @code{fetchrow_*} methods will chop
leading and trailing blanks from the returned values.
Example:
@example
$sth->@{'ChopBlanks'@} =1;
@end example

@findex DBI->trace
@findex trace DBI method
@item trace($trace_level)
@itemx trace($trace_level, $trace_filename)
The @code{trace} method enables or disables tracing.  When invoked as a
@code{DBI} class method, it affects tracing for all handles.  When invoked as
a database or statement handle method, it affects tracing for the given
handle (and any future children of the handle).  Setting @code{$trace_level}
to 2 provides detailed trace information.  Setting @code{$trace_level} to 0
disables tracing.  Trace output goes to the standard error output by
default.  If @code{$trace_filename} is specified, the file is opened in
append mode and output for @emph{all} traced handles is written to that
file.  Example:
@example
DBI->trace(2);                # trace everything
DBI->trace(2,"/tmp/dbi.out"); # trace everything to /tmp/dbi.out
$dth->trace(2);               # trace this database handle
$sth->trace(2);               # trace this statement handle
@end example

@tindex DBI_TRACE environment variable
@tindex Environment variable, DBI_TRACE
You can also enable @code{DBI} tracing by setting the @code{DBI_TRACE}
environment variable.  Setting it to a numeric value is equivalent to calling
@code{DBI->(value)}.  Setting it to a pathname is equivalent to calling
@code{DBI->(2,value)}.

@end table

@noindent
@strong{MySQL-specific methods}

The methods shown below are @strong{MySQL}-specific and not part of the
@code{DBI} standard.  Several of them are now deprecated:
@code{is_blob}, @code{is_key}, @code{is_num}, @code{is_pri_key},
@code{is_not_null}, @code{length}, @code{max_length}, and @code{table}.
Where @code{DBI}-standard alternatives exist, they are noted below.

@table @code
@findex DBI->@{insertid@}
@findex insertid DBI method
@tindex AUTO_INCREMENT, using with DBI
@item insertid
If you use the @code{AUTO_INCREMENT} feature of @strong{MySQL}, the new
auto-incremented values will be stored here.
Example:
@example
$new_id = $sth->@{insertid@};
@end example

As an alternative, you can use @code{$dbh->@{'mysql_insertid'@}}.

@findex DBI->@{is_blob@}
@findex is_blob DBI method
@item is_blob
Returns a reference to an array of boolean values; for each element of the
array, a value of TRUE indicates that the
respective column is a @code{BLOB}.
Example:
@example
$keys = $sth->@{is_blob@};
@end example

@findex DBI->@{is_key@}
@findex is_key DBI method
@item is_key
Returns a reference to an array of boolean values; for each element of the
array, a value of TRUE indicates that the
respective column is a key.
Example:
@example
$keys = $sth->@{is_key@};
@end example

@findex DBI->@{is_num@}
@findex is_num DBI method
@item is_num
Returns a reference to an array of boolean values; for each element of the
array, a value of TRUE indicates that the
respective column contains numeric values.
Example:
@example
$nums = $sth->@{is_num@};
@end example

@findex DBI->@{is_pri_key@}
@findex is_pri_key DBI method
@item is_pri_key
Returns a reference to an array of boolean values; for each element of the
array, a value of TRUE indicates that the respective column is a primary key.
Example:
@example
$pri_keys = $sth->@{is_pri_key@};
@end example

@findex DBI->@{is_not_null@}
@findex is_not_null DBI method
@item is_not_null
Returns a reference to an array of boolean values; for each element of the
array, a value of FALSE indicates that this column may contain @code{NULL}
values.
Example:
@example
$not_nulls = $sth->@{is_not_null@};
@end example

@code{is_not_null} is deprecated; it is preferable to use the
@code{NULLABLE} attribute (described above), since that is a DBI standard.

@findex DBI->@{length@}
@findex length DBI method
@findex DBI->@{max_length@}
@findex max_length DBI method
@item length
@itemx max_length
Each of these methods returns a reference to an array of column sizes.  The
@code{length} array indicates the maximum possible sizes that each column may
be (as declared in the table description).  The @code{max_length} array
indicates the maximum sizes actually present in the result table.  Example:

@example
$lengths = $sth->@{length@};
$max_lengths = $sth->@{max_length@};
@end example

@findex DBI->@{NAME@}
@findex NAME DBI method
@item NAME
Returns a reference to an array of column names.
Example:
@example
$names = $sth->@{NAME@};
@end example

@findex DBI->@{table@}
@findex table DBI method
@item table
Returns a reference to an array of table names.
Example:
@example
$tables = $sth->@{table@};
@end example

@findex DBI->@{type@}
@findex type DBI method
@item type
Returns a reference to an array of column types.
Example:
@example
$types = $sth->@{type@};
@end example

@end table

@node DBI-info,  , Perl DBI Class, Perl
@subsection More @code{DBI}/@code{DBD} information

You can use the @code{perldoc} command to get more information about
@code{DBI}.

@example
perldoc DBI
perldoc DBI::FAQ
perldoc DBD::mysql
@end example

You can also use the @code{pod2man}, @code{pod2html}, etc., tools to
translate to other formats.

And of course you can find the latest @code{DBI} information at
the @code{DBI} web page:
@example
@uref{http://www.symbolstone.org/technology/perl/DBI/index.html}
@end example

@node Java, PHP, Perl, Clients
@section @strong{MySQL} Java connectivity (JDBC)

There are 2 supported JDBC drivers for MySQL (the twz and mm driver).
You can find a copy of these at @uref{http://www.mysql.com/Contrib}.
For documentation consult any JDBC documentation and the
drivers own documentation for @strong{MySQL} specific features.

@node PHP, Cplusplus, Java, Clients
@section @strong{MySQL} PHP API

PHP is a server-side, HTML embedded scripting language that may be used to
create dynamic web pages.  It contains support for accessing several
databases, including @strong{MySQL}.  PHP may be run as a separate program,
or compiled as a module for use with the Apache web server.

The distribution and documentation are available at the
@uref{http://www.php.net/, PHP website}.

@node Cplusplus, Python, PHP, Clients
@section @strong{MySQL} C++ APIs

Two API's are available in the @strong{MySQL}
@uref{http://www.mysql.com/Contrib/,Contrib directory}.

@node Python, TCL, Cplusplus, Clients
@section @strong{MySQL} Python APIs

The @strong{MySQL} @uref{http://www.mysql.com/Contrib/,Contrib directory}
contains a Python
interface written by Joseph Skinner.

You can also use the Python interface to iODBC to access a
@strong{MySQL} server.
@uref{http://starship.skyport.net/~lemburg/,mxODBC}

@node TCL,  , Python, Clients
@section @strong{MySQL} TCL APIs

@uref{http://www.binevolve.com/~tdarugar/tcl-sql/, TCL at binevolve}.
The
@uref{http://www.mysql.com/Contrib,Contrib directory} contains a TCL
interface that is based on msqltcl 1.50.

@node Comparisons, Users, Clients, Top
@chapter How @strong{MySQL} compares to other databases

@menu
* Compare mSQL::                How @strong{MySQL} compares to @code{mSQL}
* Compare PostgreSQL::          How @strong{MySQL} compares with PostgreSQL
@end menu

@node Compare mSQL, Compare PostgreSQL, Comparisons, Comparisons
@section How @strong{MySQL} compares to @code{mSQL}

This section has been written by the @strong{MySQL} developers, so it
should be read with that in mind. But there are NO factual errors that
we know of.

For a list of all supported limits, functions and types, see the
@uref{http://www.mysql.com/crash-me-choose.htmy, @code{crash-me} web page}.

@table @strong
@item Performance

For a true comparison of speed, consult the growing @strong{MySQL} benchmark
suite. @xref{Benchmarks}.

Because there is no thread creation overhead, a small parser, few features and
simple security, @code{mSQL} should be quicker at:

@itemize @bullet
@item
Tests that perform repeated connects and disconnects, running a very simple
query during each connection.
@item
@code{INSERT} operations into very simple tables with few columns and keys.
@item
@code{CREATE TABLE} and @code{DROP TABLE}.
@item
@code{SELECT} on something that isn't an index. (A table scan is very
easy.)
@end itemize

Since these operations are so simple, it is hard to be better at them when
you have a higher startup overhead. After the connection is established,
@strong{MySQL} should perform much better.

On the other hand, @strong{MySQL} is much faster than @code{mSQL} (and
most other SQL implementions) on the following:

@itemize @bullet
@item
Complex @code{SELECT} operations.
@item
Retrieving large results (@strong{MySQL} has a better, faster and safer
protocol).
@item
Tables with variable-length strings, since @strong{MySQL} has more efficent
handling and can have indexes on @code{VARCHAR} columns.
@item
Handling tables with many columns.
@item
Handling tables with large record lengths.
@item
@code{SELECT} with many expressions.
@item
@code{SELECT} on large tables.
@item
Handling many connections at the same time. @strong{MySQL} is fully
multi-threaded. Each connection has its own thread, which means that
no thread has to wait for another (unless a thread is modifying
a table another thread wants to access.) In @code{mSQL}, once one connection
is established, all others must wait until the first has finished, regardless
of whether the connection is running a query that is short or long. When the
first connection terminates, the next can be served, while all the others wait
again, etc.
@item
Joins.
@code{mSQL} can become pathologically slow if you change the order of tables
in a @code{SELECT}. In the benchmark suite, a time more than 15000 times
slower than @strong{MySQL} was seen.  This is due to @code{mSQL}'s lack of a
join optimizer to order tables in the optimal order. However, if you put the
tables in exactly the right order in @code{mSQL}2 and the @code{WHERE} is
simple and uses index columns, the join will be relatively fast!
@xref{Benchmarks}.
@item
@code{ORDER BY} and @code{GROUP BY}.
@item
@code{DISTINCT}.
@item
Using @code{TEXT} or @code{BLOB} columns.
@end itemize

@item SQL Features

@itemize @bullet
@item @code{GROUP BY} and @code{HAVING}.
@code{mSQL} does not support @code{GROUP BY} at all.
@strong{MySQL} supports a full @code{GROUP BY} with both @code{HAVING} and
the following functions: @code{COUNT()}, @code{AVG()}, @code{MIN()},
@code{MAX()}, @code{SUM()} and @code{STD()}.  @code{COUNT(*)} is optimized to
return very quickly if the @code{SELECT} retrieves from one table, no other
columns are retrieved and there is no @code{WHERE} clause.  @code{MIN()} and
@code{MAX()} may take string arguments.

@item @code{INSERT} and @code{UPDATE} with calculations.
@strong{MySQL} can do calculations in an @code{INSERT} or @code{UPDATE}.
For example:
@example
mysql> UPDATE SET x=x*10+y WHERE x<20;
@end example

@item Aliasing.
@strong{MySQL} has column aliasing.

@item Qualifying column names.
In @strong{MySQL}, if a column name is unique among the tables used in a
query, you do not have to use the full qualifier.

@item @code{SELECT} with functions.
@strong{MySQL} has many functions (too many to list here; see @ref{Functions}).

@end itemize

@item Disk space efficiency
That is, how small can you make your tables?

@strong{MySQL} has very precise types, so you can create tables that take
very little space. An example of a useful @strong{MySQL} datatype is the
@code{MEDIUMINT} that is 3 bytes long. If you have 100,000,000 records,
saving even one byte per record is very important.

@code{mSQL2} has a more limited set of column types, so it is
more difficult to get small tables.
@item Stability
This is harder to judge objectively. For a discussion of @strong{MySQL}
stability, see @ref{Stability}.

We have no experience with @code{mSQL} stability, so we cannot say
anything about that.

@item Price
Another important issue is the license. @strong{MySQL} has a
more flexible license than @code{mSQL}, and is also less expensive than
@code{mSQL}.  Whichever product you choose to use, remember to at least
consider paying for a license or email support.  (You are required to get
a license if you include @strong{MySQL} with a product that you sell,
of course.)

@item Perl interfaces
@strong{MySQL} has basically the same interfaces to Perl as @code{mSQL} with
some added features.

@item JDBC (Java)
@strong{MySQL} currently has 4 JDBC drivers:
@itemize @bullet
@item
The gwe driver: A Java interface by GWE technologies (not supported anymore).
@item
The jms driver: An improved gwe driver by Xiaokun Kelvin ZHU
@email{X.Zhu@@brad.ac.uk}.
@item
The twz driver: A type 4 JDBC driver by Terrence W. Zellers
@email{zellert@@voicenet.com}.  This is commercial but is free for private
and educational use.
@item
The mm driver: A type 4 JDBC driver by Mark Matthews
@email{mmatthew@@ecn.purdue.edu}.  This is released under the GPL.
@end itemize

The recommended drivers are the twz or mm driver. Both are reported to work
excellently.

We know that @code{mSQL} has a JDBC driver, but we have too little experience
with it to compare.

@item Rate of development
@strong{MySQL} has a very small team of developers, but we are quite used to
coding C and C++ very rapidly. Since threads, functions, @code{GROUP BY} and so
on are still not implemented in @code{mSQL}, it has a lot of catching up
to do. To get some perspective on this, you can view the @code{mSQL}
@file{HISTORY} file for the last year and compare it with the News
section of the @strong{MySQL} Reference Manual (@pxref{News}). It should be
pretty obvious which one has developed most rapidly.

@item Utility programs
Both @code{mSQL} and @strong{MySQL} have many interesting third-party
tools. Since it is very easy to port upward (from @code{mSQL} to
@strong{MySQL}), almost all the interesting applications that are available for
@code{mSQL} are also available for @strong{MySQL}.

@strong{MySQL} comes with a simple @code{msql2mysql} program that fixes
differences in spelling between @code{mSQL} and @strong{MySQL} for the
most-used C API functions.
For example, it changes instances of @code{msqlConnect()} to
@code{mysql_connect()}. Converting a client program from @code{mSQL} to
@strong{MySQL} usually takes a couple of minutes.
@end table

@menu
* Using mSQL tools::            How to convert @code{mSQL} tools for @strong{MySQL}
* Protocol differences::        How @code{mSQL} and @strong{MySQL} client/server communications protocols differ
* Syntax differences::          How @code{mSQL} 2.0 SQL syntax differs from @strong{MySQL}
@end menu

@node Using mSQL tools, Protocol differences, Compare mSQL, Compare mSQL
@subsection How to convert @code{mSQL} tools for @strong{MySQL}

According to our experience, it would just take a few hours to convert tools
such as @code{msql-tcl} and @code{msqljava} that use the
@code{mSQL} C API so that they work with the @strong{MySQL} C API.

The conversion procedure is:

@enumerate
@item
Run the shell script @code{msql2mysql} on the source. This requires the
@code{replace} program, which is distributed with @strong{MySQL}.
@item
Compile.
@item
Fix all compiler errors.
@end enumerate

Differences between the @code{mSQL} C API and the @strong{MySQL} C API are:
@itemize @bullet
@item
@strong{MySQL} uses a @code{MYSQL} structure as a connection type (@code{mSQL}
uses an @code{int}).
@item
@code{mysql_connect()} takes a pointer to a @code{MYSQL} structure as a
parameter.  It is easy to define one globally or to use @code{malloc()} to get
one.
@code{mysql_connect()} also takes 2 parameters for specifying the user and
password.  You may set these to @code{NULL, NULL} for default use.
@item
@code{mysql_error()} takes the @code{MYSQL} structure as a parameter. Just add
the parameter to your old @code{msql_error()} code if you are porting old code.
@item
@strong{MySQL} returns an error number and a text error message for all
errors. @code{mSQL} returns only a text error message.
@item
Some incompatibilities exist as a result of @strong{MySQL} supporting
multiple connections to the server from the same process.
@end itemize

@node Protocol differences, Syntax differences, Using mSQL tools, Compare mSQL
@subsection How @code{mSQL} and @strong{MySQL} client/server communications protocols differ

There are enough differences that it is impossible (or at least not easy)
to support both.

The most significant ways in which the @strong{MySQL} protocol differs
from the @code{mSQL} protocol are listed below:

@itemize @bullet
@item
A message buffer may contain many result rows.
@item
The message buffers are dynamically enlarged if the query or the
result is bigger than the current buffer, up to a configurable server and
client limit.
@item
All packets are numbered to catch duplicated or missing packets.
@item
All column values are sent in ASCII. The lengths of columns and rows are sent
in packed binary coding (1, 2 or 3 bytes).
@item
@strong{MySQL} can read in the result unbuffered (without having to store the
full set in the client).
@item
If a single write/read takes more than 30 seconds, the server closes
the connection.
@item
If a connection is idle for 8 hours, the server closes the connection.
@end itemize

@node Syntax differences,  , Protocol differences, Compare mSQL
@subsection How @code{mSQL} 2.0 SQL syntax differs from @strong{MySQL}

@noindent
@strong{Column types}

@table @code
@item @strong{MySQL}
Has the following additional types (among others; see
@pxref{CREATE TABLE, , @code{CREATE TABLE}}):
@itemize @bullet
@item
@code{ENUM} type for one of a set of strings.
@item
@code{SET} type for many of a set of strings.
@item
@code{BIGINT} type for 64-bit integers.
@end itemize
@item
@strong{MySQL} also supports
the following additional type attributes:
@itemize @bullet
@item
@code{UNSIGNED} option for integer columns.
@item
@code{ZEROFILL} option for integer columns.
@item
@code{AUTO_INCREMENT} option for integer columns that are a
@code{PRIMARY KEY}.
@xref{mysql_insert_id, , @code{mysql_insert_id()}}.
@item
@code{DEFAULT} value for all columns.
@end itemize
@item mSQL2
@code{mSQL} column types correspond to the @strong{MySQL} types shown below:
@multitable @columnfractions .15 .85
@item @code{mSQL} @strong{type} @tab @strong{Corresponding @strong{MySQL} type}
@item @code{CHAR(len)} @tab @code{CHAR(len)}
@item @code{TEXT(len)} @tab @code{TEXT(len)}. @code{len} is the maximal length.
And @code{LIKE} works.
@item @code{INT} @tab @code{INT}. With many more options!
@item @code{REAL} @tab @code{REAL}. Or @code{FLOAT}. Both 4- and 8-byte versions are available.
@item @code{UINT} @tab @code{INT UNSIGNED}
@item @code{DATE} @tab @code{DATE}. Uses ANSI SQL format rather than @code{mSQL}'s own.
@item @code{TIME} @tab @code{TIME}
@item @code{MONEY} @tab @code{DECIMAL(12,2)}. A fixed-point value with two decimals.
@end multitable
@end table

@noindent
@strong{Index creation}

@table @code
@item @strong{MySQL}
Indexes may be specified at table creation time with the @code{CREATE TABLE}
statement.
@item mSQL
Indexes must be created after the table has been created, with separate
@code{CREATE INDEX} statements.
@end table

@noindent
@strong{To insert a unique identifier into a table}

@table @code
@item @strong{MySQL}
Use @code{AUTO_INCREMENT} as a column type
specifier.
@xref{mysql_insert_id, , @code{mysql_insert_id()}}.
@item mSQL
Create a @code{SEQUENCE} on a table and select the @code{_seq} column.
@end table

@noindent
@strong{To obtain a unique identifier for a row}

@table @code
@item @strong{MySQL}
Add a @code{PRIMARY KEY} or @code{UNIQUE} key to the table.
@item mSQL
Use the @code{_rowid} column. Observe that @code{_rowid} may change over time
depending on many factors.
@end table

@noindent
@strong{To get the time a column was last modified}

@table @code
@item @strong{MySQL}
Add a @code{TIMESTAMP} column to the table. This column is automatically set
to the current date and time for @code{INSERT} or @code{UPDATE} statements if
you don't give the column a value or if you give it a @code{NULL} value.

@item mSQL
Use the @code{_timestamp} column.
@end table

@noindent
@strong{@code{NULL} value comparisons}

@table @code
@item @strong{MySQL}
@strong{MySQL} follows
ANSI SQL and a comparison with @code{NULL} is always @code{NULL}.
@item mSQL
In @code{mSQL}, @code{NULL = NULL} is TRUE.  You
must change @code{=NULL} to @code{IS NULL} and @code{<>NULL} to
@code{IS NOT NULL} when porting old code from @code{mSQL} to @strong{MySQL}.
@end table

@noindent
@strong{String comparisons}

@table @code
@item @strong{MySQL}
Normally, string comparisons are performed in case-independent fashion with
the sort order determined by the current character set (ISO-8859-1 Latin1 by
default).  If you don't like this, declare your columns with the
@code{BINARY} attribute, which causes comparisons to be done according to the
ASCII order used on the @strong{MySQL} server host.
@item mSQL
All string comparisons are performed in case-sensitive fashion with
sorting in ASCII order.
@end table

@noindent
@strong{Case-insensitive searching}

@table @code
@item @strong{MySQL}
@code{LIKE} is a case-insensitive or case-sensitive operator, depending on
the columns involved. If possible, @strong{MySQL} uses indexes if the
@code{LIKE} argument doesn't start with a wildcard character.
@item mSQL
Use @code{CLIKE}.
@end table

@noindent
@strong{Handling of trailing spaces}

@table @code
@item @strong{MySQL}
Strips all spaces at the end of @code{CHAR} and @code{VARCHAR}
columns. Use a @code{TEXT} column if this behavior is not desired.
@item mSQL
Retains trailing space.
@end table

@noindent
@strong{@code{WHERE} clauses}

@table @code
@item @strong{MySQL}
@strong{MySQL} correctly prioritizes everything (@code{AND} is evaluated
before @code{OR}). To get @code{mSQL} behavior in @strong{MySQL}, use
parentheses (as shown below).
@item mSQL
Evaluates everything from left to right. This means that some logical
calculations with more than three arguments cannot be expressed in any
way. It also means you must change some queries when you upgrade to
@strong{MySQL}. You do this easily by adding parentheses.  Suppose you
have the following @code{mSQL} query:
@example
mysql> SELECT * FROM table WHERE a=1 AND b=2 OR a=3 AND b=4;
@end example
To make @strong{MySQL} evaluate this the way that @code{mSQL} would,
you must add parentheses:
@example
mysql> SELECT * FROM table WHERE (a=1 AND (b=2 OR (a=3 AND (b=4))));
@end example
@end table

@noindent
@strong{Access control}

@table @code
@item @strong{MySQL}
Has tables to store grant (permission) options per user, host and
database. @xref{Privileges}.
@item mSQL
Has a file @file{mSQL.acl} in which you can grant read/write privileges for
users.
@item
@end table

@node Compare PostgreSQL,  , Compare mSQL, Comparisons
@section How @strong{MySQL} compares to PostgreSQL

@code{PostgreSQL} has some more advanced features like user-defined
types, triggers, rules and some transaction support. However, PostgreSQL lacks
many of the standard types and functions from ANSI SQL and ODBC. See the
@uref{http://www.mysql.com/crash-me-choose.htmy, @code{crash-me} web page}
for a complete list of limits and which types and functions are supported
or unsupported.

Normally, @code{PostgreSQL} is a magnitude slower than
@strong{MySQL}. @xref{Benchmarks}.  This is due largely to their
transactions system. If you really need transactions or the rich type
system PostgreSQL offers and you can afford the speed penalty, you
should take a look at PostgreSQL.

@page
@node Users, Contrib, Comparisons, Top
@appendix Some @strong{MySQL} users

@c @uref{http://where?, Some European phonebooks in @strong{MySQL}}

@appendixsec Some Web search engines

@itemize @bullet
@item
@uref{http://www.aaa.com.au, AAA Matilda Web Search}
@item
@uref{http://www.whatsnu.com/, What's New}
@item
@uref{http://www.aladin.de/, Aladin}
@item
@uref{http://www.columbus-finder.de/, Columbus Finder}
@item
@uref{http://www.spider.de/, Spider}
@item
@uref{http://www.blitzsuche.de/, Blitzsuche}
@item
@uref{http://www.indoseek.co.id, Indoseek Indonesia}
@item
@uref{http://www.yaboo.dk/,
Yaboo - Yet Another BOOkmarker}
@item
@uref{http://www.yahoosuck.com, Yahoosuck}
@end itemize

@appendixsec Some Information search engines concentrated on some area

@itemize @bullet
@item
@uref{http://www.jobvertise.com,Jobvertise: Post and search for jobs}
@item
@uref{http://www.musicdatabase.com, The Music Database}
@item
@uref{http://www.soccersearch.com, Fotball (Soccer) search page}
@item
@uref{http://www.headrush.net/takedown, TAKEDOWN - wrestling}
@item
@uref{http://www.lyrics.net, The International Lyrics Network}
@item
@uref{http://TheMatrix.com/~matrix/band_search.phtml,
Musicians looking for other musicians (Free Service)}
@item
@uref{http://www.addall.com/AddBooks/Stores.html,AddALL books searching and price comparison}
@item
@uref{http://www.herbaria.harvard.edu/Data/Gray/gray.html,Harvard's Gray Herbarium Index of Plant Names}
@item
@uref{http://www.csse.monash.edu.au/publications/, Research Publications at Monash University in Australia}
@item
@uref{http://www.game-developer.com/,The Game Development Search Engine}
@item
@uref{http://www.i-run.com/html/cookbook.html,My-Recipe.com; Cookbook at i-run.com}
@end itemize

@appendixsec Some Domain/Internet/Web and related services

@itemize @bullet
@item
@uref{http://www.wix.com/mysql-hosting, Registry of Web providers that
support @strong{MySQL}}
@item
@uref{http://www.yi.org/, Dynamic DNS Services}
@item
@uref{http://www.fdns.net/, Free 3rd level domains}
@item
@uref{http://worldcommunity.com/, Online Database}
@item
@uref{http://www.bigbiz.com, BigBiz Internet Services}
@item
@uref{http://virt.circle.net, The Virt Gazette}
@item
@uref{http://www.california.com, Global InfoNet Inc}
@item
@uref{http://www.webhosters.com, WebHosters - A Guide to WWW Providers}
@item
@uref{http://online.dn.ru, Internet information server}
@item
@uref{http://www.slashdot.org, A pro-Linux/tech news and comment/discussion site}
@item
@uref{http://www.stopbit.com, A technology news site}
@item
@uref{http://www.worldnetla.net, WorldNet Communications - An Internet Services Provider}
@item
@uref{http://www.netizen.com.au/, Netizen: Australian-based web consultancy}
@item
@uref{http://www.trainingpages.co.uk, Search site for training courses in the UK}
@item
@uref{http://chat.nitco.com, Gannon Chat (GPL). Written in Perl and Javascript}
@item
@uref{http://www.addurls.com/,A general links directory}
@item
@uref{http://www.bookmarktracker.com, A web-based bookmark management service}
@item
@uref{http://www.cdrom.com,Walnut Creek CDROM}
@item
@uref{http://www.wwwthreads.org/, WWWThreads; Interactive discussion Forums}
@item
@uref{http://pvmon.portici.enea.it/Meteo, In Italian; Storage data from meteo station}
@item
@uref{http://www.buysell.net/, Online "Person To Person" Auction}
@end itemize

@appendixsec Web sites that use @code{PHP} and @strong{MySQL}

@itemize @bullet
@item
@uref{http://war.jgaa.com:8080/support/index.php3, Jgaa's Internet - Official Support Site} running via apache
@item
@uref{http://io.incluso.com, Ionline - online publication:} @strong{MySQL},
PHP, Java, Web programming, DB development
@item
@uref{http://www.baboo.com, BaBoo(Browse and bookmark). Free web-based bookmark manager and Calendar}
@item
@uref{http://www.courses.pjc.cc.fl.us/Schedule/index.php,Course Schedule System at Pensacola Junior College}
@item
@uref{http://www.devshed.com/resource/advanced/mysql/index.html,A beginners tutoral of how to start using @strong{MySQL}}
@item
@uref{http://www.32bit.com/, 32bit.com ; An extensive shareware / freeware archive}
@item
@uref{http://www.jokes2000.com/, Jokes 2000}
@end itemize

@appendixsec Uncategorized pages

@itemize @bullet
@item
@uref{http://www.feature-showcase.com/htmls/demo_mysql.sql,
AZC.COM's Feature Showcase}
@item
@uref{http://www.teach.org.uk/subjects/trainingcourse/g.html, Course Search}
@item
@uref{http://www.northerbys.com, Northerbys Online Auctions}
@item
@uref{http://www.schiphol.nl/flights/home.htm, Amsterdam Airport Schiphol}
@item
@uref{http://TheMatrix.com/seventhsin/query.phtml, CD database}
@item
@uref{http://TheMatrix.com/~flmm/GEAR.html, Used Audio Gear Database}
@item
@uref{http://www.kiss.de/musik-mueller, Musical note-sheets}
@item
@uref{http://www.bagism.com, Bagism - A John Lennon fan page}
@item
@uref{http://www.selftaught.com/, US Folk art broker}
@item
@uref{http://organizer.net/, Mail reading on the web}
@item
@uref{http://www.mypage.org/, Free home pages on www.somecoolname.mypage.org}
@item
@uref{http://www.schulweb.de/, Der Server f@"ur Schulen im Web (In German)}
@item
@uref{http://www.ald.net/, Auldhaefen Online Services}
@item
@uref{http://www.cary.net/, CaryNET Information Center}
@item
@uref{http://www.dataden.com/, Dataden Computer Systems}
@item
@uref{http://andree.grm.se/, Andr@'emuseet (In Swedish)}
@item
@uref{http://www.him.net/, HOMESITE Internet Marketing}
@item
@uref{http://www.jade-v.com/techinfo.html, Jade-V Network Services }
@item
@uref{http://ww2010.atmos.uiuc.edu/(Gl)/abt/aknw/tech.rxml, Weather
World 2010 Technical Credits@*}
@item
@uref{http://gimp.foebud.org/registry/doc/, About The Gimp plugin
registry}
@item
@uref{http://www.fast-inc.com/Products/Archiver/database.html, Java tool
Archiver technical detail (Slightly optimistic about @strong{MySQL}
ANSI-92 compliance)}
@item
@uref{http://www.gamesdomain.com/cheats/usrcheat.phtml, Games Domain
Cheats Database}
@item
@uref{http://www.kcilink.com/poweredby/, The "Powered By" Page (Kcilink)}
@item
@uref{http://www.netcasting.net/index.whtml, Netcasting}
@item
@uref{http://homepages.tig.com.au/~mjj/nbltips, NBL (Australian National
Basketball League) tipping@*}
@item
@uref{http://www.cgishop.com/, CGI shop}
@item
@uref{http://www.whirlycott.com/, Whirlycott: Website Design}
@item
@uref{http://www.mtp.dk, Museum Tusculanum Press}
@item
@uref{http://csdgi.historie.ku.dk/biblio, Centro Siciliano di Documentazione}
@item
@uref{http://caribou.dyn.ml.org:8000, Quake statistics database}
@item
@uref{http://www.astroforum.ch, Astroforum: Astrologie and related things (in German)}
@item
@uref{http://www.opendebate.com, OpenDebate - Interactive Polls & Open Discussion}
@item
@uref{http://vermeer.organik.uni-erlangen.de/dissertationen/, Online chemical dissertation server}
@item
@uref{http://www.freschinfo.com, FreSch! The Free Scholarship Search Service}
@item
@uref{http://www.nada.kth.se/~staffanu/pinball, Stockholm Pinball Locator}
@item
@uref{http://www.hek.com, HEK A construction company}
@item
@uref{http://www.nbi.nl, Elsevier Bussines Information}
@item
@uref{http://vaccination.medicallink.se/, Medical Links (Using Coldfusion and
@strong{MySQL})}
@item
@uref{http://www.joblink-usa.com, Search for jobs & people at JobLink-USA}
@item
@uref{http://www.linux-magazin.de/newsflash/, Daily news about Linux in German language}
@item
@uref{http://www.skydive.net/competfs, Competition Formation Skydiving}
@item
@uref{http://www.galaxy-net.net/Galaxy-NET Telecommunications,
E-commerce and internal accounting}
@item
@uref{http://www.borsen.dk/,
Denmark's leading business daily newspaper B@o{}rsen}
@item
@uref{http://tmmm.simplenet.com/indb/, The Internet NES Database}
@item
@uref{http://www.russia.cz, Travel agency in Prague in 3 languages}
@item
@uref{http://www.linkstation.de, Linkstation}
@item
@uref{http://www.peoplestaff.com, Searchable online database at Peoplestaff}
@item
@uref{http://www.dreamhorse.com, A searchable database system for horse classified ads for sale and at stud.}
@item
@uref{http://pootpoot.com/,The Poot site}
@item
@uref{http://grateful.net/hw_html/,"Playin' in the LAN"; a network monitoring suite}
@item
@uref{http://www-usappc.hoffman.army.mil/index.html,U.S. Army Publishing Agency}
@item
@uref{http://www.nekretnine.co.yu/,Realestate handling in Yugoslavia}
@item
@uref{http://demo.cpsoft.com/pims/devFAQ.html, PIMS; a Patient Information Management System}
@item
@uref{http://cpsoft.com,Pilkington Software Inc}
@item
@uref{http://www.betazine.com,Betazine - The Ultimate Online Beta Tester's Magazine}
@item
@uref{http://www.no-quarter.org/,A Vietnam Veteran's Memorial (The Wall) database.}
@item
@uref{http://www.gamers-union.com/,Gamer's Union specializes inauctions of used & out of print gaming material}
@item
@uref{http://www.montereyhigh.com/office/dbul.php3, A daily bulletin at Monterey High school}
@end itemize

@appendixsec Some MySQL consultants

@itemize @bullet
@item
@uref{http://www.ayni.com, Ayni AG}
@item
@uref{http://worldcommunity.com/, Online Database}
@item
@uref{http://www2.dataguard.no/,DataGuard (Uses @strong{MySQL} and PHP)}
@item
@uref{http://wwits.net/programs/mysql.phtml, WWITS (Uses @strong{MySQL} and PHP)}
@item
@uref{http://www.worldcommunity.com/, WCN - The World Community Network}
@item
@uref{http://www.chipcastle.com, Chip Castle Dot Com Inc}
@end itemize

@appendixsec Programming

@itemize @bullet
@item
@uref{http://www.perl.org/cpan-testers, The Perl CPAN Testers results page}
@end itemize

Send any additions to this list to @email{webmaster@@mysql.com}.

@page
@node Contrib, Credits, Users, Top
@appendix Contributed programs

Many users of @strong{MySQL} have contributed @emph{very} useful support
tools and addons.

@ifclear web
A list of what is available at @uref{http://www.mysql.com/Contrib}
(or any mirror) is shown below.
If you want to build @strong{MySQL} support for the Perl @code{DBI}/@code{DBD}
interface, you should fetch the @code{Data-Dumper}, @code{DBI}, and
@code{Msql-Mysql-modules} files and install them.
@xref{Perl support}.
@end ifclear


@uref{http://www.mysql.com/Contrib/00-README, 00-README}
This listing.
 
@appendixsec API's

@itemize @bullet
@item Perl modules
@itemize @bullet
@item @uref{http://www.mysql.com/Contrib/Data-Dumper-2.09.tar.gz, Data-Dumper-2.09.tar.gz}
Perl @code{Data-Dumper} module.  Useful with @code{DBI}/@code{DBD} support.

@item @uref{http://www.mysql.com/Contrib/DBI-1.08.tar.gz, DBI-1.08.tar.gz}
Perl @code{DBI} module.

@item @uref{http://www.mysql.com/Contrib/KAMXbase1.0.tar.gz,KAMXbase1.0.tar.gz}
Convert between @file{.dbf} files and @strong{MySQL} tables.  Perl
module written by Pratap Pereira @email{pereira@@ee.eng.ohio-state.edu},
extened by Kevin A. McGrail @email{kmcgrail@@digital1.peregrinehw.com}.
This converter can handle MEMO fields.

@item @uref{http://www.mysql.com/Contrib/Msql-Mysql-modules-1.2018.tar.gz, Msql-Mysql-modules-1.2018.tar.gz}
Perl @code{DBD} module to access mSQL and @strong{MySQL} databases..

@item @uref{http://www.mysql.com/Contrib/ Data-ShowTable-3.3.tar.gz,  Data-ShowTable-3.3.tar.gz}
Perl @code{Data-ShowTable} module.  Useful with @code{DBI}/@code{DBD} support.
@end itemize

@item JDBC
@itemize @bullet
@item @uref{http://www.mysql.com/Contrib/mm.mysql.jdbc-1.0.tar.gz, mm.mysql.jdbc-1.0.t
ar.gz}
New java JDBC driver for @strong{MySQL}. This is a production release
and is actively developed. By Mark Matthews
(@email{mmatthew@@ecn.purdue.edu}). This driver has a LGPL license. You
can always find the newest driver at
@uref{http://www.worldserver.com/~mmatthew/mysql/}.
@item @uref{http://www.mysql.com/Contrib/twz1jdbcForMysql-1.0.4-GA.tar.gz, twz1jdbcForMysql-1.0.4-GA.tar.gz}
The twz driver: A type 4 JDBC driver by Terrence W. Zellers
@email{zellert@@voicenet.com}.  This is commercial but is free for private
and educational use. You can always find the latest driver at
@uref{http://www.voicenet.com/~zellert/tjFM/}.
@end itemize

@item @uref{http://www.mysql.com/Contrib/mysql-c++-0.02.tar.gz, mysql-c++-0.02.tar.gz}
@strong{MySQL} C++ wrapper library. By Roland Haenel,
@email{rh@@ginster.net}.

@item @uref{http://www.mysql.com/Contrib/mysql++.64.1.1.b.tar.gz, mysql++.64.1.1.b.tar.gz}
@strong{MySQL} C++ API (More than just a wrapper library). Originally by
@email{kevina@@clark.net}. Nowadays maintained by TCX.

@item @uref{http://www.mysql.com/Contrib/delphi-interface.gz, delphi-interface.g
z}
Delphi interface to @code{libmysql.dll}, by Blestan Tabakov,
@email{root@@tdg.bis.bg}.

@item @uref{http://www.mysql.com/Contrib/DelphiMySQL2.zip, DelphiMySQL2.zip}
Delphi interface to @code{libmysql.dll}, by @email{bsilva@@umesd.k12.or.us}

@item @uref{http://www.mysql.com/Contrib/JdmMysqlDriver-0.1.0.tar.gz,JdmMysqlDriver-0.1.0.tar.gz}
A VisualWorks 3.0 Smalltalk driver for @strong{MySQL}. By
@email{joshmiller@@earthlink.net}

@item @uref{http://www.mysql.com/Contrib/Db.py, Db.py}
Python module with caching. By @email{gandalf@@rosmail.com}.

@item @uref{http://www.mysql.com/Contrib/MySQLmodule-1.4.tar.gz, MySQLmodule-1.4.tar.gz}
Python interface for the @strong{MySQL}. By Joseph Skinner @email{joe@@earthlight.co.nz};  Modified by Joerg Senekowitsch @email{senekow@@ibm.net}

@item @uref{http://www.mysql.com/Contrib/mysql_mex.tar.gz, mysql_mex.tar.gz}
An interface program for the Matlab program by MathWorks.
 
@item @uref{http://www.mysql.com/Contrib/mysqltcl-1.53.tar.gz, mysqltcl-1.53.tar.gz}
Tcl interface for @strong{MySQL}. Based on @file{msqltcl-1.50.tar.gz}.
Updated by Tobias Ritzau, @email{tobri@@ida.liu.se}.

@item @uref{http://www.mysql.com/Contrib/MyC.zip, MyC.zip}
A Visual Basic-like API, by Ed Carp.
 
@item @uref{http://www.mysql.com/Contrib/sqlscreens-1.0.1.tar.gz, sqlscreens-1.0.1.tar.gz}
TCL/TK code to generate database screens. By Jean-Francois Dockes.

@item @uref{http://www.mysql.com/Contrib/Vdb-dflts-2.1.tar.gz, Vdb-dflts-2.1.tar.gz}
This is a new version of a set of library utilities intended
to provide a generic interface to SQL database engines such that your
application becomes a 3-tiered application.  The advantage is that you
can easily switch between and move to other database engines by
implementing one file for the new backend without needing to make any
changes to your applications. By @email{damian@@cablenet.net}.

@item @uref{http://www.mysql.com/Contrib/DbFramework-1.10.tar.gz, DbFramework-1.10.tar.gz}
DbFramework is a collection of classes for manipulating @strong{MySQL}
databases.  The classes are loosely based on the CDIF Data Model
Subject Area. By Paul Sharpe @email{paul@@miraclefish.com}.

@item @uref{http://www.mysql.com/Contrib/pike-mysql-1.4.tar.gz, pike-mysql-1.4.tar.gz}
@strong{MySQL} module for pike. For use with the Roxen web server.

@item @uref{http://www.mysql.com/Contrib/squile.tar.gz, squile.tar.gz}
Module for @code{guile} that allows @code{guile} to interact with SQL
databases. By Hal Roberts.
@end itemize


@appendixsec  Clients

@itemize @bullet
@item Graphical clients
@itemize @bullet
@item @uref{http://www.mysql.com/Contrib/kmysqladmin-0.1.tar.gz, kmysqladmin-0.1.tar.gz}
An administration tool for the @strong{MySQL} server using QT / KDE.  Tested
only on Linux.

@item @uref{http://www.mysql.com/Contrib/Admin.tar.gz, Java client with Swing}
By Fredy Fischer, @email{se-afs@@dial.eunet.ch}
@item @uref{http://www.mysql.com/Contrib/mysqlwinadmn.zip, mysqlwinadmn.zip}
Win32 GUI (binary only) to administrate a database, by David B. Mansel,
@email{david@@zhadum.org}.

@item @uref{http://www.mysql.com/Contrib/xmysqladmin-1.0.tar.gz, xmysqladmin-1.0.tar.gz}
A front end to the @strong{MySQL} database engine.  It allows reloads,
status check, process control, isamchk, grant/revoke privileges,
creating databases, dropping databases, create, alter, browse and drop
tables.  Originally by Gilbert Therrien, @email{gilbert@@ican.net} but
now in public domain and supported by TcX.

@item @uref{http://www.mysql.com/Contrib/xmysql-1.9.tar.gz, xmysql-1.9.tar.gz}
@item @uref{http://web.wt.net/~dblhack, xmysql home page}
A front end to the @strong{MySQL} database engine. It allows for simple
queries and table maintenance, as well as batch queries. By Rick
Mehalick, @email{dblhack@@wt.net}.
Requires @uref{http://bragg.phys.uwm.edu/xforms,xforms 0.88} to work.
@end itemize

@item Web clients
@itemize @bullet
@item @uref{http://www.mysql.com/Contrib/mysqladmin-atif-1.0.tar.gz, mysqladmin-atif-1.0.tar.gz}
WWW @strong{MySQL} administrator for the @code{user,} @code{db} and
@code{host} tables.  By Tim Sailer, modified by Atif Ghaffar
@email{aghaffar@@artemedia.ch}.

@item @uref{http://www.mysql.com/Contrib/mysql-webadmin-1.0a8-rz.tar.gz, mysql-webadmin-1.0a8-rz.tar.gz}
A tool written in PHP-FI to administrate @strong{MySQL} databases
remotely over the web within a Web-Browser. By Peter Kuppelwieser,
@email{peter.kuppelwieser@@kantea.it}. Updated by Wim Bonis, bonis@@kiss.de.
Not maintained anymore!

@item @uref{http://www.mysql.com/Contrib/mysqladm.tar.gz, mysqladm.tar.gz}
@strong{MySQL} Web Database Administration written in Perl.  By Tim
Sailer.

@item @uref{http://www.mysql.com/Contrib/mysqladm-2.tar.gz, mysqladm-2.tar.gz}
Updated version of @file{mysqladm.tar.gz}, by High Tide.

@item @uref{http://www.mysql.com/Contrib/myadmin-0.4.tar.gz, myadmin-0.4.tar.gz}
@item @uref{http://myadmin.cheapnet.net/, MyAdmin home page}
A web based mysql administrator by Mike Machado.

@item @uref{http://www.mysql.com/Contrib/phpMyAdmin_2.0.1.tar.gz,phpMyAdmin_2.0.1.tar.gz}
A set of PHP3-scripts to adminstrate MySQL over the WWW.

@item @uref{http://www.htmlwizard.net/phpMyAdmin/, phpMyAdmin home page}
A PHP3 tool in the spirit of mysql-webadmin, by Tobias Ratschiller, tobias@@dnet.it

@item @uref{http://www.mysql.com/Contrib/useradm.tar.gz, useradm.tar.gz}
@strong{MySQL} administrator in PHP. By Ofni Thomas
@email{othomas@@vaidsystems.com}.
@end itemize
@end itemize


@appendixsec Web tools

@itemize @bullet
@item @uref{http://www.mysql.com/Contrib/ascend-radius-mysql-0.4.3.patch.gz,ascend-radius-mysql-0.4.3.patch.gz}
This is authentication and logging patch using @strong{MySQL} for
Ascend-Radius. By @email{takeshi@@SoftAgency.co.jp}.

@item @uref{http://www.odbsoft.com/cook/sources.htm}
This package has various functions for generating html code from an SQL
table structure and for generating SQL statements (Select, Insert,
Update, Delete) from an html form. You can build a complete forms
interface to an SQL database (query, add, update, delete) without any
programming!  By Marc Beneteau, @email{marc@@odbsoft.com}.

@item @uref{http://www.mysql.com/Contrib/sqlhtml.tar.gz, sqlhtml.tar.gz}
SQL/HTML is an HTML database manager for @strong{MySQL} using @code{DBI} 1.06.

@item @uref{http://www.mysql.com/Contrib/UdmSearch-2.0.tar.gz,UdmSearch-2.0.tar.gz}
A @strong{MySQL}- and PHP- based search engine over http. By
Alexander I. Barkov @email{bar@@izhcom.ru}.

@item @uref{http://www.mysql.com/Contrib/wmtcl.doc, wmtcl.doc}
@item @uref{http://www.mysql.com/Contrib/wmtcl.lex, wmtcl.lex}
With this you can write HTML files with inclusions of TCL code. By
@email{vvs@@scil.npi.msu.su}.

@item @uref{http://www.mysql.com/Contrib/www-sql-0.5.7.lsm, www-sql-0.5.7.lsm}
@item @uref{http://www.mysql.com/Contrib/www-sql-0.5.3.md5, www-sql-0.5.3.md5}
@item @uref{http://www.mysql.com/Contrib/www-sql-0.5.7.tar.gz, www-sql-0.5.7.tar.gz}
A CGI program that parses an HTML file containing special tags, parses
them and inserts data from a @strong{MySQL} database.

@item @uref{http://www.mysql.com/Contrib/genquery.zip, genquery.zip}
Perl SQL database interface package for html.

@item @uref{http://www.mysql.com/Contrib/cgi++-0.2.tar.gz, cgi++-0.2.tar.gz}
A CGI wrapper by Sasha Pachev.
@end itemize


@appendixsec Authentication tools

@itemize @bullet
@item @uref{http://www.mysql.com/Contrib/checkpassword-0.76-mysql-0.3.2.patch.gz,checkpassword-0.76-mysql-0.3.2.patch.gz}
MySQL authentication patch for QMAIL and checkpassword. These are
useful for management user(mail,pop account) by @strong{MySQL}.
By @email{takeshi@@SoftAgency.co.jp}

@item @uref{http://www.mysql.com/Contrib/jradius-diff.gz, jradius-diff.gz}
@strong{MySQL} support for Livingston's Radius 2.01. Authentication and
Accounting. By Jose de Leon, @email{jdl@@thevision.net}

@item @uref{http://www.mysql.com/Contrib/mod_auth_mysql-2.20.tar.gz, mod_auth_mysql-2.20.tar.gz}
Apache authentication module for @strong{MySQL}. By Zeev Suraski,
@email{bourbon@@netvision.net.il}.

@strong{Please} register this module at:
@url{http://bourbon.netvision.net.il/mysql/mod_auth_mysql/register.html}. The
registering information is only used for statistical purposes and will
encourage further development of this module!

@item @uref{http://www.mysql.com/Contrib/mod_log_mysql-1.05.tar.gz, mod_log_mysql-1.05.tar.gz}
@strong{MySQL} logging module for Apache. By Zeev Suraski,
@email{bourbon@@netvision.net.il}.

@item @uref{http://www.mysql.com/Contrib/mypasswd-2.0.tar.gz, mypasswd-2.0.tar.gz}
Extra for @code{mod_auth_mysql}. This is a little tool that allows you
to add/change user records storing group and/or password entries in
@strong{MySQL} tables. By Harry Brueckner, @email{brueckner@@respublica.de}.

@item @uref{http://www.mysql.com/Contrib/mysql-passwd.README, mysql-passwd.README}
@item @uref{http://www.mysql.com/Contrib/mysql-passwd-1.2.tar.gz, mysql-passwd-1.2.tar.gz}
Extra for @code{mod_auth_mysql}. This is a two-part system for use with
@code{mod_auth_mysql}.

@item @uref{http://www.mysql.com/Contrib/pam_mysql.tar.gz, pam_mysql.tar.gz}
This module authenticates users via @code{pam}, using @strong{MySQL}.

@item @uref{http://www.mysql.com/Contrib/nsapi_auth_mysql.tar, nsapi_auth_mysql.tar}
Netscape Web Server API (NSAPI) functions to authenticate (BASIC) users
against @strong{MySQL} tables. By Yuan John Jiang.

@item @uref{http://www.mysql.com/Contrib/qmail-1.03-mysql-0.3.2.patch.gz,qmail-1.03-mysql-0.3.2.patch.gz}
Patch for qmail to authenticate users from a @strong{MySQL} table.
@end itemize


@appendixsec Converters

@itemize @bullet
@item @uref{http://www.mysql.com/Contrib/dbf2mysql-1.10d.tar.gz, dbf2mysql-1.10d.tar.gz}
Convert between @file{.dbf} files and @strong{MySQL} tables. By Maarten
Boekhold, @email{boekhold@@cindy.et.tudelft.nl}, and Michael Widenius.
This converter can't handle MEMO fields.

@item @uref{http://www.mysql.com/Contrib/dbf2mysql.zip, dbf2mysql.zip}
Convert between FoxPro @file{.dbf} files and @strong{MySQL} tables on Win32.
By Alexander Eltsyn, @email{ae@@nica.ru} or @email{ae@@usa.net}.

@item @uref{http://www.mysql.com/Contrib/dump2h-1.20.gz, dump2h-1.20.gz}
Convert from @code{mysqldump} output to a C header file. By Harry Brueckner,
@email{brueckner@@mail.respublica.de}.

@item @uref{http://www.mysql.com/Contrib/exportsql.txt, exportsql.txt}
A script that is similar to @code{access_to_mysql.txt}, except that this
one is fully configurable, has better type conversion (including
detection of @code{TIMESTAMP} fields), provides warnings and suggestions
while converting, quotes @strong{all} special characters in text and
binary data, and so on.  It will also convert to @code{mSQL} v1 and v2,
and is free of charge for anyone. See
@uref{http://www.cynergi.net/prod/exportsql/} for latest version. By
Pedro Freire, @email{support@@cynergi.net}.  Note: Doesn't work with
Access2!
@item @uref{http://www.mysql.com/Contrib/access_to_mysql.txt, access_to_mysql.txt}
Paste this function into an Access module of a database which has the
tables you want to export. See also @code{exportsql}. By Brian Andrews.
Note: Doesn't work with Access2!

@item @uref{http://www.mysql.com/Contrib/importsql.txt, importsql.txt}
A script that does the exact reverse of @code{exportsql.txt}.  That is,
it imports data from @strong{MySQL} into an Access database via
ODBC. This is very handy when combined with exportSQL, since it lets you
use Access for all DB design and administration, and synchronize with
your actual @strong{MySQL} server either way. Free of charge. See
@uref{http://www.netdive.com/freebies/importsql/} for any updates.
Created by Laurent Bossavit of NetDIVE.
@strong{Note:} Doesn't work with Access2!

@item @uref{http://www.mysql.com/Contrib/sqlconv.pl, sqlconv.pl}
A simple script that can be used to copy fields from one @strong{MySQL} table to
another in bulk. Basically, you can run @code{mysqldump} and pipe it to
the @code{sqlconv.pl} script and the script will parse through the
@code{mysqldump} output and will rearrange the fields so they can be
inserted into a new table. An example is when you want to create a new
table for a different site you are working on, but the table is just a
bit different (ie - fields in different order, etc.).
By Steve Shreeve.
@end itemize

@appendixsec Using MySQL with other products

@itemize @bullet
@item @uref{http://www.mysql.com/Contrib/emacs-sql-mode.tar.gz, emacs-sql-mode.tar.gz}
Raw port of a SQL mode for XEmacs. Supports completion. Original by
Peter D. Pezaris @email{pez@@atlantic2.sbi.com} and partial
@strong{MySQL} port by David Axmark.

@item @uref{http://www.mysql.com/Contrib/MyAccess.mda, MyAccess.mda}
MyAccess is an AddIn for Access 97 and handles a lot of maintanance work
for @strong{MySQL} databases.
@uref{http://www.mysql.com/Contrib/MyAccess-0.90.readme,
MyAccess-readme}.  By Hubertus Hiden.

@item @uref{http://www.mysql.com/Contrib/radius-0.3.tar.gz, radius-0.3.tar.gz}
Patches for @code{radiusd} to make it support @strong{MySQL}. By Wim Bonis,
@email{bonis@@kiss.de}.
@end itemize

@appendixsec Useful tools

@itemize @bullet
@item @uref{http://www.mysql.com/Contrib/mysql_watchdog.pl, mysql_watchdog.pl}
Monitor the @strong{MySQL} daemon for possible lockups. By Yermo Lamers,

@email{yml@@yml.com}.
@item @uref{http://www.mysql.com/Contrib/mysqltop.tar.gz, mysqltop.tar.gz}
Shows and updates the process-list in a fixed time interleave. By Thomas Wana.

@item @uref{http://www.mysql.com/Contrib/mysqlsync, mysqlsync}.
A perl script to keep remote copies of a @strong{MySQL} database in sync with a
central master copy. By Mark Jeftovic.  @email{markjr@@easydns.com}
@end itemize

@appendixsec Uncategorized

@itemize @bullet
@item @uref{http://www.mysql.com/Contrib/findres.pl, findres.pl}
Find reserved words in tables. By Nem W Schlecht.

@item @uref{http://www.mysql.com/Contrib/handicap.tar.gz, handicap.tar.gz}
Performance handicapping system for yachts. Uses PHP. By
@email{rhill@@stobyn.ml.org}.

@item @uref{http://www.mysql.com/Contrib/hylalog-1.0.tar.gz, hylalog-1.0.tar.gz}
Store @code{hylafax} outgoing faxes in a @strong{MySQL} database. By Sinisa
Milivojevic, @email{sinisa@@coresinc.com}.

@item @uref{http://www.mysql.com/Contrib/mrtg-mysql-1.0.tar.gz, mrtg-mysql-1.0.tar.gz}
@strong{MySQL} status plotting with MRTG, by Luuk de Boer, @email{luuk@@wxs.nl}.

@item @uref{http://www.mysql.com/Contrib/wuftpd-2.4.2.18-mysql_support.2.tar.gz, wuftpd-2.4.2.18-mysql_support.2.tar.gz}
Patches to add logging to @strong{MySQL} for WU-ftpd. By Zeev Suraski,
@email{bourbon@@netvision.net.il}.

@item @uref{http://www.mysql.com/Contrib/Old-Versions, Old-Versions}
Previous versions of things found here that you probably won't be
interested in.
@end itemize


@page
@node Credits, News, Contrib, Top
@appendix Contributors to @strong{MySQL}

Contributors to the @strong{MySQL} distribution are listed below, in
somewhat random order:

@table @asis
@item Michael (Monty) Widenius
Has written the following parts of @strong{MySQL}:
@itemize @bullet
@item
All the main code in @code{mysqld}.
@item
New functions for the string library.
@item
Most of the @code{mysys} library.
@item
The @code{NISAM} and @code{MYISAM} libraries (B-tree index file
handlers with index compression and different record formats).
@item
The @code{heap} library. A memory table system with our superior full dynamic
hashing. In use since 1981 and published around 1984.
@item
The @code{replace} program (look into it, it's COOL!).
@item
@strong{MyODBC}, the ODBC driver for Windows95.
@item
Fixing bugs in MIT-pthreads to get it to work for @strong{MySQL}. And
also Unireg, a curses-based application tool with many utilities.
@item
Porting of @code{mSQL} tools like @code{msqlperl}, @code{DBD}/@code{DBI} and
@code{DB2mysql}.
@item
Most parts of crash-me and the @strong{MySQL} benchmarks.
@end itemize
@item David Axmark
@itemize @bullet
@item
Coordinator and main writer for the @strong{Reference Manual}, including
enhancements to @code{texi2html}. Also automatic website updating from
this manual.
@item
Autoconf, Automake and @code{libtool} support.
@item
The licensing stuff.
@item
Parts of all the text files.  (Nowadays only the @file{README} is
left. The rest ended up in the manual.)
@item
Our Mail master.
@item
Lots of testing of new features.
@item
Our in-house ``free'' software lawyer.
@item
Mailing list maintainer (who never has the time to do it right...)
@item
Our original portability code (more than 10 years old now). Nowadays
only some parts of @code{mysys} are left.
@item
Someone for Monty to call in the middle of the night when he just got
that new feature to work. :-)
@end itemize
@item Paul DuBois
Help with making the Reference Manual correct and understandable.
@item Gianmassimo Vigazzola @email{qwerg@@mbox.vol.it} or @email{qwerg@@tin.it}
The initial port to Win32/NT.
@item Kim Aldale
Rewriting Monty's and David's attempts at English into English.
@item Allan Larsson (The BOSS at TcX)
For all the time he has allowed Monty to spend on this ``maybe useful''
tool (@strong{MySQL}). Dedicated user (and bug finder) of Unireg & @strong{MySQL}.
@item Per Eric Olsson
For more or less constructive criticism and real testing of the dynamic
record format.
@item Irena Pancirov @email{irena@@mail.yacc.it}
Win32 port with Borland compiler.
@item David J. Hughes
For the effort to make a shareware SQL database. We at TcX started with
@code{mSQL}, but found that it couldn't satisfy our purposes so instead we
wrote a SQL interface to our application builder Unireg.  @code{mysqladmin}
and @code{mysql} are programs that were largely influenced by their
@code{mSQL} counterparts. We have put a lot of effort into making the
@strong{MySQL} syntax a superset of @code{mSQL}. Many of the APIs ideas are
borrowed from @code{mSQL} to make it easy to port free @code{mSQL} programs
to @strong{MySQL}. @strong{MySQL} doesn't contain any code from @code{mSQL}.
Two files in the distribution (@file{client/insert_test.c} and
@file{client/select_test.c}) are based on the corresponding (non-copyrighted)
files in the @code{mSQL} distribution, but are modified as examples showing
the changes necessary to convert code from @code{mSQL} to @strong{MySQL}.
(@code{mSQL} is copyrighted David J. Hughes.)
@item Fred Fish
For his excellent C debugging and trace library. Monty has made a number
of smaller improvements to the library (speed and additional options).
@item Richard A. O'Keefe
For his public domain string library.
@item Henry Spencer
For his regex library, used in @code{WHERE column REGEXP regexp}.
@item Free Software Foundation
From whom we got an excellent compiler (@code{gcc}), the @code{libc} library
(from which we have borrowed @file{strto.c} to get some code working in Linux)
and the @code{readline} library (for the @code{mysql} client).
@item Free Software Foundation & The XEmacs development team
For a really great editor/environment used by almost everybody at TcX/detron.
@item Igor Romanenko @email{igor@@frog.kiev.ua}
@code{mysqldump} (previously @code{msqldump}, but ported and enhanced by
Monty).
@item Tim Bunce, Alligator Descartes
For the @code{DBD} (Perl) interface.
@item Andreas Koenig @email{a.koenig@@mind.de}
For the Perl interface to @strong{MySQL}.
@item Eugene Chan @email{eugene@@acenet.com.sg}
For porting PHP to @strong{MySQL}.
@item Michael J. Miller Jr. @email{mke@@terrapin.turbolift.com}
For the growing @strong{MySQL} user manual. And a lot of
spelling/language fixes for the FAQ.
@item Giovanni Maruzzelli @email{maruzz@@matrice.it}
For porting iODBC (Unix ODBC).
@item Chris Provenzano
Portable user level pthreads. From the copyright: This product includes
software developed by Chris Provenzano, the University of California,
Berkeley, and contributors.  We are currently using version 1_60_beta6
patched by Monty (see @file{mit-pthreads/Changes-mysql}).
@item Xavier Leroy @email{Xavier.Leroy@@inria.fr}
The author of LinuxThreads (used by @strong{MySQL} on Linux).
@item Zarko Mocnik @email{zarko.mocnik@@dem.si}
Sorting for Slovenian language and the @file{cset.tar.gz} module that makes
it easier to add other character sets.
@item "TAMITO" @email{tommy@@valley.ne.jp}
The @code{_MB} character set macros and the ujis and sjis character sets.
@item Yves Carlier @email{Yves.Carlier@@rug.ac.be}
@code{mysqlaccess}, a program to show the access rights for a user.
@item Rhys Jones @email{rhys@@wales.com} (And GWE Technologies Limited)
For the JDBC, a module to extract data from @strong{MySQL} with a Java
client.
@item Dr Xiaokun Kelvin ZHU @email{X.Zhu@@brad.ac.uk}
Further development of the JDBC driver and other @strong{MySQL}-related
Java tools.
@item James Cooper @email{pixel@@organic.com}
For setting up a searchable mailing list archive at his site.
@item Rick Mehalick @email{Rick_Mehalick@@i-o.com}
For @code{xmysql}, a graphical X client for @strong{MySQL}.
@item Doug Sisk @email{sisk@@wix.com}
For providing RPM packages of @strong{MySQL} for RedHat Linux.
@item Diemand Alexander V. @email{axeld@@vial.ethz.ch}
For providing RPM packages of @strong{MySQL} for RedHat Linux/Alpha.
@item Antoni Pamies Olive @email{toni@@readysoft.es}
For providing RPM versions of a lot of @strong{MySQL} clients for Intel
and SPARC.
@item Jay Bloodworth @email{jay@@pathways.sde.state.sc.us}
For providing RPM versions for @strong{MySQL} 3.21 versions.
@item Jochen Wiedmann @email{wiedmann@@neckar-alb.de}
For maintaining the Perl @code{DBD::mysql} module.
@item Therrien Gilbert @email{gilbert@@ican.net}, Jean-Marc Pouyot @email{jmp@@scalaire.fr}
French error messages.
@item Petr snajdr, @email{snajdr@@pvt.net}
Czech error messages.
@item Jaroslaw Lewandowski @email{jotel@@itnet.com.pl}
Polish error messages.
@item Miguel Angel Fernandez Roiz
Spanish error messages.
@item Roy-Magne Mo @email{rmo@@www.hivolda.no}
Norwegian error messages and testing of 3.21.#.
@item Timur I. Bakeyev @email{root@@timur.tatarstan.ru}
Russian error messages.
@item brenno@@dewinter.com
Italian error messages.
@item Dirk Munzinger @email{dirk@@trinity.saar.de}
German error messages.
@item Billik Stefan @email{billik@@sun.uniag.sk}
Slovak error messages.
@item David Sacerdote @email{davids@@secnet.com}
Ideas for secure checking of DNS hostnames.
@item Wei-Jou Chen @email{jou@@nematic.ieo.nctu.edu.tw}
Some support for Chinese(BIG5) characters.
@item Zeev Suraski @email{bourbon@@netvision.net.il}
@code{FROM_UNIXTIME()} time formatting, @code{ENCRYPT()} functions, and
@code{bison} adviser.
Active mailing list member.
@item Luuk de Boer @email{luuk@@wxs.nl}
Ported (and extended) the benchmark suite to @code{DBI}/@code{DBD}. Have
been of great help with @code{crash-me} and running benchmarks. Some new
date functions. The mysql_setpermissions script.
@item Jay Flaherty @email{fty@@utk.edu}
Big parts of the Perl @code{DBI}/@code{DBD} section in the manual.
@item Paul Southworth @email{pauls@@etext.org}, Ray Loyzaga @email{yar@@cs.su.oz.au}
Proof-reading of the Reference Manual.
@item Alexis Mikhailov @email{root@@medinf.chuvashia.su}
User definable functions (UDFs); @code{CREATE FUNCTION} and
@code{DROP FUNCTION}.
@item Andreas F. Bobak @email{bobak@@relog.ch}
The @code{AGGREGATE} extension to UDF functions.
@item Ross Wakelin @email{R.Wakelin@@march.co.uk}
Help to set up InstallShield for MySQL-Win32.
@item Jethro Wright III @email{jetman@@li.net}
The @file{libmysql.dll} library.
@item James Pereria @email{jpereira@@iafrica.com}
Mysqlmanager, a Win32 GUI tool for administrating @strong{MySQL}.
@item Curt Sampson @email{cjs@@portal.ca}
Porting of MIT-pthreads to NetBSD/Alpha and NetBSD 1.3/i386.
@item Sinisa Milivojevic @email{sinisa@@coresinc.com}
Compression (with @code{zlib}) to the client/server protocol.
Perfect hashing for the lexical analyzer phase.
@item Antony T. Curtis @email{antony.curtis@@olcs.net}
Porting of @strong{MySQL} to OS/2.
@end table

Other contributors, bugfinders and testers: James H. Thompson, Maurizio
Menghini, Wojciech Tryc, Luca Berra, Zarko Mocnik, Wim Bonis, Elmar
Haneke, @email{jehamby@@lightside}, @email{psmith@@BayNetworks.COM},
@email{duane@@connect.com.au}, Ted Deppner @email{ted@@psyber.com},
Mike Simons, Jaakko Hyv@"atti.

And lots of bug report/patches from the folks on the mailing list.

And a big tribute to those that help us answer questions on the
@code{mysql@@lists.mysql.com} mailing list:

@table @asis
@item Daniel Koch @email{dkoch@@amcity.com}
Irix setup.
@item Luuk de Boer @email{luuk@@wxs.nl}
Benchmark questions.
@item Tim Sailer @email{tps@@users.buoy.com}
@code{DBD-mysql} questions.
@item Boyd Lynn Gerber @email{gerberb@@zenez.com}
SCO related questions.
@item Richard Mehalick @email{RM186061@@shellus.com}
@code{xmysql}-releated questions and basic installation questions.
@item Zeev Suraski @email{bourbon@@netvision.net.il}
Apache module configuration questions (log & auth), PHP-related
questions, SQL syntax related questions and other general questions.
@item Francesc Guasch @email{frankie@@citel.upc.es}
General questions.
@item Jonathan J Smith @email{jsmith@@wtp.net}
Questions pertaining to OS-specifics with Linux, SQL syntax, and other
things that might be needing some work.
@item David Sklar @email{sklar@@student.net}
Using @strong{MySQL} from PHP and Perl.
@item Alistair MacDonald @email{A.MacDonald@@uel.ac.uk}
Not yet specified, but is flexible and can handle Linux and maybe HP-UX.
Will try to get user to use @code{mysqlbug}.
@item John Lyon @email{jlyon@@imag.net}
Questions about installing @strong{MySQL} on Linux systems, using either
@file{.rpm} files, or compiling from source.
@item Lorvid Ltd. @email{lorvid@@WOLFENET.com}
Simple billing/license/support/copyright issues.
@item Patrick Sherrill @email{patrick@@coconet.com}
ODBC and VisualC++ interface questions.
@item Randy Harmon @email{rjharmon@@uptimecomputers.com}
@code{DBD}, Linux, some SQL syntax questions.
@end table

@node News, Bugs, Credits, Top
@appendix @strong{MySQL} change history

Note that we tend to update the manual at the same time we implement new
things to @strong{MySQL}. If you find a version listed below that you can't
find on the
@uref{http://www.mysql.com/download.html,@strong{MySQL} download page},
this means that the version has not yet been released!

@menu
* News-3.23.x::                 Changes in release 3.23.x (Not released yet)
* News-3.22.x::                 Changes in release 3.22.x (Recommended version)
* News-3.21.x::                 Changes in release 3.21.x
* News-3.20.x::                 Changes in release 3.20.x
* News-3.19.x::                 Changes in release 3.19.x
@end menu

@node News-3.23.x, News-3.22.x, News, News
@appendixsec Changes in release 3.23.x  (Not released yet)

The major difference between release 3.23 and releases 3.22 and 3.21 is that
3.23 contains a new ISAM library (MYISAM), which is more tuned for SQL
than the old ISAM was.

The 3.23 release is under development, and things will be added at a
fast pace to it.  For the moment we recommend this version only for
users that desperately need a new feature that is found only in this
release (like big file support and machine-independent tables).  (Note
that all new functionality in MySQL 3.23 is extensively tested, but as
this release involves much new code, it's difficult to test everything).  This
version should start to stabilise as soon as we get subselects included
in it.

@menu
* News-3.23.0::                 Changes in release 3.23.0
@end menu

@node News-3.23.0,  , News-3.23.x, News-3.23.x
@appendixsubsec Changes in release 3.23.0

@itemize @bullet
A new table handler library (@code{MYISAM}) with a lot of new features.
@xref{Table types}.
@item
You can create in-memory @code{HEAP} tables which are extremely fast for
lookups.
@item
Support for big files (63 bit) on OSes that support big files.
@item
New function @code{LOAD_FILE(filename)} to get the contents of a file as a
string value.
@item
New operator @code{<=>} which will act as @code{=} but will return TRUE if both
arguments are @code{NULL}.  This is useful for comparing changes between tables.
@item
Added the ODBC 3.0 @code{EXTRACT(interval FROM datetime)} function.
@item
Columns defined as @code{FLOAT(4)} or @code{FLOAT(8)} are not rounded
on storage and may be in scientific notation (1.0 E+10) when retrieved.
@item
@code{REPLACE} is now faster than before.
@item
Changed @code{LIKE} character comparison to behave as @code{=};
This means that @code{'e' LIKE 'é'} is now true.
@item
@code{SHOW TABLE STATUS} returns a lot of information about the tables.
@item
Added comments to tables (with @code{CREATE TABLE ... COMMENT "xxx"}).
@item
Added @code{UNIQUE}, as in
@code{CREATE TABLE table_name (col int not null UNIQUE)}
@item
New create syntax: @code{CREATE TABLE SELECT ....}
@item
New create syntax: @code{CREATE TABLE IF NOT EXISTS ...}
@item
Allow creation of @code{CHAR(0)} columns.
@item
@code{DATE_FORMAT()} now requires @code{%} before any format character.
@item
@code{DELAYED} is now a reserved word (sorry about that :( ).
@item
An example procedure is added: @code{analyse}, file: @file{sql_analyse.c}.
This will describe the data in your query.  Try the following:
@example
SELECT ... FROM ... WHERE ... PROCEDURE ANALYSE([max elements,[max memory]])
@end example
 
This procedure is extremely useful when you want to check the data in your
table!
@item
@code{BINARY} cast to force a string to be compared case sensitively.
@item
Added option @code{--skip-show-databases} to @code{mysqld}.
@item
Check if a row has changed in an @code{UPDATE} now also works with
@code{BLOB}/@code{TEXT} columns.
@item
Added the @code{INNER} join syntax.  @strong{NOTE}:  This made @code{INNER}
an reserved word!
@item
Added support for netmasks to the hostname in the @strong{MySQL} tables.
You can specify a netmask using the @code{IP/NETMASK} syntax.
@item
If you compare a @code{NOT NULL DATE/DATETIME} column with @code{IS
NULL}, this is changed to a compare against @code{0} to satisfy some ODBC
applications.  (By @email{shreeve@@uci.edu}).
@item
@code{NULL IN (...)} now returns @code{NULL} instead of @code{0}.  This will
ensure that @code{null_column NOT IN (...)} doesn't match
@code{NULL} values.
@item
Fix storage of floating point values in @code{TIME} columns.
@item
Changed parsing of @code{TIME} strings to be more strict.  Now the
fractional second part is detected (and currently skipped). The
following formats are supported:
@table @code
@item [[DAYS] [H]H:]MM:]SS[.fraction]
@item [[[[[H]H]H]H]MM]SS[.fraction]
@end table
@item
Detect (and ignore) second fraction part from @code{DATETIME}.
@item
Added the @code{LOW_PRIORITY} attribute to @code{LOAD DATA INFILE}.
@item
The default index name now uses the same case as the used column name.
@item
Added @code{LIKE} to the @code{SHOW STATUS} command.
@item
Changed default number of connections to 100.
@item
Use bigger buffers when using @code{LOAD DATA INFILE}.
@item
@code{DECIMAL(x,y)} now works according to ANSI SQL.
@item
Added aggregate UDF functions. Thanks to Andreas F. Bobak
@email{bobak@@relog.ch} for this!
@item
@code{LAST_INSERT_ID()} is now updated for @code{INSERT INTO ... SELECT}.
@item
Some small changes to the join table optimizer to make some joins faster.
@item
@code{SELECT DISTINCT} is much faster; It uses the new @code{UNIQUE}
functionality in @code{MYISAM}.
@item
Temporary in-memory @code{HEAP} tables are automatically converted to
@code{MYISAM} disk-based tables when needed. This means that you should no
longer get the @code{TABLE is FULL} error.
@end itemize

@node News-3.22.x, News-3.21.x, News-3.23.x, News
@appendixsec Changes in release 3.22.x

The 3.22 version has faster and safer connect code and a lot of new nice
enhancements.  The reason for not including these changes in the 3.21 version
is mainly that we are trying to avoid big changes to 3.21 to keep it as
stable as possible.  As there aren't really any MAJOR changes, upgrading to
3.22 should be very easy and painless.
@xref{Upgrading-from-3.21}.

3.22 should also be used with the new @code{DBD-mysql} (1.20xx) driver
that can use the new connect protocol!

@menu
* News-3.22.23::                Changes in release 3.22.23
* News-3.22.22::                Changes in release 3.22.22
* News-3.22.21::                Changes in release 3.22.21
* News-3.22.20::                Changes in release 3.22.20
* News-3.22.19::                Changes in release 3.22.19
* News-3.22.18::                Changes in release 3.22.18
* News-3.22.17::                Changes in release 3.22.17
* News-3.22.16::                Changes in release 3.22.16
* News-3.22.15::                Changes in release 3.22.15
* News-3.22.14::                Changes in release 3.22.14
* News-3.22.13::                Changes in release 3.22.13
* News-3.22.12::                Changes in release 3.22.12
* News-3.22.11::                Changes in release 3.22.11
* News-3.22.10::                Changes in release 3.22.10
* News-3.22.9::                 Changes in release 3.22.9
* News-3.22.8::                 Changes in release 3.22.8
* News-3.22.7::                 Changes in release 3.22.7
* News-3.22.6::                 Changes in release 3.22.6
* News-3.22.5::                 Changes in release 3.22.5
* News-3.22.4::                 Changes in release 3.22.4
* News-3.22.3::                 Changes in release 3.22.3
* News-3.22.2::                 Changes in release 3.22.2
* News-3.22.1::                 Changes in release 3.22.1
* News-3.22.0::                 Changes in release 3.22.0
@end menu

@node News-3.22.23, News-3.22.22, News-3.22.x, News-3.22.x
@appendixsubsec Changes in release 3.22.23

@itemize @bullet
@item
Upgraded to use autoconf 2.3, automake 1.4 and libtool 1.3.2
@item
Better support for SCO in configure.
@item
Added option @code{--defaults-file=###} to option file handling to force use
of only one specific option file.
@item
Extended @code{CREATE} syntax to ignore @code{MySQL 3.23} keywords.
@item
Fixed deadlock problem when using @code{INSERT DELAYED} on a table locked with
@code{LOCK TABLES}.
@item
Fixed deadlock problem when using @code{DROP TABLE} on a table that was
locked by another thread.
@item
Add logging of @code{GRANT/REVOKE} commands in the update log.
@item
Fixed @code{isamchk} to detect a new error condition.
@item
Fixed bug in @code{NATURAL LEFT JOIN}.
@end itemize

@node News-3.22.22, News-3.22.21, News-3.22.23, News-3.22.x
@appendixsubsec Changes in release 3.22.22

@itemize @bullet
@item
Fixed problem in the C API when you called @code{mysql_close()} directly after
@code{mysql_init()}.
@item
Better client error message when you can't open socket.
@item
Fixed @code{delayed_insert_thread} counting when you couldn't create a new
delayed_insert thread.
@item
Fixed bug in @code{CONCAT()} with many arguments.
@item
Added patches for DEC 3.2 and SCO.
@item
Fixed path-bug when installing @strong{MySQL} as a service on NT.
@item
The @strong{MySQL}-win32 version is now compiled with VC++ 6.0 instead of
with VC++ 5.0.
@item
New installation setup for @strong{MySQL-Win32}
@end itemize

@node News-3.22.21, News-3.22.20, News-3.22.22, News-3.22.x
@appendixsubsec Changes in release 3.22.21

@itemize @bullet
@item
Fixed problem with @code{DELETE FROM TABLE} when table was locked by
another thread.
@item
Fixed bug in @code{LEFT JOIN} involving empty tables.
@item
Changed the @code{mysql.db} column from @code{char(32)} to @code{char(60)}.
@item
@code{MODIFY} and @code{DELAYED} are not reserved words anymore.
@item
Fixed a bug when storing days in a @code{TIME} column.
@item
Fixed a problem with @code{Host '..' is not allowed to connect to this MySQL
server} after one had inserted a new @strong{MySQL} user with a @code{GRANT}
command.
@item
Changed to use TCP_NODELAY also on Linux (Should give faster TCP/IP
connections).
@end itemize

@node News-3.22.20, News-3.22.19, News-3.22.21, News-3.22.x
@appendixsubsec Changes in release 3.22.20

@itemize @bullet
@item
Fixed @code{STD()} for big tables when result should be 0.
@item
The update log didn't have newlines on some operating systems.
@item
@code{INSERT DELAYED} had some garbage at end in the update log.
@end itemize

@node News-3.22.19, News-3.22.18, News-3.22.20, News-3.22.x
@appendixsubsec Changes in release 3.22.19

@itemize @bullet
@item
Fixed bug in @code{mysql_install_db} (from 3.22.17).
@item
Changed default key cache size to 8M.
@item
Fixed problem with queries that needed temporary tables with @code{BLOB}
columns.
@end itemize

@node News-3.22.18, News-3.22.17, News-3.22.19, News-3.22.x
@appendixsubsec Changes in release 3.22.18

@itemize @bullet
@item
Fixes a fatal problem in 3.22.17 on Linux;  After @code{shutdown}
all threads didn't die properly.
@item
Added option @code{-O flush-time=#} to @code{mysqld}.  This is mostly
useful on Win32 and tells how often @strong{MySQL} should close all
unused tables and flush all updated tables to disk.
@item
Fixed problem that a @code{VARCHAR} column compared with @code{CHAR} column
didn't use keys efficiently.
@end itemize

@node News-3.22.17, News-3.22.16, News-3.22.18, News-3.22.x
@appendixsubsec Changes in release 3.22.17

@itemize @bullet
@item
Fixed a core dump problem when using @code{--log-update} and connecting
without a default database.
@item
Fixed some @code{configure} and portability problems.
@item
Using @code{LEFT JOIN} on tables that had circular dependencies caused
@code{mysqld} to hang forever.
@end itemize

@node News-3.22.16, News-3.22.15, News-3.22.17, News-3.22.x
@appendixsubsec Changes in release 3.22.16

@itemize @bullet
@item
@code{mysqladmin processlist} could kill the server if a new user logged in.
@item
@code{DELETE FROM tbl_name WHERE key_column=col_name} didn't find any matching
rows.  Fixed.
@item
@code{DATE_ADD(column,...)} didn't work.
@item
@code{INSERT DELAYED} could deadlock with status 'upgrading lock'
@item
Extended @code{ENCRYPT()} to take longer salt strings than 2 characters.
@item
@code{longlong2str} is now much faster than before.  For @code{Intel x86}
platforms, this function is written in optimized assembler.
@item
Added the @code{MODIFY} keyword to @code{ALTER TABLE}.
@end itemize

@node News-3.22.15, News-3.22.14, News-3.22.16, News-3.22.x
@appendixsubsec Changes in release 3.22.15

@itemize @bullet
@item
@code{GRANT} used with @code{IDENTIFIED BY} didn't take effect until privileges
were flushed.
@item
Name change of some variables in @code{SHOW STATUS}.
@item
Fixed problem with @code{ORDER BY} with 'only index' optimzation when there
were multiple key definitions for a used column.
@item
@code{DATE} and @code{DATETIME} columns are now up to 5 times faster than
before.
@item
@code{INSERT DELAYED} can be used to let the client do other things while the
server inserts rows into a table.
@item
@code{LEFT JOIN USING (col1,col2)} didn't work if one used it with tables
from 2 different databases.
@item
@code{LOAD DATA LOCAL INFILE} didn't work in the Unix version because of
a missing file.
@item
Fixed problems with @code{VARCHAR}/@code{BLOB} on very short rows (< 4 bytes);
error 127 could occur when deleting rows.
@item
Updating @code{BLOB/TEXT} through formulas didn't work for short (< 256 char)
strings.
@item
When you did a @code{GRANT} on a new host, @code{mysqld} could die on the first
connect from this host.
@item
Fixed bug when one used @code{ORDER BY} on column name that was the same
name as an alias.
@item
Added @code{BENCHMARK(loop-count,expression)} function to time expressions.
@end itemize

@node News-3.22.14, News-3.22.13, News-3.22.15, News-3.22.x
@appendixsubsec Changes in release 3.22.14

@itemize @bullet
@item
Allow empty arguments to @code{mysqld} to make it easier to start from shell
scripts.
@item
Setting a @code{TIMESTAMP} column to @code{NULL} didn't record the timestamp
value in the update log.
@item
Fixed lock handler bug when one did
@code{INSERT INTO TABLE ... SELECT ... GROUP BY}.
@item
Added a patch for @code{localtime_r()} on Win32 so that it will not crash
anymore if your date is > 2039, but instead will return a time of all zero.
@item
Names for
user-defined functions are no longer case sensitive.
@item
Added escape of @code{^Z} (ASCII 26) to @code{\Z} as @code{^Z} doesn't
work with pipes on Win32.
@item
@code{mysql_fix_privileges} adds a new column to the @code{mysql.func} to
support aggregate UDF functions in future @strong{MySQL} releases.
@end itemize

@node News-3.22.13, News-3.22.12, News-3.22.14, News-3.22.x
@appendixsubsec Changes in release 3.22.13

@itemize @bullet
@item
Saving @code{NOW()}, @code{CURDATE()} or @code{CURTIME()} directly in a
column didn't work.
@item
@code{SELECT COUNT(*) ... LEFT JOIN ...} didn't work with no @code{WHERE} part.
@item
Updated @file{config.guess} to allow @strong{MySQL} to configure on
UnixWare 7.0.x.
@item
Changed the implementation of @code{pthread_cond()} on the Win32 version.
@code{get_lock()} now correctly times out on Win32!
@end itemize

@node News-3.22.12, News-3.22.11, News-3.22.13, News-3.22.x
@appendixsubsec Changes in release 3.22.12

@itemize @bullet
@item
Fixed problem when using @code{DATE_ADD()} and @code{DATE_SUB()} in a
@code{WHERE} clause.
@item
You can now set the password for a user with the @code{GRANT ... TO user
IDENTIFIED BY 'password'} syntax.
@item
Fixed bug in @code{GRANT} checking with @code{SELECT} on many tables.
@item
Added missing file @code{mysql_fix_privilege_tables} to the RPM
distribution. This is not run by default since it relies on the client
package.
@item
Added option @code{SQL_SMALL_RESULT} to @code{SELECT} to force use of
fast temporary tables when you know that the result set will be small.
@item
Allow use of negative real numbers without a decimal point.
@item
Day number is now adjusted to max days in month if the resulting month
after @code{DATE_ADD}/@code{DATE_SUB()} doesn't have enough days.
@item
Fix that @code{GRANT} compares columns in case-insensitive fashion.
@item
Fixed a bug in @file{sql_list.h} that made @code{ALTER TABLE} dump core in
some contexts.
@item
The hostname in @code{user@@hostname} can now include @samp{.} and @samp{-}
without quotes in the context of the @code{GRANT}, @code{REVOKE} and
@code{SET PASSWORD FOR ...} statements.
@item
Fix for @code{isamchk} for tables which need big temporary files.
@end itemize

@node News-3.22.11, News-3.22.10, News-3.22.12, News-3.22.x
@appendixsubsec Changes in release 3.22.11

@itemize @bullet
@item
@strong{IMPORTANT}: You must run the @code{mysql_fix_privilege_tables} script
when you upgrade to this version!  This is needed because of the new
@code{GRANT} system. If you don't do this, you will get @code{Access
denied} when you try to use @code{ALTER TABLE}, @code{CREATE INDEX} or
@code{DROP INDEX}.
@item
@code{GRANT} to allow/deny users table and column access.
@item
Changed @code{USER()} to return @code{user@@host}
@item
Changed the syntax for how to set @code{PASSWORD} for another user.
@item
New command @code{FLUSH STATUS} that sets most status variables to zero.
@item
New status variables: @code{aborted_threads}, @code{aborted_connects}.
@item
New option variable: @code{connection_timeout}.
@item
Added support for Thai sorting (by Pruet Boonma
@email{pruet@@ds90.intanon.nectec.or.th}).
@item
Slovak and japanese error messages.
@item
Configuration and portability fixes.
@item
Added option @code{SET SQL_WARNINGS=1} to get a warning count also for simple
inserts.
@item
@strong{MySQL} now uses @code{SIGTERM} instead of @code{SIGQUIT} with
shutdown to work better on FreeBSD.
@item
Added option @code{\G} (print vertically) to @code{mysql}.
@item
@code{SELECT HIGH_PRIORITY} ... killed @code{mysqld}.
@item
@code{IS NULL} on a @code{AUTO_INCREMENT} column in a @code{LEFT JOIN} didn't
work as expected.
@item
New function @code{MAKE_SET()}.
@end itemize

@node News-3.22.10, News-3.22.9, News-3.22.11, News-3.22.x
@appendixsubsec Changes in release 3.22.10

@itemize @bullet
@item
@code{mysql_install_db} no longer starts the @strong{MySQL} server!  You
should start @code{mysqld} with @code{safe_mysqld} after installing it!  The
@strong{MySQL} RPM will however start the server as before.
@item
Added @code{--bootstrap} option to @code{mysqld} and recoded
@code{mysql_install_db} to use it.  This will make it easier to install
@strong{MySQL} with RPMs.
@item
Changed @code{+}, @code{-} (sign and minus), @code{*}, @code{/}, @code{%},
@code{ABS()} and @code{MOD()} to be @code{BIGINT} aware (64-bit safe).
@item
Fixed a bug in @code{ALTER TABLE} that caused @code{mysqld} to crash.
@item
@strong{MySQL} now always reports the conflicting key values when a
duplicate key entry occurs. (Before this was only reported for @code{INSERT}).
@item
New syntax: @code{INSERT INTO tbl_name SET col_name=value,col_name=value,...}
@item
Most errors in the @file{.err} log are now prefixed with a time stamp.
@item
Added option @code{MYSQL_INIT_COMMAND} to @code{mysql_options()} to make
a query on connect or reconnect.
@item
Added option @code{MYSQL_READ_DEFAULT_FILE} and
@code{MYSQL_READ_DEFAULT_GROUP} to @code{mysql_options()} to read the
following parameters from the @strong{MySQL} option files: port, socket,
compress, password, pipe, timeout, user, init-command, host and
database.
@item
Added @code{maybe_null} to the UDF structure.
@item
Added option @code{IGNORE} to @code{INSERT} statemants with many rows.
@item
Fixed some problems with sorting of the koi8 character sets; Users of koi8
@strong{MUST} run @code{isamchk -rq} on each table that has an index on
a @code{CHAR} or @code{VARCHAR} column.
@item
New script @code{mysql_setpermission}, by Luuk de Boer, allows one
to easily create new users with permissions for specific databases.
@item
Allow use of hexadecimal strings (0x...) when specifying a constant string
(like in the column separators with @code{LOAD DATA INFILE}).
@item
Ported to OS/2 (thanks to Antony T. Curtis @email{antony.curtis@@olcs.net}).
@item
Added more variables to @code{SHOW STATUS} and changed format of output to
be like @code{SHOW VARIABLES}.
@item
Added @code{extended-status} command to @code{mysqladmin} which will show the
new status variables.
@end itemize

@node News-3.22.9, News-3.22.8, News-3.22.10, News-3.22.x
@appendixsubsec Changes in release 3.22.9

@itemize @bullet
@item
@code{SET SQL_LOG_UPDATE=0} caused a lockup of the server.
@item
New SQL command:  @code{FLUSH [ TABLES | HOSTS | LOGS | PRIVILEGES ] [, ...]}
@item
New SQL command:  @code{KILL} thread_id
@item
Added casts and changed include files to make @strong{MySQL} easier to
compile on AIX and DEC OSF1 4.x
@item
Fixed conversion problem when using @code{ALTER TABLE} from a @code{INT}
to a short @code{CHAR()} column.
@item
Added @code{SELECT HIGH_PRIORITY}; This will get a lock for the
@code{SELECT} even if there is a thread waiting for another
@code{SELECT} to get a @code{WRITE LOCK}.
@item
Moved wild_compare to string class to be able to use @code{LIKE} on
@code{BLOB}/@code{TEXT} columns with @code{\0}.
@item
Added @code{ESCAPE} option to @code{LIKE}.
@item
Added a lot more output to @code{mysqladmin debug}.
@item
You can now start @code{mysqld} on Win32 with the @code{--flush} option.
This will flush all tables to disk after each update.  This makes things
much safer on NT/Win98 but also @strong{MUCH} slower.
@end itemize

@node News-3.22.8, News-3.22.7, News-3.22.9, News-3.22.x
@appendixsubsec Changes in release 3.22.8

@itemize @bullet
@item
Czech character sets should now work much better.  You must also install
@uref{ftp://www.mysql.com/pub/mysql/Downloads/Patches/czech-3.22.8-patch}.
This patch should also be installed if you are using a character set with
uses @code{my_strcoll()}!  The patch should always be safe to install (for any system),
but as this patch changes ISAM internals it's not yet in the default
distribution.
@item
@code{DATE_ADD()} and @code{DATE_SUB()} didn't work with group functions.
@item
@code{mysql} will now also try to reconnect on @code{USE DATABASE} commands.
@item
Fix problem with @code{ORDER BY} and @code{LEFT JOIN} and @code{const} tables.
@item
Fixed problem with @code{ORDER BY} if the first @code{ORDER BY} column
was a key and the rest of the @code{ORDER BY} columns wasn't part of the key.
@item
Fixed a big problem with @code{OPTIMIZE TABLE}.
@item
@strong{MySQL} clients on NT will now by default first try to connect with
named pipes and after this with TCP/IP.
@item
Fixed a problem with @code{DROP TABLE} and @code{mysqladmin shutdown} on Win32
(a fatal bug from 3.22.6).
@item
Fixed problems with @code{TIME columns} and negative strings.
@item
Added an extra thread signal loop on shutdown to avoid some error messages
from the client.
@item
@strong{MySQL} now uses the next available number as extension for the update
log file.
@item
Added patches for UNIXWARE 7.
@end itemize

@node News-3.22.7, News-3.22.6, News-3.22.8, News-3.22.x
@appendixsubsec Changes in release 3.22.7

@itemize @bullet
@item
Added @code{LIMIT} clause for the @code{DELETE} statement.
@item
You can now use the @code{/*! ... */} syntax to hide @strong{MySQL}-specific
keywords when you write portable code.  @strong{MySQL} will parse the code
inside the comments as if the surrounding @code{/*!} and @code{*/} comment
characters didn't exist.
@item
@code{OPTIMIZE TABLE tbl_name} can now be used to reclaim disk space
after many deletes.  Currently, this uses @code{ALTER TABLE} to re-generate
the table, but in the future it will use an integrated @code{isamchk}
for more speed.
@item
Upgraded @code{libtool} to get the configure more portable.
@item
Fixed slow @code{UPDATE} and @code{DELETE} operations when using
@code{DATETIME} or @code{DATE} keys.
@item
Changed optimizer to make it better at deciding when to do a full join
and when using keys.
@item
You can now use @code{mysqladmin proc} to display information about your own
threads. Only users with the @strong{Process_priv} privilege can get
information about all threads.
@item
Added handling of formats @code{YYMMDD}, @code{YYYYMMDD},
@code{YYMMDDHHMMSS} for numbers when using @code{DATETIME} and
@code{TIMESTAMP} types. (Formerly these formats only worked with strings.)
@item
Added connect option @code{CLIENT_IGNORE_SPACE} to allow use of spaces
after function names and before @samp{(} (Powerbuilder requires this).
This will make all function names reserved words.
@item
Added the @code{--log-long-format} option to @code{mysqld} to enable timestamps
and INSERT_ID's in the update log.
@item
Added @code{--where} option to @code{mysqldump} (patch by Jim Faucette).
@item
The lexical analyzer now uses ``perfect hashing'' for faster parsing of SQL
statements.
@end itemize

@node News-3.22.6, News-3.22.5, News-3.22.7, News-3.22.x
@appendixsubsec Changes in release 3.22.6

@itemize @bullet
@item
Faster @code{mysqldump}.
@item
For the @code{LOAD DATA INFILE} statement, you can now use the new @code{LOCAL}
keyword to read the file from the client.  @code{mysqlimport} will
automatically use @code{LOCAL} when importing with the TCP/IP protocol.
@item
Fixed small optimize problem when updating keys.
@item
Changed makefiles to support shared libraries.
@item
@strong{MySQL}-NT can now use named pipes, which means that you can now use
@strong{MySQL}-NT without having to install TCP/IP.
@end itemize

@node News-3.22.5, News-3.22.4, News-3.22.6, News-3.22.x
@appendixsubsec Changes in release 3.22.5

@itemize @bullet
@item
All table lock handing is changed to avoid some very subtle
deadlocks when using @code{DROP TABLE}, @code{ALTER TABLE}, @code{DELETE FROM
TABLE} and @code{mysqladmin flush-tables} under heavy usage.
Changed locking code to get better handling of locks of different types.
@item
Updated @code{DBI} to 1.00 and @code{DBD} to 1.2.0.
@item
Added a check that the error message file contains error messages suitable for
the current version of @code{mysqld}. (To avoid errors if you accidentally
try to use an old error message file.)
@item
All count structures in the client (@code{affected_rows()},
@code{insert_id()},...) are now of type @code{BIGINT} to allow 64-bit values
to be used.
This required a minor change in the @strong{MySQL} protocol which should affect
only old clients when using tables with @code{AUTO_INCREMENT} values > 24M.
@item
The return type of @code{mysql_fetch_lengths()} has changed from @code{uint *}
to @code{ulong *}. This may give a warning for old clients but should work
on most machines.
@item
Change @code{mysys} and @code{dbug} libraries to allocate all thread variables
in one struct.  This makes it easier to make a threaded @file{libmysql.dll}
library.
@item
Use the result from @code{gethostname()} (instead of @code{uname()}) when
constructing @file{.pid} file names.
@item
New better compressed server/client protocol.
@item
@code{COUNT()}, @code{STD()} and @code{AVG()} are extended to handle more than
4G rows.
@item
You can now store values in the range @code{-838:59:59} <= x <=
@code{838:59:59} in a @code{TIME} column.
@item
@strong{WARNING: INCOMPATIBLE CHANGE!!}
If you set a @code{TIME} column to too short a value, @strong{MySQL} now
assumes the value is given as: @code{[[[D ]HH:]MM:]SS} instead of
@code{HH[:MM[:SS]]}.
@item
@code{TIME_TO_SEC()} and @code{SEC_TO_TIME()} can now handle negative times
and hours up to 32767.
@item
Added new option
@code{SET OPTION SQL_LOG_UPDATE=@{0|1@}} to allow users with
the @strong{process} privilege to bypass the update log.
(Modified patch from Sergey A Mukhin @email{violet@@rosnet.net}.)
@item
Fixed fatal bug in @code{LPAD()}.
@item
Initialize line buffer in @file{mysql.cc} to make @code{BLOB} reading from
pipes safer.
@item
Added @code{-O max_connect_errors=#} option to @code{mysqld}.
Connect errors are now reset for each correct connection.
@item
Increased the default value of @code{max_allowed_packet} to @code{1M} in
@code{mysqld}.
@item
Added @code{--low-priority-updates} option to @code{mysqld}, to give
@code{UPDATE} operations lower priority than retrievals.  You can now use
@code{@{INSERT | REPLACE | UPDATE | DELETE@} LOW_PRIORITY ...}
You can also use @code{SET OPTION LOW_PRIORITY_UPDATES=@{0|1@}} to change the
priority for one thread.
One side effect is that @code{LOW_PRIORITY} is now a reserved word. :(
@item
Add support for @code{INSERT INTO table ... VALUES(...),(...),(...)},
to allow inserting multiple rows with a single statement.
@item
@code{INSERT INTO tbl_name} is now also cached when used with @code{LOCK TABLES}.
(Previously only @code{INSERT ... SELECT} and @code{LOAD DATA INFILE} were
cached.)
@item
Allow @code{GROUP BY} functions with @code{HAVING}:
@example
mysql> SELECT col FROM table GROUP BY col HAVING COUNT(*)>0;
@end example
@item
@code{mysqld} will now ignore trailing @samp{;} characters in queries. This
is to make it easier to migrate from some other SQL servers that require the
trailing @samp{;}.
@item
Fix for corrupted fixed-format output generated by @code{SELECT INTO OUTFILE}.
@item
@strong{WARNING: INCOMPATIBLE CHANGE!!}
Added Oracle @code{GREATEST()} and @code{LEAST()} functions.  You must now use
these instead of the @code{MAX()} and @code{MIN()} functions to get the
largest/smallest value from a list of values. These can now handle @code{REAL},
@code{BIGINT} and string (@code{CHAR} or @code{VARCHAR}) values.
@item
@strong{WARNING: INCOMPATIBLE CHANGE!!}
@code{DAYOFWEEK()} had offset 0 for Sunday. Changed the offset to 1.
@item
Give an error for queries that mix @code{GROUP BY} columns and fields when
there is no @code{GROUP BY} specification.
@item
Added @code{--vertical} option to @code{mysql}, for printing results in
vertical mode.
@item
Index-only optimization; some queries are now resolved using
only indexes.  Until @strong{MySQL} 4.0, this works only for numeric columns.
@xref{MySQL indexes, , @strong{MySQL} indexes}.
@item
Lots of new benchmarks.
@item
A new C API chapter and lots of other improvements in the manual.
@end itemize

@node News-3.22.4, News-3.22.3, News-3.22.5, News-3.22.x
@appendixsubsec Changes in release 3.22.4

@itemize @bullet
@item
Added @code{--tmpdir} option to @code{mysqld}, for specifying the location
of the temporary file directory.
@item
@strong{MySQL} now automatically changes a query from an ODBC client:
@example
SELECT ... FROM table WHERE auto_increment_column IS NULL
@end example
to:
@example
SELECT ... FROM table WHERE auto_increment_column == LAST_INSERT_ID()
@end example
This allows some ODBC programs (Delphi, Access) to retrieve the newly
inserted row to fetch the @code{AUTO_INCREMENT} id.
@item
@code{DROP TABLE} now waits for all users to free a table before deleting it.
@item
Fixed small memory leak in the new connect protocol.
@item
New functions @code{BIN()}, @code{HEX()} and @code{CONV()} for converting
between different number bases.
@item
Added function @code{SUBSTRING()} with 2 arguments.
@item
If you created a table with a record length smaller than 5, you couldn't
delete rows from the table.
@item
Added optimization to remove const reference tables from @code{ORDER BY} and
@code{GROUP BY}.
@item
@code{mysqld} now automatically disables system locking on Linux and Win32,
and for systems that use MIT-pthreads.  You can force the use of locking
with the @code{--enable-locking} option.
@item
Added @code{--console} option to @code{mysqld}, to force a console window
(for error messages) when using Win32.
@item
Fixed table locks for Win32.
@item
Allow @samp{$} in identifiers.
@item
Changed name of user-specific configuration file from @file{my.cnf} to
@file{.my.cnf} (Unix only).
@item
Added @code{DATE_ADD()} and @code{DATE_SUB()} functions.
@end itemize

@node News-3.22.3, News-3.22.2, News-3.22.4, News-3.22.x
@appendixsubsec Changes in release 3.22.3

@itemize @bullet
@item
Fixed a lock problem (bug in @strong{MySQL} 3.22.1) when closing temporary tables.
@item
Added missing @code{mysql_ping()} to the client library.
@item
Added @code{--compress} option to all @strong{MySQL} clients.
@item
Changed @code{byte} to @code{char} in @file{mysql.h} and @file{mysql_com.h}.
@end itemize

@node News-3.22.2, News-3.22.1, News-3.22.3, News-3.22.x
@appendixsubsec Changes in release 3.22.2

@itemize @bullet
@item
Searching on multiple constant keys that matched more than 30% of the rows
didn't always use the best possible key.
@item
New functions @code{<<}, @code{>>}, @code{RPAD()} and @code{LPAD()}.
@item
You can now save default options (like passwords) in a configuration file
(@file{my.cnf}).
@item
Lots of small changes to get @code{ORDER BY} to work when no records are found
when using fields that are not in @code{GROUP BY} (@strong{MySQL} extension).
@item
Added @code{--chroot} option to @code{mysqld}, to start @code{mysqld} in
a chroot environment (by Nikki Chumakov @email{nikkic@@cityline.ru}).
@item
Trailing spaces are now ignored when comparing case-sensitive strings;
this should fix some problems with ODBC and flag 512!
@item
Fixed a core-dump bug in the range optimizer.
@item
Added @code{--one-thread} option to @code{mysqld}, for debugging with
LinuxThreads (or @code{glibc}).  (This replaces the @code{-T32} flag)
@item
Added @code{DROP TABLE IF EXISTS} to prevent an error from occurring if the
table doesn't exist.
@item
@code{IF} and @code{EXISTS} are now reserved words (they would have to
be sooner or later).
@item
Added lots of new options to @code{mysqldump}.
@item
Server error messages are now in @file{mysqld_error.h}.
@item
The server/client protocol now supports compression.
@item
All bug fixes from @strong{MySQL} 3.21.32.
@end itemize

@node News-3.22.1, News-3.22.0, News-3.22.2, News-3.22.x
@appendixsubsec Changes in release 3.22.1

@itemize @bullet
@item
Added new C API function @code{mysql_ping()}.
@item
Added new API functions @code{mysql_init()} and @code{mysql_options()}.
You now MUST call @code{mysql_init()} before you call
@code{mysql_real_connect()}.
You don't have to call @code{mysql_init()} if you only use
@code{mysql_connect()}.
@item
Added @code{mysql_options(...,MYSQL_OPT_CONNECT_TIMEOUT,...)} so you can set a
timeout for connecting to a server.
@item
Added @code{--timeout} option to @code{mysqladmin}, as a test of
@code{mysql_options()}.
@item
Added @code{AFTER column} and @code{FIRST} options to
@code{ALTER TABLE ... ADD columns}.
This makes it possible to add a new column at some specific location
within a row in an existing table.
@item
@code{WEEK()} now takes an optional argument to allow handling of weeks when
the week starts on Monday (some European countries).  By default,
@code{WEEK()} assumes the week starts on Sunday.
@item
@code{TIME} columns weren't stored properly (bug in @strong{MySQL} 3.22.0).
@item
@code{UPDATE} now returns information about how many rows were
matched and updated, and how many ``warnings'' occurred when doing the update.
@item
Fixed incorrect result from @code{FORMAT(-100,2)}.
@item
@code{ENUM} and @code{SET} columns were compared in binary (case-sensitive)
fashion; changed to be case insensitive.
@end itemize

@node News-3.22.0,  , News-3.22.1, News-3.22.x
@appendixsubsec Changes in release 3.22.0

@itemize @bullet
@item
New (backward compatible) connect protocol that allows you to
specify the database to use when connecting, to get much faster
connections to a specific database.

The @code{mysql_real_connect()} call is changed to:

@example
mysql_real_connect(MYSQL *mysql, const char *host, const char *user,
                   const char *passwd, const char *db, uint port,
                   const char *unix_socket, uint client_flag)
@end example
@item
Each connection is handled by its own thread, rather than by the
master @code{accept()} thread.  This fixes permanently the telnet bug
that was a topic on the mail list some time ago.
@item
All TCP/IP connections are now checked with backward resolution of
the hostname to get better security. @code{mysqld} now has a local hostname
resolver cache so connections should actually be faster than before,
even with this feature.
@item
A site automatically will be blocked from future connections if someone
repeatedly connects with an ``improper header'' (like when one uses telnet).
@item
You can now refer to tables in different databases with references of the form
@code{tbl_name@@db_name} or @code{db_name.tbl_name}.  This makes it possible to
give a user read access to some tables and write access to others simply by
keeping them in different databases!
@item
Added @code{--user} option to @code{mysqld}, to allow it to run
as another Unix user (if it is started as the Unix @code{root} user).
@item
Added caching of users and access rights (for faster access rights checking)
@item
Normal users (not anonymous ones) can change their password with
@code{mysqladmin password 'new_password'}.  This uses encrypted passwords
that are not logged in the normal @strong{MySQL} log!
@item
All important string functions are now coded in assembler for x86 Linux
machines.  This gives a speedup of 10% in many cases.
@item
For tables that have many columns, the column names are now hashed for
much faster column name lookup (this will speed up some benchmark
tests a lot!)
@item
Some benchmarks are changed to get better individual timing.
(Some loops were so short that a specific test took < 2 seconds. The
loops have been changed to take about 20 seconds to make it easier
to compare different databases. A test that took 1-2 seconds before
now takes 11-24 seconds, which is much better)
@item
Re-arranged @code{SELECT} code to handle some very specific queries
involving group functions (like @code{COUNT(*)}) without a @code{GROUP BY} but
with @code{HAVING}. The following now works:
@example
mysql> SELECT count(*) as C FROM table HAVING C > 1;
@end example
@item
Changed the protocol for field functions to be faster and avoid some
calls to @code{malloc()}.
@item
Added @code{-T32} option to @code{mysqld}, for running all queries under the
main thread.  This makes it possible to debug @code{mysqld} under Linux with
@code{gdb}!
@item
Added optimization of @code{not_null_column IS NULL} (needed for some Access
queries).
@item
Allow @code{STRAIGHT_JOIN} to be used between two tables to force the optimizer
to join them in a specific order.
@item
String functions now return @code{VARCHAR} rather than @code{CHAR} and
the column type is now @code{VARCHAR} for fields saved as @code{VARCHAR}.
This should make the @strong{MyODBC} driver better, but may break some old
@strong{MySQL} clients that don't handle @code{FIELD_TYPE_VARCHAR} the same
way as @code{FIELD_TYPE_CHAR}.
@item
@code{CREATE INDEX} and @code{DROP INDEX} are now implemented through
@code{ALTER TABLE}.
@code{CREATE TABLE} is still the recommended (fast) way to create indexes.
@item
Added @code{--set-variable} option @code{wait_timeout} to @code{mysqld}.
@item
Added time column to @code{mysqladmin processlist} to show how long a query
has taken or how long a thread has slept.
@item
Added lots of new variables to @code{show variables} and some new to
@code{show status}.
@item
Added new type @code{YEAR}. @code{YEAR} is stored in 1 byte with allowable
values of 0, and 1901 to 2155.
@item
Added new @code{DATE} type that is stored in 3 bytes rather than 4 bytes.
All new tables are created with the new date type if you don't use the
@code{--old-protocol} option to @code{mysqld}.
@item
Fixed bug in record caches; for some queries, you could get
@code{Error from table handler: #} on some operating systems.
@item
Added @code{--enable-assembler} option to @code{configure}, for x86 machines
(tested on Linux + @code{gcc}).  This will enable assembler functions for the
most important string functions for more speed!
@end itemize

@node News-3.21.x, News-3.20.x, News-3.22.x, News
@appendixsec Changes in release 3.21.x

@menu
* News-3.21.33::                Changes in release 3.21.33
* News-3.21.32::                Changes in release 3.21.32
* News-3.21.31::                Changes in release 3.21.31
* News-3.21.30::                Changes in release 3.21.30
* News-3.21.29::                Changes in release 3.21.29
* News-3.21.28::                Changes in release 3.21.28
* News-3.21.27::                Changes in release 3.21.27
* News-3.21.26::                Changes in release 3.21.26
* News-3.21.25::                Changes in release 3.21.25
* News-3.21.24::                Changes in release 3.21.24
* News-3.21.23::                Changes in release 3.21.23
* News-3.21.22::                Changes in release 3.21.22
* News-3.21.21a::               Changes in release 3.21.21a
* News-3.21.21::                Changes in release 3.21.21
* News-3.21.20::                Changes in release 3.21.20
* News-3.21.19::                Changes in release 3.21.19
* News-3.21.18::                Changes in release 3.21.18
* News-3.21.17::                Changes in release 3.21.17
* News-3.21.16::                Changes in release 3.21.16
* News-3.21.15::                Changes in release 3.21.15
* News-3.21.14b::               Changes in release 3.21.14b
* News-3.21.14a::               Changes in release 3.21.14a
* News-3.21.13::                Changes in release 3.21.13
* News-3.21.12::                Changes in release 3.21.12
* News-3.21.11::                Changes in release 3.21.11
* News-3.21.10::                Changes in release 3.21.10
* News-3.21.9::                 Changes in release 3.21.9
* News-3.21.8::                 Changes in release 3.21.8
* News-3.21.7::                 Changes in release 3.21.7
* News-3.21.6::                 Changes in release 3.21.6
* News-3.21.5::                 Changes in release 3.21.5
* News-3.21.4::                 Changes in release 3.21.4
* News-3.21.3::                 Changes in release 3.21.3
* News-3.21.2::                 Changes in release 3.21.2
* News-3.21.0::                 Changes in release 3.21.0
@end menu

@node News-3.21.33, News-3.21.32, News-3.21.x, News-3.21.x
@appendixsubsec Changes in release 3.21.33

@itemize @bullet
@item
Fixed problem when sending @code{SIGHUP} to @code{mysqld};
@code{mysqld} core dumped when starting from boot on some systems.
@item
Fixed problem with losing a little memory for some connections.
@item
@code{DELETE FROM tbl_name} without a @code{WHERE} condition is now done the
long way when you use @code{LOCK TABLES} or if the table is in use, to
avoid race conditions.
@item
@code{INSERT INTO TABLE (timestamp_column) VALUES (NULL);} didn't set timestamp.
@end itemize

@node News-3.21.32, News-3.21.31, News-3.21.33, News-3.21.x
@appendixsubsec Changes in release 3.21.32

@itemize @bullet
@item
Fixed some possible race conditions when doing many reopen/close on the same
tables under heavy load!  This can happen if you execute @code{mysqladmin
refresh} often. This could in some very rare cases corrupt the header of the
index file and cause error 126 or 138.

@item
Fixed fatal bug in @code{refresh()} when running with the @code{--skip-locking}
option.
There was a ``very small'' time gap after a @code{mysqladmin refresh} when
a table could be corrupted if one thread updated a table while another
thread did @code{mysqladmin refresh} and another thread started a new update
ont the same table before the first thread had finished.
A refresh (or @code{--flush-tables}) will now not return until all used tables
are closed!
@item
@code{SELECT DISTINCT} with a @code{WHERE} clause that didn't match any rows
returned a row in some contexts (bug only in 3.21.31).
@item
@code{GROUP BY} + @code{ORDER BY} returned one empty row when no rows where
found.
@item
Fixed a bug in the range optimizer that wrote
@code{Use_count: Wrong count for ...} in the error log file.
@end itemize

@node News-3.21.31, News-3.21.30, News-3.21.32, News-3.21.x
@appendixsubsec Changes in release 3.21.31
@itemize @bullet
@item
Fixed a sign extension problem for the @code{TINYINT} type on Irix.
@item
Fixed problem with @code{LEFT("constant_string",function)}.
@item
Fixed problem with @code{FIND_IN_SET()}.
@item
@code{LEFT JOIN} core dumped if the second table is used with a constant
@code{WHERE/ON} expression that uniquely identifies one record.
@item
Fixed problems with @code{DATE_FORMAT()} and incorrect dates.
@code{DATE_FORMAT()} now ignores @code{'%'} to make it possible to extend
it more easily in the future.
@end itemize

@node News-3.21.30, News-3.21.29, News-3.21.31, News-3.21.x
@appendixsubsec Changes in release 3.21.30
@itemize @bullet
@item
@code{mysql} now returns an exit code > 0 if the query returned an error.
@item
Saving of command line history to file in @code{mysql} client.
By Tommy Larsen @email{tommy@@mix.hive.no}.
@item
Fixed problem with empty lines that were ignored in @file{mysql.cc}.
@item
Save the pid of the signal handler thread in the pid file instead
of the pid of the main thread.
@item
Added patch by @email{tommy@@valley.ne.jp} to support Japanese characters
SJIS and UJIS.
@item
Changed @code{safe_mysqld} to redirect startup messages to
@code{'hostname'.err} instead
of @code{'hostname'.log} to reclaim file space on @code{mysqladmin refresh}.
@item
@code{ENUM} always had the first entry as default value.
@item
@code{ALTER TABLE} wrote two entries to the update log.
@item
@code{sql_acc()} now closes the @code{mysql} grant tables after a reload to
save table space and memory.
@item
Changed @code{LOAD DATA} to use less memory with tables and @code{BLOB}
columns.
@item
Sorting on a function which made a division / 0 produced a wrong set
in some cases.
@item
Fixed @code{SELECT} problem with @code{LEFT()} when using the czech character
set.
@item
Fixed problem in @code{isamchk}; it couldn't repair a packed table in a very
unusual case.
@item
@code{SELECT} statements with @code{&} or @code{|} (bit functions) failed on
columns with @code{NULL} values.
@item
When comparing a field = field, where one of the fields was a part key,
only the length of the part key was compared.
@end itemize

@node News-3.21.29, News-3.21.28, News-3.21.30, News-3.21.x
@appendixsubsec Changes in release 3.21.29
@itemize @bullet
@item
@code{LOCK TABLES} + @code{DELETE from tbl_name} never removed locks properly.
@item
Fixed problem when grouping on an @code{OR} function.
@item
Fixed permission problem with @code{umask()} and creating new databases.
@item
Fixed permission problem on result file with @code{SELECT ... INTO OUTFILE ...}
@item
Fixed problem in range optimizer (core dump) for a very complex query.
@item
Fixed problem when using @code{MIN(integer)} or @code{MAX(integer)} in
@code{GROUP BY}.
@item
Fixed bug on Alpha when using integer keys. (Other keys worked on Alpha).
@item
Fixed bug in @code{WEEK("XXXX-xx-01")}.
@end itemize

@node News-3.21.28, News-3.21.27, News-3.21.29, News-3.21.x
@appendixsubsec Changes in release 3.21.28
@itemize @bullet
@item
Fixed socket permission (clients couldn't connect to Unix socket on Linux).
@item
Fixed bug in record caches; for some queries, you could get
@code{Error from table handler: #} on some operating systems.
@end itemize

@node News-3.21.27, News-3.21.26, News-3.21.28, News-3.21.x
@appendixsubsec Changes in release 3.21.27
@itemize @bullet
@item
Added user level lock functions @code{GET_LOCK(string,timeout)},
@code{RELEASE_LOCK(string)}.
@item
Added @code{opened_tables} to @code{show status}.
@item
Changed connect timeout to 3 seconds to make it somewhat harder
for crackers to kill @code{mysqld} through telnet + TCP/IP.
@item
Fixed bug in range optimizer when using
@code{WHERE key_part_1 >= something AND key_part_2 <= something_else}.
@item
Changed @code{configure} for detection of FreeBSD 3.0 9803xx and above
@item
@code{WHERE} with string_column_key = constant_string didn't always find
all rows if the column had many values differing only with characters of
the same sort value (like e and @'e).
@item
Strings keys looked up with 'ref' were not compared in case-sensitive fashion.
@item
Added @code{umask()} to make log files non-readable for normal users.
@item
Ignore users with old (8-byte) password on startup if not using
@code{--old-protocol} option to @code{mysqld}.
@item
@code{SELECT} which matched all key fields returned the values in the
case of the matched values, not of the found values. (Minor problem.)
@end itemize

@node News-3.21.26, News-3.21.25, News-3.21.27, News-3.21.x
@appendixsubsec Changes in release 3.21.26
@itemize @bullet
@item
@code{FROM_DAYS(0)} now returns "0000-00-00".
@item
In @code{DATE_FORMAT()}, PM and AM were swapped for hours 00 and 12.
@item
Extended the default maximum key size to 256.
@item
Fixed bug when using @code{BLOB}/@code{TEXT} in @code{GROUP BY} with many
tables.
@item
An @code{ENUM} field that is not declared @code{NOT NULL} has @code{NULL} as
the default value.
(Previously, the default value was the first enumeration value.)
@item
Fixed bug in the join optimizer code when using many part keys
on the same key:  @code{INDEX (Organization,Surname(35),Initials(35))}.
@item
Added some tests to the table order optimizer to get some cases with
@code{SELECT ... FROM many_tables} much faster.
@item
Added a retry loop around @code{accept()} to possibly fix some problems on some
Linux machines.
@end itemize

@node News-3.21.25, News-3.21.24, News-3.21.26, News-3.21.x
@appendixsubsec Changes in release 3.21.25
@itemize @bullet
@item
Changed @code{typedef 'string'} to @code{typedef 'my_string'} for better
portability.
@item
You can now kill threads that are waiting on a disk full condition.
@item
Fixed some problems with UDF functions.
@item
Added long options to @code{isamchk}. Try @code{isamchk --help}.
@item
Fixed a bug when using 8 bytes long (alpha); @code{filesort()} didn't work.
Affects @code{DISTINCT}, @code{ORDER BY} and @code{GROUP BY} on 64-bit
processors.
@end itemize

@node News-3.21.24, News-3.21.23, News-3.21.25, News-3.21.x
@appendixsubsec Changes in release 3.21.24
@itemize @bullet
@item
Dynamic loadable functions. Based on source from Alexis Mikhailov.
@item
You couldn't delete from a table if no one had done a @code{SELECT} on the
table.
@item
Fixed problem with range optimizer with many @code{OR} operators on key parts
inside each other.
@item
Recoded @code{MIN()} and @code{MAX()} to work properly with strings and
@code{HAVING}.
@item
Changed default umask value for new files from @code{0664} to @code{0660}.
@item
Fixed problem with @code{LEFT JOIN} and constant expressions in the @code{ON}
part.
@item
Added Italian error messages from @email{brenno@@3cord.philips.nl}.
@item
@code{configure} now works better on OSF1 (tested on 4.0D).
@item
Added hooks to allow @code{LIKE} optimization with international character
support.
@item
Upgraded @code{DBI} to 0.93.
@end itemize

@node News-3.21.23, News-3.21.22, News-3.21.24, News-3.21.x
@appendixsubsec Changes in release 3.21.23
@itemize @bullet
@item
The following symbols are now reserved words:
@code{TIME}, @code{DATE}, @code{TIMESTAMP}, @code{TEXT}, @code{BIT},
@code{ENUM}, @code{NO}, @code{ACTION}, @code{CHECK}, @code{YEAR},
@code{MONTH}, @code{DAY}, @code{HOUR}, @code{MINUTE}, @code{SECOND},
@code{STATUS}, @code{VARIABLES}.
@item
Setting a @code{TIMESTAMP} to @code{NULL} in @code{LOAD DATA INFILE ...} didn't
set the current time for the @code{TIMESTAMP}.
@item
Fix @code{BETWEEN} to recognize binary strings. Now @code{BETWEEN} is
case sensitive.
@item
Added @code{--skip-thread-priority} option to @code{mysqld}, for systems
where @code{mysqld}'s thread scheduling doesn't work properly (BSDI 3.1).
@item
Added ODBC functions @code{DAYNAME()} and @code{MONTHNAME()}.
@item
Added function @code{TIME_FORMAT()}.  This works like @code{DATE_FORMAT()},
but takes a time string (@code{'HH:MM:DD'}) as argument.
@item
Fixed unlikely(?) key optimizer bug when using @code{OR}s of key parts
inside @code{AND}s.
@item
Added command @code{variables} to @code{mysqladmin}.
@item
A lot of small changes to the binary releases.
@item
Fixed a bug in the new protocol from @strong{MySQL} 3.21.20.
@item
Changed @code{ALTER TABLE} to work with Win32 (Win32 can't rename open files).
Also fixed a couple of small bugs in the Win32 version.
@item
All standard @strong{MySQL} clients are now ported to MySQL-Win32.
@item
@strong{MySQL} can now be started as a service on NT.
@end itemize

@node News-3.21.22, News-3.21.21a, News-3.21.23, News-3.21.x
@appendixsubsec Changes in release 3.21.22
@itemize @bullet
@item
Starting with this version, all @strong{MySQL} distributions will be
configured, compiled and tested with @code{crash-me} and the benchmarks on
the following platforms: SunOS 5.6 sun4u, SunOS 5.5.1 sun4u, SunOS 4.14 sun4c,
SunOS 5.6 i86pc, Irix 6.3 mips5k, HP-UX 10.20 hppa, AIX 4.2.1 ppc,
OSF1 V4.0 alpha, FreeBSD 2.2.2 i86pc and BSDI 3.1 i386.
@item
Fix @code{COUNT(*)} problems when the @code{WHERE} clause didn't match any
records.  (Bug from 3.21.17.)
@item
Removed that @code{NULL = NULL} is true.  Now you must use @code{IS NULL}
or @code{IS NOT NULL} to test whether or not a value is @code{NULL}.
(This is according to ANSI SQL but may break
old applications that are ported from @code{mSQL}.)
You can get the old behavior by compiling with @code{-DmSQL_COMPLIANT}.
@item
Fixed bug that core dumped when using many @code{LEFT OUTER JOIN} clauses.
@item
Fixed bug in @code{ORDER BY} on string formula with possible @code{NULL} values.
@item
Fixed problem in range optimizer when using <= on sub index.
@item
Added functions @code{DAYOFYEAR()}, @code{DAYOFMONTH()}, @code{MONTH()},
@code{YEAR()}, @code{WEEK()}, @code{QUARTER()}, @code{HOUR()}, @code{MINUTE()},
@code{SECOND()} and @code{FIND_IN_SET()}.
@item
Added command @code{SHOW VARIABLES}.
@item
Added support of ``long constant strings'' from ANSI SQL:
@example
mysql> SELECT 'first ' 'second';       -> 'first second'
@end example
@item
Upgraded mSQL-Mysql-modules to 1.1825.
@item
Upgraded @code{mysqlaccess} to 2.02.
@item
Fixed problem with Russian character set and @code{LIKE}.
@item
Ported to OpenBSD 2.1.
@item
New Dutch error messages.
@end itemize

@node News-3.21.21a, News-3.21.21, News-3.21.22, News-3.21.x
@appendixsubsec Changes in release 3.21.21a
@itemize @bullet
@item
Configure changes for some operating systems.
@end itemize

@node News-3.21.21, News-3.21.20, News-3.21.21a, News-3.21.x
@appendixsubsec Changes in release 3.21.21
@itemize @bullet
@item
Fixed optimizer bug when using
@code{WHERE data_field = date_field2 AND date_field2 = constant}.
@item
Added command @code{SHOW STATUS}.
@item
Removed @file{manual.ps} from the source distribution to make it smaller.
@end itemize

@node News-3.21.20, News-3.21.19, News-3.21.21, News-3.21.x
@appendixsubsec Changes in release 3.21.20
@itemize @bullet
@item
Changed the maximum table name and column name lengths from 32 to 64.
@item
Aliases can now be of ``any'' length.
@item
Fixed @code{mysqladmin stat} to return the right number of queries.
@item
Changed protocol (downward compatible) to mark if a column has the
@code{AUTO_INCREMENT} attribute or is a @code{TIMESTAMP}. This is needed for
the new Java driver.
@item
Added Hebrew sorting order by Zeev Suraski.
@item
Solaris 2.6: Fixed @code{configure} bugs and increased maximum table size
from 2G to 4G.
@end itemize

@node News-3.21.19, News-3.21.18, News-3.21.20, News-3.21.x
@appendixsubsec Changes in release 3.21.19
@itemize @bullet
@item
Upgraded @code{DBD} to 1823. This version implements @code{mysql_use_result} in
@code{DBD-Mysql}.
@item
Benchmarks updated for empress (by Luuk).
@item
Fixed a case of slow range searching.
@item
Configure fixes (@file{Docs} directory).
@item
Added function @code{REVERSE()} (by Zeev Suraski).
@end itemize

@node News-3.21.18, News-3.21.17, News-3.21.19, News-3.21.x
@appendixsubsec Changes in release 3.21.18
@itemize @bullet
@item
Issue error message if client C functions are called in wrong order.
@item
Added automatic reconnect to the @file{libmysql.c} library. If a write command
fails, an automatic reconnect is done.
@item
Small sort sets no longer use temporary files.
@item
Upgraded @code{DBI} to 0.91.
@item
Fixed a couple of problems with @code{LEFT OUTER JOIN}.
@item
Added @code{CROSS JOIN} syntax. @code{CROSS} is now a reserved word.
@item
Recoded @code{yacc}/@code{bison} stack allocation to be even safer and to allow
@strong{MySQL} to handle even bigger expressions.
@item
Fixed a couple of problems with the update log.
@item
@code{ORDER BY} was slow when used with key ranges.
@end itemize

@node News-3.21.17, News-3.21.16, News-3.21.18, News-3.21.x
@appendixsubsec Changes in release 3.21.17
@itemize @bullet
@item
Changed documentation string of @code{--with-unix-socket-path} to avoid
confusion.
@item
Added ODBC and ANSI SQL style @code{LEFT OUTER JOIN}.
@item
The following are new reserved words: @code{LEFT}, @code{NATURAL},
@code{USING}.
@item
The client library now uses the value of the environment variable
@code{MYSQL_HOST} as the default host if it's defined.
@item
@code{SELECT column, SUM(expr)} now returns @code{NULL} for @code{column} when
there are matching rows.
@item
Fixed problem with comparing binary strings and @code{BLOB}s with ASCII
characters over 127.
@item
Fixed lock problem: when freeing a read lock on a table with multiple
read locks, a thread waiting for a write lock would have been given the lock.
This shouldn't affect data integrity, but could possibly make @code{mysqld}
restart if one thread was reading data that another thread modified.
@item
@code{LIMIT offset,count} didn't work in @code{INSERT ... SELECT}.
@item
Optimized key block caching. This will be quicker than the old algorithm when
using bigger key caches.
@end itemize

@node News-3.21.16, News-3.21.15, News-3.21.17, News-3.21.x
@appendixsubsec Changes in release 3.21.16

@itemize @bullet
@item
Added ODBC 2.0 & 3.0 functions @code{POWER()}, @code{SPACE()},
@code{COT()}, @code{DEGREES()}, @code{RADIANS()}, @code{ROUND(2 arg)}
and @code{TRUNCATE()}.
@item
@strong{WARNING: INCOMPATIBLE CHANGE!!} @code{LOCATE()} parameters were
swapped according to ODBC standard. Fixed.
@item
Added function @code{TIME_TO_SEC()}.
@item
In some cases, default values were not used for @code{NOT NULL} fields.
@item
Timestamp wasn't always updated properly in @code{UPDATE SET ...} statements.
@item
Allow empty strings as default values for @code{BLOB} and @code{TEXT}, to
be compatible with @code{mysqldump}.
@end itemize

@node News-3.21.15, News-3.21.14b, News-3.21.16, News-3.21.x
@appendixsubsec Changes in release 3.21.15

@itemize @bullet
@item
@strong{WARNING: INCOMPATIBLE CHANGE!!} @code{mysqlperl} is now from
Msql-Mysql-modules. This means that @code{connect()} now takes
@code{host}, @code{database}, @code{user}, @code{password} arguments! The old
version took @code{host}, @code{database}, @code{password}, @code{user}.
@item
Allow @code{DATE '1997-01-01'}, @code{TIME '12:10:10'} and
@code{TIMESTAMP '1997-01-01 12:10:10'} formats required by ANSI SQL.
@strong{WARNING: INCOMPATIBLE CHANGE!!} This has the unfortunate
side-effect that you no longer can have columns named @code{DATE}, @code{TIME}
or @code{TIMESTAMP}. :( Old columns can still be accessed through
@code{tablename.columnname}!)
@item
Changed Makefiles to hopefully work better with BSD systems. Also,
@file{manual.dvi} is now included in the distribution to avoid having stupid
@code{make} programs trying to rebuild it.
@item
@code{readline} library upgraded to version 2.1.
@item
A new sortorder german-1. That is a normal ISO-Latin1 with a german sort
order.
@item
Perl @code{DBI}/@code{DBD} is now included in the distribution. @code{DBI}
is now the recommended way to connect to @strong{MySQL} from Perl.
@item
New portable benchmark suite with @code{DBD}, with test results from
@code{mSQL} 2.0.3, @strong{MySQL}, PostgreSQL 6.2.1 and Solid server 2.2.
@item
@code{crash-me} is now included with the benchmarks; This is a Perl program
designed to find as many limits as possible in a SQL server. Tested with
@code{mSQL}, PostgreSQL, Solid and @strong{MySQL}.
@item
Fixed bug in range-optimizer that crashed @strong{MySQL} on some queries.
@item
Table and column name completion for @code{mysql} command line tool, by Zeev
Suraski and Andi Gutmans.
@item
Added new command @code{REPLACE} that works like @code{INSERT} but
replaces conflicting records with the new record. @code{REPLACE INTO
TABLE ... SELECT ...} works also.
@item
Added new commands @code{CREATE DATABASE db_name} and @code{DROP
DATABASE db_name}.
@item
Added @code{RENAME} option to @code{ALTER TABLE}: @code{ALTER TABLE name
RENAME AS new_name}.
@item
@code{make_binary_distribution} now includes @file{libgcc.a} in
@file{libmysqlclient.a}. This should make linking work for people who don't
have @code{gcc}.
@item
Changed @code{net_write()} to @code{my_net_write()} because of a name
conflict with Sybase.
@item
@cindex ODBC compatibility
@cindex Compatibility, with ODBC
New function @code{DAYOFWEEK()} compatible with ODBC.
@item
Stack checking and @code{bison} memory overrun checking to make @strong{MySQL}
safer with weird queries.
@end itemize

@node News-3.21.14b, News-3.21.14a, News-3.21.15, News-3.21.x
@appendixsubsec Changes in release 3.21.14b

@itemize @bullet
@item
Fixed a couple of small @code{configure} problems on some platforms.
@end itemize

@node News-3.21.14a, News-3.21.13, News-3.21.14b, News-3.21.x
@appendixsubsec Changes in release 3.21.14a

@itemize @bullet
@item
Ported to SCO Openserver 5.0.4  with FSU Pthreads.
@item
HP-UX 10.20 should work.
@item
Added new function @code{DATE_FORMAT()}.
@item
Added @code{NOT IN}.
@item
Added automatic removal of 'ODBC function conversions': @code{@{fn now() @}}
@item
Handle ODBC 2.50.3 option flags.
@item
Fixed comparison of @code{DATE} and @code{TIME} values with @code{NULL}.
@item
Changed language name from germany to german to be consistent with
the other language names.
@item
Fixed sorting problem on functions returning a @code{FLOAT}. Previously, the
values were converted to @code{INT}s before sorting.
@item
Fixed slow sorting when sorting on key field when using
@code{key_column=constant}.
@item
Sorting on calculated @code{DOUBLE} values sorted on integer results instead.
@item
@code{mysql} no longer needs a database argument.
@item
Changed the place where @code{HAVING} should be. According to ANSI, it should
be after @code{GROUP BY} but before @code{ORDER BY}. @strong{MySQL} 3.20
incorrectly had it last.
@item
Added Sybase command @code{USE DATABASE} to start using another database.
@item
Added automatic adjusting of number of connections and table cache size
if the maximum number of files that can be opened is less than needed.
This should fix that @code{mysqld} doesn't crash even if you haven't done a
@code{ulimit -n 256} before starting @code{mysqld}.
@item
Added lots of limit checks to make it safer when running with too little
memory or when doing weird queries.
@end itemize

@node News-3.21.13, News-3.21.12, News-3.21.14a, News-3.21.x
@appendixsubsec Changes in release 3.21.13

@itemize @bullet
@item
Added retry of interrupted reads and clearing of @code{errno}.
This makes Linux systems much safer!
@item
Fixed locking bug when using many aliases on the same table in the same
@code{SELECT}.
@item
Fixed bug with @code{LIKE} on number key.
@item
New error message so you can check whether the connection was lost while
the command was running or whether the connection was down from the start.
@item
Added @code{--table} option to @code{mysql} to print in table format.
Moved time and row information after query result.
Added automatic reconnect of lost connections.
@item
Added @code{!=} as a synonym for @code{<>}.
@item
Added function @code{VERSION()} to make easier logs.
@item
New multi-user test @file{tests/fork_test.pl} to put some strain on the
thread library.
@end itemize

@node News-3.21.12, News-3.21.11, News-3.21.13, News-3.21.x
@appendixsubsec Changes in release 3.21.12

@itemize @bullet
@item
Fixed @code{ftruncate()} call in MIT-pthreads. This made @code{isamchk}
destroy the @file{.ISM} files on (Free)BSD 2.x systems.
@item
Fixed broken @code{__P_} patch in MIT-pthreads.
@item
Many memory overrun checks. All string functions now return @code{NULL}
if the returned string should be longer than @code{max_allowed_packet} bytes.
@item
Changed the name of the @code{INTERVAL} type to @code{ENUM}, because
@code{INTERVAL} is used in ANSI SQL.
@item
In some cases, doing a @code{JOIN} + @code{GROUP} + @code{INTO OUTFILE},
the result wasn't grouped.
@item
@code{LIKE} with @code{'_'} as last character didn't work. Fixed.
@item
Added extended ANSI SQL @code{TRIM()} function.
@item
Added @code{CURTIME()}.
@item
Added @code{ENCRYPT()} function by Zeev Suraski.
@item
Fixed better @code{FOREIGN KEY} syntax skipping. New reserved words:
@code{MATCH}, @code{FULL}, @code{PARTIAL}.
@item
@code{mysqld} now allows IP number and hostname to the @code{--bind-address}
option.
@item
Added @code{SET OPTION CHARACTER SET cp1251_koi8} to enable conversions of
data to/from cp1251_koi8.
@item
Lots of changes for Win95 port. In theory, this version should now be
easily portable to Win95.
@item
Changed the @code{CREATE COLUMN} syntax of @code{NOT NULL} columns to be after
the @code{DEFAULT} value, as specified in the ANSI SQL standard. This will
make @code{mysqldump} with @code{NOT NULL} and default values incompatible with
@strong{MySQL} 3.20.
@item
Added many function name aliases so the functions can be used with
ODBC or ANSI SQL92 syntax.
@item
Fixed syntax of @code{ALTER TABLE tbl_name ALTER COLUMN col_name SET DEFAULT
NULL}.
@item
Added @code{CHAR} and @code{BIT} as synonyms for @code{CHAR(1)}.
@item
Fixed core dump when updating as a user who has only @strong{select} privilege.
@item
@code{INSERT ... SELECT ... GROUP BY} didn't work in some cases. An
@code{Invalid use of group function} error occurred.
@item
When using @code{LIMIT}, @code{SELECT} now always uses keys instead of record
scan.  This will give better performance on @code{SELECT} and a @code{WHERE}
that matches many rows.
@item
Added Russian error messages.
@end itemize

@node News-3.21.11, News-3.21.10, News-3.21.12, News-3.21.x
@appendixsubsec Changes in release 3.21.11

@itemize @bullet
@item
Configure changes.
@item
@strong{MySQL} now works with the new thread library on BSD/OS 3.0.
@item
Added new group functions @code{BIT_OR()} and @code{BIT_AND()}.
@item
Added compatibility functions @code{CHECK} and @code{REFERENCES}.
@code{CHECK} is now a reserved word.
@item
Added @code{ALL} option to @code{GRANT} for better compatibility. (@code{GRANT}
is still a dummy function.)
@item
Added partly-translated dutch messages.
@item
Fixed bug in @code{ORDER BY} and @code{GROUP BY} with @code{NULL} columns.
@item
Added function @code{last_insert_id()} to retrieve last @code{AUTO_INCREMENT}
value.  This is intended for clients to ODBC that can't use the
@code{mysql_insert_id()} API function, but can be used by any client.
@item
Added @code{--flush-logs} option to @code{mysqladmin}.
@item
Added command @code{STATUS} to @code{mysql}.
@item
Fixed problem with @code{ORDER BY}/@code{GROUP BY} because of bug in @code{gcc}.
@item
Fixed problem with @code{INSERT ... SELECT ... GROUP BY}.
@end itemize

@node News-3.21.10, News-3.21.9, News-3.21.11, News-3.21.x
@appendixsubsec Changes in release 3.21.10

@itemize @bullet
@item
New @code{mysqlaccess}.
@item
@code{CREATE} now supports all ODBC types and the @code{mSQL} @code{TEXT} type.
All ODBC 2.5 functions are also supported (added @code{REPEAT}). This provides
better portability.
@item
Added text types @code{TINYTEXT}, @code{TEXT}, @code{MEDIUMTEXT} and
@code{LONGTEXT}.  These are actually @code{BLOB}types, but all searching is
done in case-insensitive fashion.
@item
All old @code{BLOB} fields are now @code{TEXT} fields.  This only
changes that all searching on strings is done in case-sensitive fashion.
You must do an @code{ALTER TABLE} and change the field type to @code{BLOB}
if you want to have tests done in case-sensitive fashion.
@item
Fixed some @code{configure} issues.
@item
Made the locking code a bit safer. Fixed very unlikely
deadlock situation.
@item
Fixed a couple of bugs in the range optimizer. Now the new range benchmark
@code{test-select} works.
@end itemize

@node News-3.21.9, News-3.21.8, News-3.21.10, News-3.21.x
@appendixsubsec Changes in release 3.21.9

@itemize @bullet
@item
Added @code{--enable-unix-socket=pathname} option to @code{configure}.
@item
Fixed a couple of portability problems with include files.
@item
Fixed bug in range calculation that could return empty
set when searching on multiple key with only one entry (very rare).
@item
Most things ported to FSU Pthreads, which should allow @strong{MySQL} to
run on SCO. @xref{SCO}.
@end itemize

@node News-3.21.8, News-3.21.7, News-3.21.9, News-3.21.x
@appendixsubsec Changes in release 3.21.8

@itemize @bullet
@item
Works now in Solaris 2.6.
@item
Added handling of calculation of @code{SUM()} functions.
For example, you can now use @code{SUM(column)/COUNT(column)}.
@item
Added handling of trigometric functions:
@code{PI()}, @code{ACOS()}, @code{ASIN()}, @code{ATAN()}, @code{COS()},
@code{SIN()} and @code{TAN()}.
@item
New languages: norwegian, norwegian-ny and portuguese.
@item
Fixed parameter bug in @code{net_print()} in @file{procedure.cc}.
@item
Fixed a couple of memory leaks.
@item
Now allow also the old @code{SELECT ... INTO OUTFILE} syntax.
@item
Fixed bug with @code{GROUP BY} and @code{SELECT} on key with many values.
@item
@code{mysql_fetch_lengths()} sometimes returned incorrect lengths when you used
@code{mysql_use_result()}. This affected at least some cases of
@code{mysqldump --quick}.
@item
Fixed bug in optimization of @code{WHERE const op field}.
@item
Fixed problem when sorting on @code{NULL} fields.
@item
Fixed a couple of 64-bit (Alpha) problems.
@item
Added @code{--pid-file=#} option to @code{mysqld}.
@item
Added date formatting to @code{FROM_UNIXTIME()}, originally by Zeev Suraski.
@item
Fixed bug in @code{BETWEEN} in range optimizer (Did only test = of the first
argument).
@item
Added machine-dependent files for MIT-pthreads i386-SCO. There is probably
more to do to get this to work on SCO 3.5.
@end itemize

@node News-3.21.7, News-3.21.6, News-3.21.8, News-3.21.x
@appendixsubsec Changes in release 3.21.7

@itemize @bullet
@item
Changed @file{Makefile.am} to take advantage of Automake 1.2.
@item
Added the beginnings of a benchmark suite.
@item
Added more secure password handling.
@item
Added new client function @code{mysql_errno()}, to get the error number of
the error message. This makes error checking in the client much easier.
This makes the new server incompatible with the 3.20.x server when running
without @code{--old-protocol}.  The client code is backward compatible.
More information can be found in the @file{README} file!
@item
Fixed some problems when using very long, illegal names.
@end itemize

@node News-3.21.6, News-3.21.5, News-3.21.7, News-3.21.x
@appendixsubsec Changes in release 3.21.6

@itemize @bullet
@item
Fixed more portability issues (incorrect @code{sigwait} and @code{sigset}
defines).
@item
@code{configure} should now be able to detect the last argument to
@code{accept()}.
@end itemize

@node News-3.21.5, News-3.21.4, News-3.21.6, News-3.21.x
@appendixsubsec Changes in release 3.21.5

@itemize @bullet
@item
Should now work with FreeBSD 3.0 if used with
@file{FreeBSD-3.0-libc_r-1.0.diff},
which can be found at @uref{http://www.mysql.com/Download/Patches}.
@item
Added new option @code{-O tmp_table_size=#} to @code{mysqld}.
@item
New function @code{FROM_UNIXTIME(timestamp)} which returns a date string in
'YYYY-MM-DD HH:MM:DD' format.
@item
New function @code{SEC_TO_TIME(seconds)} which returns a string in
'HH:MM:SS' format.
@item
New function @code{SUBSTRING_INDEX()}, originally by Zeev Suraski.
@end itemize

@node News-3.21.4, News-3.21.3, News-3.21.5, News-3.21.x
@appendixsubsec Changes in release 3.21.4

@itemize @bullet
@item
Should now configure and compile on OSF1 4.0 with the DEC compiler.
@item
Configuration and compilation on BSD/OS 3.0 works, but due to some bugs in
BSD/OS 3.0, @code{mysqld} doesn't work on it yet.
@item
Configuration and compilation on FreeBSD 3.0 works, but I couldn't get
@code{pthread_create} to work.
@end itemize

@node News-3.21.3, News-3.21.2, News-3.21.4, News-3.21.x
@appendixsubsec Changes in release 3.21.3

@itemize @bullet
@item
Added reverse check lookup of hostnames to get better security.
@item
Fixed some possible buffer overflows if filenames that are too long are used.
@item
@code{mysqld} doesn't accept hostnames that start with digits followed by a
@code{'.'}, because the hostname may look like an IP number.
@item
Added @code{--skip-networking} option to @code{mysqld}, to only allow socket
connections.  (This will not work with MIT-pthreads!)
@item
Added check of too long table names for alias.
@item
Added check if database name is okay.
@item
Added check if too long table names.
@item
Removed incorrect @code{free()} that killed the server on
@code{CREATE DATABASE} or @code{DROP DATABASE}.
@item
Changed some @code{mysqld} @code{-O} options to better names.
@item
Added @code{-O join_cache_size=#} option to @code{mysqld}.
@item
Added @code{-O max_join_size=#} option to @code{mysqld}, to be able to set a
limit how big queries (in this case big = slow) one should be able to handle
without specifying @code{SET OPTION SQL_BIG_SELECTS=1}.  A # = is about 10
examined records. The default is ``unlimited''.
@item
When comparing a @code{TIME}, @code{DATE}, @code{DATETIME} or @code{TIMESTAMP}
column to a constant, the constant is converted to a time value before
performing the comparison.
This will make it easier to get ODBC (particularly Access97) to work with
the above types. It should also make dates easier to use and the comparisons
should be quicker than before.
@item
Applied patch from Jochen Wiedmann that allows @code{query()} in
@code{mysqlperl} to take a query with @code{\0} in it.
@item
Storing a timestamp with a 2-digit year (@code{YYMMDD}) didn't work.
@item
Fix that timestamp wasn't automatically updated if set in an @code{UPDATE}
clause.
@item
Now the automatic timestamp field is the FIRST timestamp field.
@item
@code{SELECT * INTO OUTFILE}, which didn't correctly if the outfile already
existed.
@item
@code{mysql} now shows the thread ID when starting or doing a reconnect.
@item
Changed the default sort buffer size from 2M to 1M.
@end itemize

@node News-3.21.2, News-3.21.0, News-3.21.3, News-3.21.x
@appendixsubsec Changes in release 3.21.2

@itemize @bullet
@item
The range optimizer is coded, but only 85% tested. It can be enabled with
@code{--new}, but it crashes core a lot yet...
@item
More portable. Should compile on AIX and alpha-digital.
At least the @code{isam} library should be relatively 64-bit clean.
@item
New @code{isamchk} which can detect and fix more problems.
@item
New options for @code{isamlog}.
@item
Using new version of Automake.
@item
Many small portability changes (from the AIX and alpha-digital port)
Better checking of pthread(s) library.
@item
czech error messages by @email{snajdr@@pvt.net}.
@item
Decreased size of some buffers to get fewer problems on systems with little
memory.  Also added more checks to handle ``out of memory'' problems.
@item
@code{mysqladmin}: you can now do @code{mysqladmin kill 5,6,7,8} to kill
multiple threads.
@item
When the maximum connection limit is reached, one extra connection by a user
with the @strong{PROCESS_ACL} privilege is granted.
@item
Added @code{-O backlog=#} option to @code{mysqld}.
@item
Increased maximum packet size from 512K to 1024K for client.
@item
Almost all of the function code is now tested in the internal test suite.
@item
@code{ALTER TABLE} now returns warnings from field conversions.
@item
Port changed to 3306 (got it reserved from ISI).
@item
Added a fix for Visual FoxBase so that any schema name from a table
specification is automatically removed.
@item
New function @code{ASCII()}.
@item
Removed function @code{BETWEEN(a,b,c)}. Use the standard ANSI
synax instead: @code{expr BETWEEN expr AND expr}.
@item
@strong{MySQL} no longer has to use an extra temporary table when sorting
on functions or @code{SUM()} functions.
@item
Fixed bug that you couldn't use @code{tbl_name.field_name} in @code{UPDATE}.
@item
Fixed @code{SELECT DISTINCT} when using 'hidden group'. For example:
@example
mysql> SELECT DISTINCT MOD(some_field,10) FROM test
           GROUP BY some_field;
@end example
Note: @code{some_field} is normally in the @code{SELECT} part. ANSI SQL should
require it.
@end itemize

@node News-3.21.0,  , News-3.21.2, News-3.21.x
@appendixsubsec Changes in release 3.21.0

@itemize @bullet
@item
New keywords used: @code{INTERVAL}, @code{EXPLAIN}, @code{READ},
@code{WRITE}, @code{BINARY}.
@item
Added ODBC function @code{CHAR(num,...)}.
@item
New operator @code{IN}. This uses a binary search to find a match.
@item
New command @code{LOCK TABLES tbl_name [AS alias] @{READ|WRITE@} ...}
@item
Added @code{--log-update} option to @code{mysqld}, to get a log suitable for
incremental updates.
@item
New command @code{EXPLAIN SELECT ...} to get information about how the
optimizer will do the join.
@item
For easier client code, the client should no longer use
@code{FIELD_TYPE_TINY_BLOB}, @code{FIELD_TYPE_MEDIUM_BLOB},
@code{FIELD_TYPE_LONG_BLOB} or @code{FIELD_TYPE_VAR_STRING} (as
previously returned by @code{mysql_list_fields}).  You should instead only use
@code{FIELD_TYPE_BLOB} or @code{FIELD_TYPE_STRING}.  If you want exact
types, you should use the command @code{SHOW FIELDS}.
@item
Added varbinary syntax: @code{0x######} which can be used as a string
(default) or a number.
@item
@code{FIELD_TYPE_CHAR} is renamed to @code{FIELD_TYPE_TINY}.
@item
Changed all fields to C++ classes.
@item
Removed FORM struct.
@item
Fields with @code{DEFAULT} values no longer need to be @code{NOT NULL}.
@item
New field types:
@table @code
@item ENUM
A string which can take only a couple of defined values. The value is
stored as a 1-3 byte number that is mapped automatically to a string.
This is sorted according to string positions!
@item SET
A string which may have one or many string values separated with ','.
The string is stored as a 1-, 2-, 3-, 4- or 8-byte number where each bit stands
for a specific set member.  This is sorted according to the unsigned value
of the stored packed number.
@end table
@item
Now all function calculation is done with @code{double} or @code{long long}.
This will provide the full 64-bit range with bit functions and fix some
conversions that previously could result in precision losses.  One should
avoid using @code{unsigned long long} columns with full 64-bit range
(numbers bigger than 9223372036854775807) because calculations are done
with @code{signed long long}.
@item
@code{ORDER BY} will now put @code{NULL} field values first. @code{GROUP BY}
will also work with @code{NULL} values.
@item
Full @code{WHERE} with expressions.
@item
New range optimizer that can resolve ranges when some keypart prefix is
constant. Example:
@example
mysql> SELECT * FROM tbl_name
           WHERE key_part_1="customer"
           AND key_part_2>=10 AND key_part_2<=10;
@end example
@end itemize

@node News-3.20.x, News-3.19.x, News-3.21.x, News
@section Changes in release 3.20.x

Changes from 3.20.18 to 3.20.32b are not documented here since the
3.21 release branched here. And the relevant changes are also
documented as changes to the 3.21 version.

@menu
* News-3.20.18::                Changes in release 3.20.18
* News-3.20.17::                Changes in release 3.20.17
* News-3.20.16::                Changes in release 3.20.16
* News-3.20.15::                Changes in release 3.20.15
* News-3.20.14::                Changes in release 3.20.14
* News-3.20.13::                Changes in release 3.20.13
* News-3.20.11::                Changes in release 3.20.11
* News-3.20.10::                Changes in release 3.20.10
* News-3.20.9::                 Changes in release 3.20.9
* News-3.20.8::                 Changes in release 3.20.8
* News-3.20.7::                 Changes in release 3.20.7
* News-3.20.6::                 Changes in release 3.20.6
* News-3.20.3::                 Changes in release 3.20.3
* News-3.20.0::                 Changes in releases 3.20.0
@end menu

@node News-3.20.18, News-3.20.17, News-3.20.x, News-3.20.x
@appendixsubsec Changes in release 3.20.18

@itemize @bullet
@item
Added @code{-p#} (remove @code{#} directories from path) to @code{isamlog}.
All files are written with a relative path from the database directory
Now @code{mysqld} shouldn't crash on shutdown when using the
@code{--log-isam} option.
@item
New @code{mysqlperl} version. It is now compatible with @code{msqlperl-0.63}.
@item
New @code{DBD} module available at @uref{http://www.mysql.com/Contrib}
site.
@item
Added group function @code{STD()} (standard deviation).
@item
The @code{mysqld} server is now compiled by default without debugging
information.  This will make the daemon smaller and faster.
@item
Now one usually only has to specify the @code{--basedir} option to
@code{mysqld}. All other paths are relative in a normal installation.
@item
@code{BLOB} columns sometimes contained garbage when used with a @code{SELECT}
on more than one table and @code{ORDER BY}.
@item
Fixed that calculations that are not in @code{GROUP BY} work as expected
(ANSI SQL extension).
Example:
@example
mysql> SELECT id,id+1 FROM table GROUP BY id;
@end example
@item
The test of using @code{MYSQL_PWD} was reversed. Now @code{MYSQL_PWD} is
enabled as default in the default release.
@item
Fixed conversion bug which caused @code{mysqld} to core dump with
Arithmetic error on Sparc-386.
@item
Added @code{--unbuffered} option to @code{mysql}, for new @code{mysqlaccess}.
@item
When using overlapping (unnecessary) keys and join over many tables,
the optimizer could get confused and return 0 records.
@end itemize

@node News-3.20.17, News-3.20.16, News-3.20.18, News-3.20.x
@appendixsubsec Changes in release 3.20.17

@itemize @bullet
@item
You can now use @code{BLOB} columns and the functions @code{IS NULL} and
@code{IS NOT NULL} in the @code{WHERE} clause.
@item
All communication packages and row buffers are now allocated dynamically on
demand. The default value of @code{max_allowed_packet} is now 65K for the server
and 512K for the client. This is mainly used to catch incorrect packets that
could trash all memory. The server limit may be changed when it is started.
@item
Changed stack usage to use less memory.
@item
Changed @code{safe_mysqld} to check for running daemon.
@item
The @code{ELT()} function is renamed to @code{FIELD()}.  The new
@code{ELT()} function returns a value based on an index: @code{FIELD()}
is the inverse of @code{ELT()} Example: @code{ELT(2,"A","B","C")} returns
@code{"B"}. @code{FIELD("B","A","B","C")} returns @code{2}.
@item
@code{COUNT(field)}, where @code{field} could have a @code{NULL} value, now
works.
@item
A couple of bugs fixed in @code{SELECT ... GROUP BY}.
@item
Fixed memory overrun bug in @code{WHERE} with many unoptimizable brace levels.
@item
Fixed some small bugs in the grant code.
@item
If hostname isn't found by @code{get_hostname}, only the IP is checked.
Previously, you got @code{Access denied}.
@item
Inserts of timestamps with values didn't always work.
@item
@code{INSERT INTO ... SELECT ... WHERE} could give the error
@code{Duplicated field}.
@item
Added some tests to @code{safe_mysqld} to make it ``safer''.
@item
@code{LIKE} was case sensitive in some places and case insensitive in others.
Now @code{LIKE} is always case insensitive.
@item
@file{mysql.cc}: Allow @code{'#'} anywhere on the line.
@item
New command @code{SET OPTION SQL_SELECT_LIMIT=#}. See the FAQ for more details.
@item
New version of the @code{mysqlaccess} script.
@item
Change @code{FROM_DAYS()} and @code{WEEKDAY()} to also take a full
@code{TIMESTAMP} or @code{DATETIME} as argument. Before they only took a
number of type @code{YYYYMMDD} or @code{YYMMDD}.
@item
Added new function @code{UNIX_TIMESTAMP(timestamp_column)}.
@end itemize

@node News-3.20.16, News-3.20.15, News-3.20.17, News-3.20.x
@appendixsubsec Changes in release 3.20.16

@itemize @bullet
@item
More changes in MIT-pthreads to get them safer. Fixed also some link
bugs at least in SunOS.
@item
Changed @code{mysqld} to work around a bug in MIT-pthreads. This makes multiple
small @code{SELECT} operations 20 times faster. Now @code{lock_test.pl} should
work.
@item
Added @code{mysql_FetchHash(handle)} to @code{mysqlperl}.
@item
The @code{mysqlbug} script is now distributed built to allow for reporting
bugs that appear during the build with it.
@item
Changed @file{libmysql.c} to prefer @code{getpwuid()} instead of
@code{cuserid()}.
@item
Fixed bug in @code{SELECT} optimizer when using many tables with the same
column used as key to different tables.
@item
Added new latin2 and Russian KOI8 character tables.
@item
Added support for a dummy @code{GRANT} command to satisfy Powerbuilder.
@end itemize

@node News-3.20.15, News-3.20.14, News-3.20.16, News-3.20.x
@appendixsubsec Changes in release 3.20.15

@itemize @bullet
@item
Fixed fatal bug @code{packets out of order} when using MIT-pthreads.
@item
Removed possible loop when a thread waits for command from client
and @code{fcntl()} fails. Thanks to Mike Bretz for finding this bug.
@item
Changed alarm loop in @file{mysqld.cc} because shutdown didn't always
succeed in Linux.
@item
Removed use of @code{termbits} from @file{mysql.cc}.  This conflicted with
@code{glibc} 2.0.
@item
Fixed some syntax errors for at least BSD and Linux.
@item
Fixed bug when doing a @code{SELECT} as superuser without a database.
@item
Fixed bug when doing @code{SELECT} with group calculation to outfile.
@end itemize

@node News-3.20.14, News-3.20.13, News-3.20.15, News-3.20.x
@appendixsubsec Changes in release 3.20.14

@itemize @bullet
@item
If one gives @code{-p} or @code{--password} option to @code{mysql} without
an argument, the user is solicited for the password from the tty.
@item
Added default password from @code{MYSQL_PWD} (by Elmar Haneke).
@item
Added command @code{kill} to @code{mysqladmin} to kill a specific
@strong{MySQL} thread.
@item
Sometimes when doing a reconnect on a down connection this succeeded
first on second try.
@item
Fixed adding an @code{AUTO_INCREMENT} key with @code{ALTER_TABLE}.
@item
@code{AVG()} gave too small value on some @code{SELECT}s with
@code{GROUP BY} and @code{ORDER BY}.
@item
Added new @code{DATETIME} type (by Giovanni Maruzzelli
@email{maruzz@@matrice.it}).
@item
Fixed that define @code{DONT_USE_DEFAULT_FIELDS} works.
@item
Changed to use a thread to handle alarms instead of signals on Solaris to
avoid race conditions.
@item
Fixed default length of signed numbers. (George Harvey
@email{georgeh@@pinacl.co.uk}.)
@item
Allow anything for @code{CREATE INDEX}.
@item
Add prezeros when packing numbers to @code{DATE}, @code{TIME} and
@code{TIMESTAMP}.
@item
Fixed a bug in @code{OR} of multiple tables (gave empty set).
@item
Added many patches to MIT-pthreads. This fixes at least one lookup bug.
@end itemize

@node News-3.20.13, News-3.20.11, News-3.20.14, News-3.20.x
@appendixsubsec Changes in release 3.20.13

@itemize @bullet
@item
Added ANSI SQL94 @code{DATE} and @code{TIME} types.
@item
Fixed bug in @code{SELECT} with @code{AND}-@code{OR} levels.
@item
Added support for Slovenian characters. The @file{Contrib} directory contains
source and instructions for adding other character sets.
@item
Fixed bug with @code{LIMIT} and @code{ORDER BY}.
@item
Allow @code{ORDER BY} and @code{GROUP BY} on items that aren't in the
@code{SELECT} list.
(Thanks to Wim Bonis @email{bonis@@kiss.de}, for pointing this out.)
@item
Allow setting of timestamp values in @code{INSERT}.
@item
Fixed bug with @code{SELECT ... WHERE ... = NULL}.
@item
Added changes for @code{glibc} 2.0. To get @code{glibc} to work, you should
add the @file{gibc-2.0-sigwait-patch} before compiling @code{glibc}.
@item
Fixed bug in @code{ALTER TABLE} when changing a @code{NOT NULL} field to
allow @code{NULL} values.
@item
Added some ANSI92 synonyms as field types to @code{CREATE TABLE}.
@code{CREATE TABLE} now allows @code{FLOAT(4)} and @code{FLOAT(8)} to mean
@code{FLOAT} and @code{DOUBLE}.
@item
New utility program @code{mysqlaccess} by @email{Yves.Carlier@@rug.ac.be}.
This program shows the access rights for a specific user and the grant
rows that determine this grant.
@item
Added @code{WHERE const op field} (by @email{bonis@@kiss.de}).
@end itemize

@node News-3.20.11, News-3.20.10, News-3.20.13, News-3.20.x
@appendixsubsec Changes in release 3.20.11

@itemize @bullet
@item
When using @code{SELECT ... INTO OUTFILE}, all temporary tables are ISAM
instead of HEAP to allow big dumps.
@item
Changed date functions to be string functions. This fixed some ``funny''
side effects when sorting on dates.
@item
Extended @code{ALTER TABLE} according to SQL92.
@item
Some minor compability changes.
@item
Added @code{--port} and @code{--socket} options to all utility programs and
@code{mysqld}.
@item
Fixed MIT-pthreads @code{readdir_r()}. Now @code{mysqladmin create database}
and @code{mysqladmin drop database} should work.
@item
Changed MIT-pthreads to use our @code{tempnam()}. This should fix the ``sort
aborted'' bug.
@item
Added sync of records count in @code{sql_update}. This fixed slow updates
on first connection. (Thanks to Vaclav Bittner for the test.)
@end itemize

@node News-3.20.10, News-3.20.9, News-3.20.11, News-3.20.x
@appendixsubsec Changes in release 3.20.10

@itemize @bullet
@item
New insert type: @code{INSERT INTO ... SELECT ...}
@item
@code{MEDIUMBLOB} fixed.
@item
Fixed bug in @code{ALTER TABLE} and @code{BLOB}s.
@item
@code{SELECT ... INTO OUTFILE} now creates the file in the current
database directory.
@item
@code{DROP TABLE} now can take a list of tables.
@item
Oracle synonym @code{DESCRIBE} (@code{DESC}).
@item
Changes to @code{make_binary_distribution}.
@item
Added some comments to installation instructions about @code{configure}'s
C++ link test.
@item
Added @code{--without-perl} option to @code{configure}.
@item
Lots of small portability changes.
@end itemize

@node News-3.20.9, News-3.20.8, News-3.20.10, News-3.20.x
@appendixsubsec Changes in release 3.20.9

@itemize @bullet
@item
@code{ALTER TABLE} didn't copy null bit. As a result, fields that were allowed
to have @code{NULL} values were always @code{NULL}.
@item
@code{CREATE} didn't take numbers as @code{DEFAULT}.
@item
Some compatibility changes for SunOS.
@item
Removed @file{config.cache} from old distribution.
@end itemize

@node News-3.20.8, News-3.20.7, News-3.20.9, News-3.20.x
@appendixsubsec Changes in release 3.20.8

@itemize @bullet
@item
Fixed bug with @code{ALTER TABLE} and multi-part keys.
@end itemize

@node News-3.20.7, News-3.20.6, News-3.20.8, News-3.20.x
@appendixsubsec Changes in release 3.20.7

@itemize @bullet
@item
New commands: @code{ALTER TABLE}, @code{SELECT ... INTO OUTFILE} and
@code{LOAD DATA INFILE}.
@item
New function: @code{NOW()}.
@item
Added new field @strong{file_priv} to @code{mysql/user} table.
@item
New script @code{add_file_priv} which adds the new field @strong{file_priv}
to the @code{user} table. This script must be executed if you want to
use the new @code{SELECT ... INTO} and @code{LOAD DATA INFILE ...} commands
with a version of @strong{MySQL} earlier than 3.20.7.
@item
Fixed bug in locking code, which made @code{lock_test.pl} test fail.
@item
New files @file{NEW} and @file{BUGS}.
@item
Changed @file{select_test.c} and @file{insert_test.c} to include
@file{config.h}.
@item
Added command @code{status} to @code{mysqladmin} for short logging.
@item
Increased maximum number of keys to 16 and maximum number of key parts to 15.
@item
Use of sub keys. A key may now be a prefix of a string field.
@item
Added @code{-k} option to @code{mysqlshow}, to get key information for a table.
@item
Added long options to @code{mysqldump}.
@end itemize

@node News-3.20.6, News-3.20.3, News-3.20.7, News-3.20.x
@appendixsubsec Changes in release 3.20.6

@itemize @bullet
@item
Portable to more systems because of MIT-pthreads, which will
be used automatically if @code{configure} cannot find a @code{-lpthreads}
library.
@item
Added GNU-style long options to almost all programs. Test with
@code{@kbd{program} --help}.
@item
Some shared library support for Linux.
@item
The FAQ is now in @file{.texi} format and is available in @file{.html},
@file{.txt} and @file{.ps} formats.
@item
Added new SQL function @code{RAND([init])}.
@item
Changed @code{sql_lex} to handle @code{\0} unquoted, but the client can't send
the query through the C API, because it takes a str pointer.
You must use @code{mysql_real_query()} to send the query.
@item
Added API function @code{mysql_get_client_info()}.
@item
@code{mysqld} now uses the @code{N_MAX_KEY_LENGTH} from @file{nisam.h} as
the maximum allowed key length.
@item
The following now works:
@example
mysql> SELECT filter_nr,filter_nr FROM filter ORDER BY filter_nr;
@end example
Previously, this resulted in the error:
@code{Column: 'filter_nr' in order clause is ambiguous}.
@item
@code{mysql} now outputs @code{'\0'}, @code{'\t'}, @code{'\n'} and @code{'\\'}
when encountering ASCII 0, tab, newline or @code{'\'} while writing
tab-separated output.
This is to allow printing of binary data in a portable format.
To get the old behavior, use @code{-r} (or @code{--raw}).
@item
Added german error messages (60 of 80 error messages translated).
@item
Added new API function @code{mysql_fetch_lengths(MYSQL_RES *)}, which
returns an array of of column lengths (of type @code{uint}).
@item
Fixed bug with @code{IS NULL} in @code{WHERE} clause.
@item
Changed the optimizer a little to get better results when searching on a key
part.
@item
Added @code{SELECT} option @code{STRAIGHT_JOIN} to tell the optimizer that
it should join tables in the given order.
@item
Added support for comments starting with @code{'--'} in @file{mysql.cc}
(Postgres syntax).
@item
You can have @code{SELECT} expressions and table columns in a @code{SELECT}
which are not used in the group part. This makes it efficient to implement
lookups.  The column that is used should be a constant for each group because
the value is calculated only once for the first row that is found for a group.
@example
mysql> SELECT id,lookup.text,sum(*) FROM test,lookup
         WHERE test.id=lookup.id GROUP BY id;
@end example
@item
Fixed bug in @code{SUM(function)} (could cause a core dump).
@item
Changed @code{AUTO_INCREMENT} placement in the SQL query:
@example
INSERT into table (auto_field) values (0);
@end example
inserted 0, but it should insert an @code{AUTO_INCREMENT} value.
@item
@file{mysqlshow.c}: Added number of records in table. Had to change the
client code a little to fix this.
@item
@code{mysql} now allows doubled @code{''} or @code{""} within strings for
embedded @code{'} or @code{"}.
@item
New math functions:
@code{EXP()}, @code{LOG()}, @code{SQRT()}, @code{ROUND()}, @code{CEILING()}.
@end itemize

@node News-3.20.3, News-3.20.0, News-3.20.6, News-3.20.x
@appendixsubsec Changes in release 3.20.3

@itemize @bullet
@item
The @code{configure} source now compiles a thread-free client library
@code{-lmysqlclient}. This is the only library that needs to be linked
with client applications.  When using the binary releases, you must
link with @code{-lmysql -lmysys -ldbug -lstrings} as before.
@item
New @code{readline} library from @code{bash-2.0}.
@item
LOTS of small changes to @code{configure} and makefiles (and related source).
@item
It should now be possible to compile in another directory using
@code{VPATH}. Tested with GNU Make 3.75.
@item
@code{safe_mysqld} and @code{mysql.server} changed to be more compatible
between the source and the binary releases.
@item
@code{LIMIT} now takes one or two numeric arguments.
If one argument is given, it indicates the maximum number of rows in
a result. If two arguments are given, the first argument indicates the offset
of the first row to return, the second is the maximum number of rows.
With this it's easy to do a poor man's next page/previous page WWW
application.
@item
Changed name of SQL function @code{FIELDS()} to @code{ELT()}.
Changed SQL function @code{INTERVALL()} to @code{INTERVAL()}.
@item
Made @code{SHOW COLUMNS} a synonym for @code{SHOW FIELDS}.
Added compatibility syntax @code{FRIEND KEY} to @code{CREATE TABLE}. In
@strong{MySQL}, this creates a non-unique key on the given columns.
@item
Added @code{CREATE INDEX} and @code{DROP INDEX} as compatibility functions.
In @strong{MySQL}, @code{CREATE INDEX} only checks if the index exists and
issues an error if it doesn't exist. @code{DROP INDEX} always succeeds.
@item
@file{mysqladmin.c}: added client version to version information.
@item
Fixed core dump bug in @code{sql_acl} (core on new connection).
@item
Removed @code{host}, @code{user} and @code{db} tables from database @code{test}
in the distribution.
@item
@code{FIELD_TYPE_CHAR} can now be signed (-128 - 127) or unsigned (0 - 255)
Previously, it was always unsigned.
@item
Bug fixes in @code{CONCAT()} and @code{WEEKDAY()}.
@item
Changed a lot of source to get @code{mysqld} to be compiled with SunPro
compiler.
@item
SQL functions must now have a @code{'('} immediately after the function name
(no intervening space).
For example, @code{'user('} is regarded as beginning a function call, and
@code{'user ('} is regarded as an identifier @code{user} followed by a
@code{'('}, not as a function call.
@end itemize

@node News-3.20.0,  , News-3.20.3, News-3.20.x
@appendixsubsec Changes in release 3.20.0

@itemize @bullet
@item
The source distribution is done with @code{configure} and Automake.
It will make porting much easier.  The @code{readline} library is included
in the distribution.
@item
Separate client compilation:
the client code should be very easy to compile on systems which
don't have threads.
@item
The old Perl interface code is automatically compiled and installed.
Automatic compiling of @code{DBD} will follow when the new @code{DBD} code
is ported.
@item
Dynamic language support: @code{mysqld} can now be started with Swedish
or English (default) error messages.
@item
New functions: @code{INSERT()}, @code{RTRIM()}, @code{LTRIM()} and
@code{FORMAT()}.
@item
@code{mysqldump} now works correctly for all field types (even
@code{AUTO_INCREMENT}). The format for @code{SHOW FIELDS FROM tbl_name} is changed
so the @code{Type} column contains information suitable for @code{CREATE TABLE}.
In previous releases, some @code{CREATE TABLE} information had to be patched
when recreating tables.
@item
Some parser bugs from 3.19.5 (@code{BLOB} and @code{TIMESTAMP}) are corrected.
@code{TIMESTAMP} now returns different date information depending on its
create length.
@item
Changed parser to allow a database, table or field name to
start with a number or @code{'_'}.
@item
All old C code from Unireg changed to C++ and cleaned up. This makes
the daemon a little smaller and easier to understand.
@item
A lot of small bug fixes done.
@item
New INSTALL files (not final version) and some info regarding porting.
@end itemize

@node News-3.19.x,  , News-3.20.x, News
@appendixsec Changes in release 3.19.x

@menu
* News-3.19.5::                 Changes in release 3.19.5
* News-3.19.4::                 Changes in release 3.19.4
* News-3.19.3::                 Changes in release 3.19.3
@end menu

@node News-3.19.5, News-3.19.4, News-3.19.x, News-3.19.x
@appendixsubsec Changes in release 3.19.5

@itemize @bullet
@item
Some new functions, some more optimization on joins.
@item
Should now compile clean on Linux (2.0.x).
@item
Added functions @code{DATABASE()}, @code{USER()}, @code{POW()},
@code{LOG10()} (needed for ODBC).
@item
In a @code{WHERE} with an @code{ORDER BY} on fields from only one table,
the table is now preferred as first table in a multi-join.
@item
@code{HAVING} and @code{IS NULL} or @code{IS NOT NULL} now works.
@item
A group on one column and a sort on a group function (@code{SUM()},
@code{AVG()}...) didn't work together. Fixed.
@item
@code{mysqldump}: Didn't send password to server.
@end itemize

@node News-3.19.4, News-3.19.3, News-3.19.5, News-3.19.x
@appendixsubsec Changes in release 3.19.4

@itemize @bullet
@item
Fixed horrible locking bug when inserting in one thread and reading
in another thread.
@item
Fixed one-off decimal bug.  1.00 was output as 1.0.
@item
Added attribute @code{'Locked'} to process list as info if a query is
locked by another query.
@item
Fixed full magic timestamp. Timestamp length may now be 14, 12, 10, 8, 6, 4
or 2 bytes.
@item
Sort on some numeric functions could sort incorrectly on last number.
@item
@code{IF(arg,syntax_error,syntax_error)} crashed.
@item
Added functions @code{CEILING()}, @code{ROUND()}, @code{EXP()}, @code{LOG()} and @code{SQRT()}.
@item
Enhanced @code{BETWEEN} to handle strings.
@end itemize

@node News-3.19.3,  , News-3.19.4, News-3.19.x
@appendixsubsec Changes in release 3.19.3

@itemize @bullet
@item
Fixed @code{SELECT} with grouping on @code{BLOB} columns not to return
incorrect @code{BLOB} info. Grouping, sorting and distinct on @code{BLOB}
columns will not yet work as
expected (probably it will group/sort by the first 7 characters in the
@code{BLOB}). Grouping on formulas with a fixed string size (use @code{MID()}
on a @code{BLOB}) should work.
@item
When doing a full join (no direct keys) on multiple tables with @code{BLOB}
fields, the @code{BLOB} was garbage on output.
@item
Fixed @code{DISTINCT} with calculated columns.
@end itemize

@node Bugs, TODO, News, Top
@appendix Known errors and design deficiencies in @strong{MySQL}

@itemize @bullet
@item
You cannot build in another directory when using
MIT-pthreads. Since this requires changes to MIT-pthreads, we are not
likely to fix this.
@item
@code{BLOB} values can't ``reliably'' be used in @code{GROUP BY} or
@code{ORDER BY} or @code{DISTINCT}. Only the first @code{max_sort_length}
bytes (default 1024) are used when comparing @code{BLOB}bs in these cases.
This can be changed with the @code{-O max_sort_length} option to
@code{mysqld}. A workaround for most cases is to use a substring:
@code{SELECT DISTINCT LEFT(blob,2048) FROM tbl_name}.
@item
Calculation is done with @code{BIGINT} or @code{DOUBLE} (both are
normally 64 bits long). It depends on the function which precision one
gets. The general rule is that bit functions are done with @code{BIGINT}
precision, @code{IF}, and @code{ELT()} with @code{BIGINT} or @code{DOUBLE}
precision and the rest with @code{DOUBLE} precision.  One should try to
avoid using bigger unsigned long long values than 63 bits
(9223372036854775807) for anything else than bit fields!
@item
All numeric types are treated as fixed-point fields. That means you must
specify how many decimals a floating-point field shall have. All results will
be returned with the correct number of decimals. (@strong{MySQL} 3.23 supports
floating-point columns).
@item
All string columns, except @code{BLOB} and @code{TEXT} columns, automatically
have all trailing spaces removed when retrieved. For @code{CHAR} types this
is okay, and may be regarded as a feature according to ANSI SQL92. The bug is
that in @strong{MySQL}, @code{VARCHAR} columns are treated the same way.
@item
You can only have up to 255 @code{ENUM} and @code{SET} columns in one table.
@item
An @code{UPDATE} that updates a key with a @code{WHERE} on the same key may
fail because the key is used to search for records and will be found
multiple times:

@example
UPDATE tbl_name SET KEY=KEY+1 WHERE KEY > 100;
@end example

This will be fixed in newer @strong{MySQL} versions by not using keys
that contain fields that are going to be updated.

Until this fixed you can use the current workaround:

@example
mysql> UPDATE tbl_name SET KEY=KEY+1 WHERE KEY+0 > 100;
@end example

This will work because @strong{MySQL} will not use index on expressions in
the @code{WHERE} clause.
@item
@code{safe_mysqld} re-directs all messages from @code{mysqld} to the
@code{mysqld} log.  One problem with this is that if you execute
@code{mysqladmin refresh} to close and reopen the log,
@code{stdout} and @code{stderr} are still redirected to the old log.
If you use @code{--log} extensively, you should edit @code{safe_mysqld} to
log to @file{'hostname'.err} instead of @file{'hostname'.log} so you can
easily reclaim the space for the old log by deleting the old one and
executing @code{mysqladmin refresh}.
@item
In the @code{UPDATE} statement, columns are updated from left to right.
If you refer to a updated column, you will get the updated value instead of the
original value. For example:
@example
mysql> UPDATE tbl_name SET KEY=KEY+1,KEY=KEY+1
@end example
will update @code{KEY} with @code{2} instead of with @code{1}.
@end itemize

For platform-specific bugs, see the sections about compiling and porting.

@cindex TODO
@node TODO, Porting, Bugs, Top
@appendix List of things we want to add to @strong{MySQL} in the future (The TODO)

@menu
* TODO future::                 Things that must done in the real near future
* TODO sometime::               Things that have to be done sometime
* TODO unplanned::              Some things we don't have any plans to do
@end menu

Everything in this list is in the order it will be done.  If you want to
affect the priority order, please register a license or support us and
tell us what you want to have done more quickly. @xref{Licensing and Support}.

@node TODO future, TODO sometime, TODO, TODO
@appendixsec Things that must done in the real near future

@itemize @bullet
@item
Binary compatible ISAM tables.
@item
Subqueries. @code{select id from t where grp in (select grp from g where u > 100)}
@item
If you perform an @code{ALTER TABLE} on a table that is symlinked to another
disk, create temporary tables on this disk.
@item
FreeBSD and MIT-pthreads;  Do sleeping threads take CPU?
@item
Allow join on key parts (optimization issue).
@item
Automatically convert temporary HEAP tables to NISAM if
they get too big. At the moment you get @code{error 135} or @code{Table
xxx is full}
if you execute a query which has to use a big temporary table.
@item
Binary portable data tables (a new version of ISAM).
@item
Add @code{DISTINCT} qualifier to @code{COUNT()}, @code{SUM()}, ...
@item
Change conv_blob to handle @code{BLOB} as a @code{TEXT} field.
@item
Entry for @code{DECRYPT()}.
@item
Remember @code{FOREIGN} key definitions in the @file{.frm} file.
@item
Server side cursors.
@item
Allow users to change startup options.
@item
Add --ansi option to MySQL (to change || -> CONCAT())
@item
Don't add automatic @code{DEFAULT} values to columns.  Give an error when using
an @code{INSERT} that doesn't contain a column that doesn't have a
@code{DEFAULT}.
@item
Caching of queries and results. This should be done as a separated
module that examines each query and if this is query is in the cache
the cached result should be returned.  When one updates a table one
should remove as few queries as possible from the cache.
This should give a big speed bost on machines with much RAM where
queries are often repeated (like WWW applications).
One idea would be to only cache queries of type:
@code{SELECT CACHED ....}
@item
Fix @file{libmysql.c} to allow two @code{mysql_query()} commands in a row
without reading results or give a nice error message when one does this.
@item
Optimize @code{BIT} type to take 1 bit (now @code{BIT} takes 1 char).
@item
Check why MIT-pthreads @code{ctime()} doesn't work on some FreeBSD systems.
@item
Check if locked threads take any CPU.
@item
Add @code{ORDER BY} to update. This would be handy with functions like:
@code{generate_id(start,step)}.
@item
Add an @code{IMAGE} option to @code{LOAD DATA INFILE} to not update
@code{TIMESTAMP} and @code{AUTO_INCREMENT} fields.
@item
Make @code{LOAD DATA INFILE} understand a syntax like:
@example
LOAD DATA INFILE 'file_name.txt' INTO TABLE tbl_name
TEXT_FIELDS (text_field1, text_field2, text_field3)
SET table_field1=concatenate(text_field1, text_field2), table_field3=23
IGNORE text_field3
@end example
@item
Allow strings with @code{MIN()}, @code{MAX()} (not group functions).
These should be synonyms for @code{LEAST()}, @code{GREATEST()}.
@item
Demo procedure: analyze
@item
Automatic output from @code{mysql} to netscape.
@item
@code{LOCK DATABASES}. (with various options)
@item
@code{NATURAL JOIN}.
@item
Change sort to allocate memory in ``hunks'' to get better memory utilization.
@item
@code{DECIMAL} and @code{NUMERIC} types can't read exponential numbers;
@code{Field_decimal::store(const char *from,uint len)} must be recoded
to fix this.
@item
Fix @code{mysql.cc} to do fewer @code{malloc()} calls when hashing field
names.
@item
Add functions:
@example
EXPORT_SET(set_column,'Y','N',[separator],[number_of_set_values])
@end example
where @code{separator} is @code{','} by default and
@code{number_of_set_values} is taken from the @code{set_column} (or is
64 if @code{set_column} is an expression). For example:

@example
EXPORT_SET(9,'Y','N',',',5) -> Y,N,N,Y,N
@end example
@item
Add use of @code{t1 JOIN t2 ON ...} and @code{t1 JOIN t2 USING ...}
Currently, you can only use this syntax with @code{LEFT JOIN}.
@item
Add full support for @code{unsigned long long} type.
@item
A @code{LOCK DATABASE} function (for backups).
@item
Function @code{CASE}.
@item
Many more variables for @code{show status}.  Counts for:
@code{INSERT}/@code{DELETE}/@code{UPDATE} statements. Records reads and updated.
Selects on 1 table and selects with joins.  Mean number of tables in
select. Key buffer read/write hits (logical and real).
@code{ORDER BY}, @code{GROUP BY}, temporary tables created.
@item
If you abort @code{mysql} in the middle of a query, you should open
another connection and kill the old running query.
Alternatively, an attempt should be made to detect this in the server.
@item
Add optimization to make @code{LEFT JOIN ..  WHERE not_null_field IS NULL} much
faster. (This is often used to find rows that don't match)
@item
Add a handler interface for table information so you can use it as a system
table. This would be a bit slow if you requested information about all tables,
but very flexible.  @code{SHOW INFO FROM tbl_name} for basic table information
should be implemented.
@item
Allow @code{mysqld} to support many character sets at the same time.
@item
Add support for UNICODE.
@item
@code{NATURAL JOIN}.
@item
Oracle like @code{CONNECT BY PRIOR ...} to search hierarchy structures.
@item
@code{RENAME DATABASE}
@item
@code{mysqladmin copy database new-database}.
@item
Processlist should show number of queries/thread.
@item
@code{IGNORE} option to the @code{UPDATE} statement (this will delete
all rows that gets a dupplicate key error while updating).
@item
@code{select distinct a from foo order by b} should not return duplicate
rows, if there are different pairs of (a,b)
@item
Change the format of @code{DATETIME} to store fractions of seconds.
@item
Add all missing ANSI92 and ODBC 3.0 types.
@item
Change table names from empty strings to @code{NULL} for calculated columns.
@end itemize

@node TODO sometime, TODO unplanned, TODO future, TODO
@appendixsec Things that have to be done sometime

@itemize @bullet
@item
Implement a table optimizer by an analyze procedure call that returns a
table like show fields with min and max value and the best
@strong{MySQL} type for that expression.
@item
Implement function: @code{get_changed_tables(timeout,table1,table2,...)}
@item
Implement function: @code{LAST_UPDATED(tbl_name)}
@item
Atomic updates; This includes a language that one can even use for
a set of stored procedures.
@item
@code{update items,month set items.price=month.price where items.id=month.id;}
@item
Change reading through tables to use memmap when possible. Now only
compressed tables use memmap.
@item
Make a SQL standard @code{GRANT} command with @strong{MySQL} extensions.
@item
Add a new privilege @strong{'Show_priv'} for @code{SHOW} commands.
@item
Make the automatic timestamp code nicer.  Add timestamps to the update
log with @code{SET TIMESTAMP=#;}
@item
Optimize the autoincrement code.
@item
Use read/write mutex in some places to get more speed.
@item
Full foreign key support. One probably wants to implement a procedural
language first.
@item
Simple views (first on one table, later on any expression).
@item
Automatically close some tables if a table, temporary table or temporary files
gets error 23 (not enough open files).
@item
When one finds a field=#, change all occurrences of field to #.  Now this
is only done for some simple cases.
@item
Change all const expressions with calculated expressions if possible.
@item
Optimize key = expression. At the moment only key = field or key =
constant are optimized.
@item
Join some of the copy functions for nicer code.
@item
Change @file{sql_yacc.yy} to an inline parser to reduce its size and get
better error messages (5 days).
@item
Change the parser to use only one rule per different number of arguments
in function.
@item
Use of full calculation names in the order part. (For ACCESS97)
@item
@code{UNION}, @code{MINUS}, @code{INTERSECT} and @code{FULL OUTER JOIN}.
(Currently only @code{LEFT OUTER JOIN} is supported)
@item
Allow @code{UNIQUE} on fields that can be @code{NULL}.
@item
@code{SQL_OPTION MAX_SELECT_TIME=#} to put a time limit on a query.
@item
Make the update log to a database.
@item
Negative @code{LIMIT} to retrieve data from the end.
@item
Alarm around client connect/read/write functions.
@item
Make a @code{mysqld} version which isn't multithreaded (3-5 days).
@item
Please note the changes to @code{safe_mysqld}: according to FSSTND (which
Debian tries to follow) PID files should go into @file{/var/run/<progname>.pid}
and log files into @file{/var/log}. It would be nice if you could put the
"DATADIR" in the first declaration of "pidfile" and "log", so the
placement of these files can be changed with a single statement.
@item
Better dynamic record layout to avoid fragmentation.
@item
@code{UPDATE SET blob=read_blob_from_file('my_gif') where id=1;}
@item
Allow sorting on @code{RAND()}:

@example
SELECT email,RAND() AS ran FROM info ORDER BY ran;
@end example
@item
Allow a client to request logging.
@item
Add use of @code{zlib()} for @code{gzip}-ed files to @code{LOAD DATA INFILE}.
@item
Fix sorting and grouping of @code{BLOB} columns (partly solved now).
@item
Stored procedures.  This is currently not regarded to be very
important as stored procedures are not very standardized yet.
Another problem is that true stored procedures make it much harder for
the optimizer and in many cases the result is slower than before
We will, on the other hand, add a simple (atomic) update language that
can be used to write loops and such in the @strong{MySQL} server.
@item
Change to use semaphores when counting threads.  One should first implement
a semaphore library to MIT-pthreads.
@item
Don't assign a new @code{AUTO_INCREMENT} value when one sets a column to 0.
Use @code{NULL} instead.
@item
Add full support for @code{JOIN} with parentheses.
@item
Reuse threads for system with a lot of connections.
@end itemize

Time is given according to amount of work, not real time. TcX's main
business is the use of @strong{MySQL} not the development of it. But
since TcX is a very flexible company, we have put a lot of resources
into the development of @strong{MySQL}.

@node TODO unplanned,  , TODO sometime, TODO
@appendixsec Some things we don't have any plans to do

@itemize @bullet
@item
Transactions with rollback (we mainly do @code{SELECT}s, and because we don't
do transactions, we can be much quicker on everything else). We will
support some kind of atomic operations on multiple tables,
though. Currently atomic operations can be done with @code{LOCK
TABLES}/@code{UNLOCK TABLES} but we will make this more automatic in the
future.
@end itemize

@node Porting, Regexp, TODO, Top
@appendix Comments on porting to other systems

A working Posix thread library is needed for the server. On Solaris 2.5
we use SUN PThreads (the native thread support in 2.4 and earlier
versions are not good enough) and on Linux we use LinuxThreads by Xavier
Leroy, @email{Xavier.Leroy@@inria.fr}.

The hard part of porting to a new Unix variant without good native
thread support is probably to port MIT-pthreads. See
@file{mit-pthreads/README} and
@uref{http://www.humanfactor.com/pthreads/, Programming POSIX Threads}.

The @strong{MySQL} distribution includes a patched version of
Provenzano's Pthreads from MIT (see
@uref{http://www.mit.edu:8001/people/proven/pthreads.html, MIT Pthreads
web page}). This can be used for some operating systems that do not
have POSIX threads.

It is also possible to use another user level thread package named
FSU Pthreads (see
@uref{http://www.informatik.hu-berlin.de/~mueller/pthreads.html, FSU Pthreads
home page}). This implementation is being used for the SCO port.

See the @file{thr_lock.c} and @file{thr_alarm.c} programs in the @file{mysys}
directory for some tests/examples of these problems.

Both the server and the client need a working C++ compiler (we use @code{gcc}
and have tried SparcWorks). Another compiler that is known to work is the
Irix @code{cc}.

To compile only the client use @code{./configure --without-server}.

There is currently no support for only compiling the server. Nor is it
likly to be added unless someone has a good reason for it.

If you want/need to change any @file{Makefile} or the configure script you must
get Automake and Autoconf. We have used the @code{automake-1.2} and
@code{autoconf-2.12} distributions.

All steps needed to remake everything from the most basic files.

@example
/bin/rm */.deps/*.P
/bin/rm -f config.cache
aclocal
autoheader
aclocal
automake
autoconf
./configure --with-debug --prefix='your installation directory'

# The makefiles generated above need GNU make 3.75 or newer.
# (called gmake below)
gmake clean all install init-db
@end example

If you run into problems with a new port, you may have to do some debugging
of @strong{MySQL}!
@xref{Debugging server}.

@strong{Note:} Before you start debugging @code{mysqld}, first get the test
programs @code{mysys/thr_alarm} and @code{mysys/thr_lock} to work.  This
will ensure that your thread installation has even a remote chance to work!

@menu
* Debugging server::            Debugging a @strong{MySQL} server
* Debugging client::            Debugging a @strong{MySQL} client
* RTS-threads::                 Comments about RTS threads
* Thread packages::             Differences between different thread packages
@end menu

@node Debugging server, Debugging client, Porting, Porting
@appendixsec Debugging a @strong{MySQL} server

If you are using some functionality that is very new in @strong{MySQL},
you can try to run mysqld with the @code{--skip-new} (which will disable all
new, potentially unsafe functionality) or with @code{--safe-mode} which
disables a lot of optimization that may cause problems.
@xref{Crashing}.

If @code{mysqld} doesn't want to start, you should check that you don't have
any @code{my.cnf} file that interferes with your setup!
You can check your @code{my.cnf} arguments with @code{mysqld --print-defaults}
and avoid using them by starting with @code{mysqld --no-defaults ...}.

If you have some very specific problem, you can always try to debug
@strong{MySQL}.  To do this you must configure @strong{MySQL} with the
option @code{--with-debug}.  You can check whether or not
@strong{MySQL} was compiled with debugging by doing: @code{mysqld
--help}.  If the @code{--debug} flag is listed with the options then you
have debugging enabled.  @code{mysqladmin ver} also lists the
@code{mysqld} version as @code{mysql ... -debug} in this case.

If you are using gcc or egcs, the recommended configure line is:

@example
CC=gcc CFLAGS="-O6" CXX=gcc CXXFLAGS="-O6 -felide-constructors -fno-exceptions -fno-rtti" ./configure --prefix=/usr/local/mysql --with-debug
@end example

This will avoid problems with the libstdc++ library and with C++ exceptions.

If you can cause the @code{mysqld} server to crash quickly, you can try to
create a trace file of this:

Start the @code{mysqld} server with a trace log in @file{/tmp/mysql.trace}.
The log file will get very @emph{BIG}.

@code{mysqld --debug --log}

or you can start it with

@code{mysqld --debug=d,info,error,query,general,where:O,/tmp/mysql.trace}

which only prints information with the most interesting tags.

When you configure @strong{MySQL} for debugging you automatically enable a
lot of extra safety check functions that monitor the health of @code{mysqld}.
If they find something ``unexpected,'' an entry will be written to
@code{stderr}, which @code{safe_mysqld} directs to the error log!  This also
means that if you are having some unexpected problems with @strong{MySQL} and
are using a source distribution, the first thing you should do is to
configure @strong{MySQL} for debugging!  (The second thing, of course, is to
send mail to @email{mysql@@lists.mysql.com} and ask for help.  Please use the
@code{mysqlbug} script for all bug reports or questions regarding the
@strong{MySQL} version you are using!

On most system you can also start @code{mysqld} from @code{gdb} to get
more information if @code{mysqld} crashes.

With some @code{gdb} versions on Linux you must use @code{run --one-thread} if
you want to be able to debug @code{mysqld} threads.  In this case you
can only have one thread active at a time.

If you are using gdb 4.17.x on Linux, you should install a @file{.gdb} file,
with the following information, in your current directory:

@example
set print sevenbit off
handle SIGUSR1 nostop noprint
handle SIGUSR2 nostop noprint
handle SIGWAITING nostop noprint
handle SIGLWP nostop noprint
handle SIGPIPE nostop
handle SIGALRM nostop
handle SIGHUP nostop
handle SIGTERM nostop noprint
@end example

Here follows an example how to debug mysqld:

@example
shell> gdb /usr/local/libexec/mysqld
gdb> run
...
back   # Do this when mysqld crashes
info locals
up
info locals
up
...
(until you get some information about local variables)

quit
@end example

Include the above output in a mail generated with @code{mysqlbug} and
mail this to @code{mysql@@lists.mysql.com}.

If @code{mysqld} hangs you can try to use some system tools like
@code{strace} or @code{/usr/proc/bin/pstack} to examine where
@code{mysqld} has hanged.

If @code{mysqld} starts to eat up CPU or memory or if it ``hangs'', you
can use @code{mysqladmin processlist status} to find out if someone is
executing some query that takes a long time.  It may be a good idea to
run @code{mysqladmin -i10 processlist status} in some window if you are
experiencing performance problems or problems when new clients can't connect.

If @code{mysqld} dies or hangs, you should start @code{mysqld} with
@code{--log}.  When @code{mysqld} dies again, you can check in the log file
for the query that killed @code{mysqld}.  Note that before starting
@code{mysqld} with @code{--log} you should check all your tables with
@code{isamchk}.  @xref{Maintenance}.

If you are using a log file, @code{mysqld --log}, you should check the
'hostname' log files, that you can find in the database directory, for
any queries that could cause a problem. Try the command @code{EXPLAIN}
on all @code{SELECT} statements that takes a long time to ensure that
mysqld are using indexes properly. @xref{EXPLAIN, , @code{EXPLAIN}}. You
should also test complicated queries that didn't complete within the
@code{mysql} command line tool.

If you find the text @code{mysqld restarted} in the error log file (normally
named @file{hostname.err}) you have probably found a query that causes
@code{mysqld} to fail.  If this happens you should check all your tables with
@code{isamchk} (@pxref{Maintenance}), and test the queries in the
@strong{MySQL} log files if someone doesn't work.  If you find such a query,
try first upgrading to the newest @strong{MySQL} version.  If this doesn't
help and you can't find anything in the @code{mysql} mail archive, you should
report the bug to @email{mysql@@lists.mysql.com}.  Links to mail archives are
available at the online @uref{http://www.mysql.com/doc.html, @strong{MySQL}
documentation page}.

If you get corrupted tables or if @code{mysqld} always fails after some
update commands, you can test if this bug is reproducible by doing the
following:

@itemize @bullet
@item
Stop the mysqld daemon (with @code{mysqladmin shutdown})
@item
Check all tables with @code{isamchk -s database/*.ISM}.  Repair any
wrong tables with @code{isamchk -r database/table.ISM}.
@item
Start @code{mysqld} with @code{--log-update}
@item
When you have got a crashed table, stop the @code{mysqld server}.
@item
Restore the backup.
@item
Restart the @code{mysqld} server @strong{without} @code{--log-update}
@item
Re-execute the commands with @code{mysql < update-log}.  The update log
is saved in the @strong{MySQL} database directory with the name
@code{your-hostname.#}.
@item
If the tables are now again corrupted, you have found reproducible bug
in the @code{ISAM} code!  ftp the tables + the update log to
@uref{ftp://www.mysql.com/pub/mysql/secret} and we will fix this as soon as
possible!
@end itemize

The command @code{mysqladmin debug} will dump some information about
locks in use, used memory and query usage to the mysql log file. This
may help solve some problems.  This command also provides some useful
information even if you haven't compiled @strong{MySQL} for debugging!

If the problem is that some tables are getting slower and slower you
should try to repair the tables with @code{isamchk} to optimize the
table layout.  You should also check the slow queries with @code{EXPLAIN}.
@xref{Maintenance}.

You should also read the OS-specific section in this manual for
problems that may be unique to your environment. @xref{Source install system issues}

@findex DBI->trace
@findex trace DBI method
@tindex DBI_TRACE environment variable
@tindex Environment variable, DBI_TRACE
If you are using the Perl @code{DBI} interface, you can turn on
debugging information by using the @code{trace} method or by
setting the @code{DBI_TRACE} environment variable.
@xref{Perl DBI Class, , Perl @code{DBI} Class}.

@node Debugging client, RTS-threads, Debugging server, Porting
@appendixsec Debugging a @strong{MySQL} client

To be able to debug a @strong{MySQL} client with the integrated debug package,
you should configure @strong{MySQL} with @code{--with-debug}.
@xref{configure options}

@tindex MYSQL_DEBUG environment variable
@tindex Environment variable, MYSQL_DEBUG
Before running a client, you should set the @code{MYSQL_DEBUG} environment
variable:

@example
shell> MYSQL_DEBUG=d:t:O,/tmp/client.trace
shell> export MYSQL_DEBUG
@end example

This causes clients to generate a trace file in @file{/tmp/client.trace}.

If you have problems with your own client code, you should attempt to
connect to the server and run your query using a client that is known to
work.  Do this by running @code{mysql} in debugging mode (assuming you
have compiled @strong{MySQL} with debugging on):

@example
shell> mysql --debug=d:t:O,/tmp/client.trace
@end example

This will provide useful information in case you mail a bug report.
@xref{Bug reports}.

If your client crashes at some 'legal' looking code, you should check
that your @file{mysql.h} include file matches your mysql library file.
A very common mistake is to use an old @file{mysql.h} file from an old
@strong{MySQL} installation with new @strong{MySQL} library.

@node RTS-threads, Thread packages, Debugging client, Porting
@appendixsec Comments about RTS threads

I have tried to use the RTS thread packages with @strong{MySQL} but
stumbled on the following problems:

They use old version of a lot of POSIX calls and it is very tedious to
make wrappers for all functions. I am inclined to think that it would
be easier to change the thread libraries to the newest POSIX
specification.

Some wrappers are already written. See @file{mysys/my_pthread.c} for more info.

At least the following should be changed:

@code{pthread_get_specific} should use one argument.
@code{sigwait} should take two arguments.
A lot of functions (at least @code{pthread_cond_wait},
@code{pthread_cond_timedwait})
should return the error code on error. Now they return -1 and set @code{errno}.

Another problem is that user-level threads use the @code{ALRM} signal and this
aborts a lot of functions (@code{read}, @code{write}, @code{open}...).
@strong{MySQL} should do a retry on interrupt on all of these but it is
not that easy to verify it.

The biggest unsolved problem is the following:

To get thread-level alarms I changed @file{mysys/thr_alarm.c} to wait between
alarms with @code{pthread_cond_timedwait()}, but this aborts with error
@code{EINTR}.  I tried to debug the thread library as to why this happens,
but couldn't find any easy solution.

If someone wants to try @strong{MySQL} with RTS threads I suggest the
following:

@itemize @bullet
@item
Change functions @strong{MySQL} uses from the thread library to POSIX.
This shouldn't take that long.
@item
Compile all libraries with the @code{-DHAVE_rts_threads}.
@item
Compile @code{thr_alarm}.
@item
If there are some small differences in the implementation, they may be fixed
by changing @file{my_pthread.h} and @file{my_pthread.c}.
@item
Run @code{thr_alarm}. If it runs without any ``warning'', ``error'' or aborted
messages, you are on the right track. Here follows a successful run on
Solaris:
@example
Main thread: 1
Tread 0 (5) started
Thread: 5  Waiting
process_alarm
Tread 1 (6) started
Thread: 6  Waiting
process_alarm
process_alarm
thread_alarm
Thread: 6  Slept for 1 (1) sec
Thread: 6  Waiting
process_alarm
process_alarm
thread_alarm
Thread: 6  Slept for 2 (2) sec
Thread: 6  Simulation of no alarm needed
Thread: 6  Slept for 0 (3) sec
Thread: 6  Waiting
process_alarm
process_alarm
thread_alarm
Thread: 6  Slept for 4 (4) sec
Thread: 6  Waiting
process_alarm
thread_alarm
Thread: 5  Slept for 10 (10) sec
Thread: 5  Waiting
process_alarm
process_alarm
thread_alarm
Thread: 6  Slept for 5 (5) sec
Thread: 6  Waiting
process_alarm
process_alarm

...
thread_alarm
Thread: 5  Slept for 0 (1) sec
end
@end example
@end itemize

@node Thread packages,  , RTS-threads, Porting
@appendixsec Differences between different thread packages

@strong{MySQL} is very dependent on the thread package used. So when
choosing a good platform for @strong{MySQL}, the thread package is very
important.

There are at least three types of thread packages:

@itemize @bullet
@item
User threads in a single process. Thread switching is managed with
alarms and the threads library manages all non-thread-safe functions
with locks. Read, write and select operations are usually managed with a
thread-specific select that switches to another thread if the running
threads have to wait for data.  If the user thread packages are
integrated in the standard libs (FreeBSD and BSDI threads) the thread
package requires less overhead than thread packages that have to map all
unsafe calls (MIT-pthreads, FSU Pthreads and RTS threads).  In some
environments (for example, SCO), all system calls are thread-safe so the
mapping can be done very easily (FSU Pthreads on SCO).  Downside: All
mapped calls take a little time and it's quite tricky to be able to
handle all situations. There are usually also some system calls that are
not handled by the thread package (like MIT-pthreads and sockets). Thread
scheduling isn't always optimal.
@item
User threads in separate processes. Thread switching is done by the
kernel and all data are shared between threads.  The thread package
manages the standard thread calls to allow sharing data between threads.
LinuxThreads is using this method.  Downside: Lots of processes. Thread
creating is slow. If one thread dies the rest are usually left hanging
and you must kill them all before restarting. Thread switching is
somewhat expensive.
@item
Kernel threads. Thread switching is handled by the thread library or the
kernel and is very fast. Everything is done in one process, but on some
systems, @code{ps} may show the different threads. If one thread aborts the
whole process aborts. Most system calls are thread-safe and should
require very little overhead.  Solaris, HP-UX, AIX and OSF1 have kernel
threads.
@end itemize

In some systems kernel threads are managed by integrating user
level threads in the system libraries. In such cases, the thread
switching can only be done by the thread library and the kernel isn't
really ``thread aware''.

@node Regexp, Unireg, Porting, Top
@appendix Description of @strong{MySQL} regular expression syntax

A regular expression (regex) is a powerful way of specifying a complex search.

@strong{MySQL} uses regular Henry Spencer's inplementation of regular
expressions. And that is aimed to conform to POSIX
1003.2. @strong{MySQL} uses the extended version.

This is a simplistic reference that skips the details. To get more exact
information, see Henry Spencer's @code{regex(7)} manual page that is
included in the source distribution. @xref{Credits}.

A regular expression describes a set of strings. The simplest regexp is
one that has no special characters in it. For example, the regexp
@code{hello} matches @code{hello} and nothing else.

Nontrivial regular expressions use certain special constructs so that
they can match more than one string. For example, the regexp
@code{hello|word} matches either the string @code{hello} or the string
@code{word}.

As a more complex example, the regexp @code{B[an]*s} matches any of the
strings @code{Bananas}, @code{Baaaaas}, @code{Bs} and any other string
starting with a @code{B}, ending with an @code{s}, and containing any
number of @code{a} or @code{n} characters in between.

A regular expression may use any of the following special
characters/constructs:
@table @code
@item ^
Match the beginning of a string.
@example
mysql> select "fo\nfo" REGEXP "^fo$";           -> 0
mysql> select "fofo" REGEXP "^fo";              -> 1
@end example
@item $
Match the end of a string.
@example
mysql> select "fo\no" REGEXP "^fo\no$";         -> 1
mysql> select "fo\no" REGEXP "^fo$";            -> 0
@end example
@item .
Match any character (including newline).
@example
mysql> select "fofo" REGEXP "^f.*";             -> 1
mysql> select "fo\nfo" REGEXP "^f.*";           -> 1
@end example
@item a*
Match any sequence of zero or more @code{a} characters.
@example
mysql> select "Ban" REGEXP "^Ba*n";             -> 1
mysql> select "Baaan" REGEXP "^Ba*n";           -> 1
mysql> select "Bn" REGEXP "^Ba*n";              -> 1
@end example
@item a+
Match any sequence of one or more @code{a} characters.
@example
mysql> select "Ban" REGEXP "^Ba+n";             -> 1
mysql> select "Bn" REGEXP "^Ba+n";              -> 0
@end example
@item a?
Match either zero or one @code{a} character.
@example
mysql> select "Bn" REGEXP "^Ba?n";              -> 1
mysql> select "Ban" REGEXP "^Ba?n";             -> 1
mysql> select "Baan" REGEXP "^Ba?n";            -> 0
@end example
@item de|abc
Match either of the sequences @code{de} or @code{abc}.
@example
mysql> select "pi" REGEXP "pi|apa";             -> 1
mysql> select "axe" REGEXP "pi|apa";            -> 0
mysql> select "apa" REGEXP "pi|apa";            -> 1
mysql> select "apa" REGEXP "^(pi|apa)$";        -> 1
mysql> select "pi" REGEXP "^(pi|apa)$";         -> 1
mysql> select "pix" REGEXP "^(pi|apa)$";        -> 0
@end example
@item (abc)*
Match zero or more instances of the sequence @code{abc}.
@example
mysql> select "pi" REGEXP "^(pi)+$";            -> 1
mysql> select "pip" REGEXP "^(pi)+$";           -> 0
mysql> select "pipi" REGEXP "^(pi)+$";          -> 1
@end example
@item @{1@}
@itemx @{2,3@}
The is a more general way of writing regexps that match many
occurrences of the previous atom.
@table @code
@item a*
Can be written as @code{a@{0,@}}.
@item a+
Can be written as @code{a@{1,@}}.
@item a?
Can be written as @code{a@{0,1@}}.
@end table
To be more precise, an atom followed by a bound containing one integer
@code{i} and no comma matches a sequence of exactly @code{i} matches of
the atom. An atom followed by a bound containing one integer @code{i}
and a comma matches a sequence of @code{i} or more matches of the atom.
An atom followed by a bound containing two integers @code{i} and
@code{j} matches a sequence of @code{i} through @code{j} (inclusive)
matches of the atom.

Both arguments must @code{0 >= value <= RE_DUP_MAX (default 255)}.
If there are two arguments, the second must be greater than or equal to the
first.
@item [a-dX]
@itemx [^a-dX]
Matches
any character which is (or is not, if ^ is used) either @code{a}, @code{b},
@code{c}, @code{d} or @code{X}. To include a literal @code{]} character,
it must immediately follow the opening bracket @code{[}.  To include a
literal @code{-} character, it must be written first or last. So
@code{[0-9]} matches any decimal digit. Any character that does not have
a defined meaning inside a @code{[]} pair has no special meaning and
matches only itself.
@example
mysql> select "aXbc" REGEXP "[a-dXYZ]";         -> 1
mysql> select "aXbc" REGEXP "^[a-dXYZ]$";       -> 0
mysql> select "aXbc" REGEXP "^[a-dXYZ]+$";      -> 1
mysql> select "aXbc" REGEXP "^[^a-dXYZ]+$";     -> 0
mysql> select "gheis" REGEXP "^[^a-dXYZ]+$";    -> 1
mysql> select "gheisa" REGEXP "^[^a-dXYZ]+$";   -> 0
@end example
@item [[.characters.]]
The sequence of characters of that collating element. The sequence is a
single element of the bracket expression's list. A bracket expression
containing a multi-character collating element can thus match more than
one character, e.g., if the collating sequence includes a @code{ch}
collating element, then the regular expression @code{[[.ch.]]*c} matches the
first five characters of @code{chchcc}.

@item [=character-class=]
An equivalence class, standing for the sequences of characters of all
collating elements equivalent to that one, including itself.

For example, if @code{o} and @code{(+)} are the members of an
equivalence class, then @code{[[=o=]]}, @code{[[=(+)=]]}, and
@code{[o(+)]} are all synonymous. An equivalence class may not be an
endpoint of a range.

@item [:character_class:]
Within a bracket expression, the name of a character class enclosed in
@code{[:} and @code{:]} stands for the list of all characters belonging
to that class. Standard character class names are:

@multitable @columnfractions .33 .33 .33
@item alnum @tab digit @tab punct
@item alpha @tab graph @tab space
@item blank @tab lower @tab upper
@item cntrl @tab print @tab xdigit
@end multitable

These stand for the character classes defined in the @code{ctype(3)} manual
page. A locale may provide others. A character class may not be used as an
endpoint of a range.
@example
mysql> select "justalnums" REGEXP "[[:alnum:]]+";       -> 1
mysql> select "!!" REGEXP "[[:alnum:]]+";               -> 0
@end example

@item [[:<:]]
@itemx [[:>:]]
These match the null string at the beginning and end of a word
respectively.  A word is defined as a sequence of word characters which
is neither preceded nor followed by word characters. A word character is
an alnum character (as defined by @code{ctype(3)}) or an underscore
(@code{_}).
@example
mysql> select "a word a" REGEXP "[[:<:]]word[[:>:]]";      -> 1
mysql> select "a xword a" REGEXP "[[:<:]]word[[:>:]]";     -> 0
@end example
@end table

@example
mysql> select "weeknights" REGEXP "^(wee|week)(knights|nights)$"; -> 1
@end example

@node Unireg, Public license, Regexp, Top
@appendix What is Unireg?

Unireg is our tty interface builder, but it uses a low level connection
to our NISAM (which is used by @strong{MySQL}) and because of this it is very
quick. It has existed since 1979 (on Unix in C since ~1986).

Unireg has the following components:

@itemize @bullet
@item
One table viewer with updates/browsing.
@item
Multi table viewer (with one scrolling region).
@item
Table creator. (With lots of column tags you can't create with @strong{MySQL})
This is WYSIWYG (for a tty). You design a screen and Unireg prompts for
the column specification.
@item
Report generator.
@item
A lot of utilities (quick export/import of tables to/from text files,
analysis of table contents...).
@item
Powerful multi-table updates (which we use a lot) with a BASIC-like
language with LOTS of functions.
@item
Dynamic languages (at present in Swedish and Finnish). If somebody wants
an English version there are a few files that would have to be translated.
@item
The ability to run updates interactively or in a batch.
@item
Emacs-like key definitions with keyboard macros.
@item
All this in a binary of 800K.
@item
The @code{convform} utility. Converts @file{.frm} and text files between
different character sets.
@item
The @code{pack_isam} utility. Packs a NISAM table (makes it 50-80%
smaller). The table can be read by @strong{MySQL} like an ordinary
table. Only one record has to be decompressed  per access. Cannot handle
@code{BLOB} or @code{TEXT} columns or updates (yet).
@end itemize

We update most of our production databases with the Unireg interface and
serve web pages through @strong{MySQL} (and in some extreme cases the Unireg
report generator).

Unireg takes about 3M of disk space and works on at least the following
platforms: SunOS 4.x, Solaris, Linux, HP-UX, ICL Unix, DNIX, SCO and
MS-DOS.

Unireg is currently only available in Swedish and Finnish.

The price tag for Unireg is 10,000 Swedish kr (about $1500 US), but this
includes support. Unireg is distributed as a binary. (But all the ISAM
sources can be found in @strong{MySQL}). Usually we compile the binary for the
customer at their site.

All new development is concentrated to @strong{MySQL}.

@page
@c This node name is special
@node Public license, Win license, Unireg, Top
@appendix The @strong{MySQL} server license for non Microsoft operating systems

@center @strong{MySQL FREE PUBLIC LICENSE}
@center (Version 4, March 5, 1995)

@center Copyright (C) 1995, 1996 TcX AB & Monty Program KB & Detron HB
@center Stockholm SWEDEN, Helsingfors FINLAND and Uppsala SWEDEN
@center All rights reserved.

NOTE: This license is not the same as any of the GNU Licenses published
by the Free Software Foundation. Its terms are substantially different
from those of the GNU Licenses. If you are familiar with the GNU
Licenses, please read this license with extra care.

This License applies to the computer program known as "MySQL".  The
"Program", below, refers to such program, and a "work based on the
Program" means either the Program or any derivative work of the Program,
as defined in the United States Copyright Act of 1976, such as a
translation or a modification. The Program is a copyrighted work whose
copyright is held by TcX Datakonsult AB and Monty Program KB and Detron
HB.

This License does not apply when running "MySQL" on any Microsoft
operating system. Microsoft operating systems include all versions of
Microsoft Windows NT and Microsoft Windows.

BY MODIFYING OR DISTRIBUTING THE PROGRAM (OR ANY WORK BASED ON THE
PROGRAM), YOU INDICATE YOUR ACCEPTANCE OF THIS LICENSE TO DO SO, AND ALL
ITS TERMS AND CONDITIONS FOR COPYING, DISTRIBUTING OR MODIFYING THE
PROGRAM OR WORKS BASED ON IT. NOTHING OTHER THAN THIS LICENSE GRANTS
YOU PERMISSION TO MODIFY OR DISTRIBUTE THE PROGRAM OR ITS DERIVATIVE
WORKS. THESE ACTIONS ARE PROHIBITED BY LAW. IF YOU DO NOT ACCEPT THESE
TERMS AND CONDITIONS, DO NOT MODIFY OR DISTRIBUTE THE PROGRAM.

@enumerate
@item
Licenses.

Licensor hereby grants you the following rights, provided that you
comply with all of the restrictions set forth in this License and
provided, further, that you distribute an unmodified copy of this
License with the Program:

@enumerate a
@item
You may copy and distribute literal (i.e., verbatim) copies of the
Program's source code as you receive it throughout the world, in any
medium.
@item
You may modify the Program, create works based on the Program and
distribute copies of such throughout the world, in any medium.
@end enumerate

@item
Restrictions.

This license is subject to the following restrictions:
@enumerate a
@item
Distribution of the Program or any work based on the Program by a
commercial organization to any third party is prohibited if any payment is
made in connection with such distribution, whether directly (as in payment
for a copy of the Program) or indirectly (as in payment for some service
related to the Program, or payment for some product or service that
includes a copy of the Program "without charge"; these are only examples,
and not an exhaustive enumeration of prohibited activities). However, the
following methods of distribution involving payment shall not in and of
themselves be a violation of this restriction:

@enumerate A
@item
Posting the Program on a public access information storage and retrieval
service for which a fee is received for retrieving information (such as
an on-line service), provided that the fee is not content-dependent
(i.e., the fee would be the same for retrieving the same volume of
information consisting of random data).
@item
Distributing the Program on a CD-ROM, provided that the files containing
the Program are reproduced entirely and verbatim on such CD-ROM, and
provided further that all information on such CD-ROM be redistributable
for non-commercial purposes without charge.
@end enumerate
@item
Activities other than copying, distribution and modification of the
Program are not subject to this License and they are outside its scope.
Functional use (running) of the Program is not restricted, and any
output produced through the use of the Program is subject to this
license only if its contents constitute a work based on the Program
(independent of having been made by running the Program).
@item
You must meet all of the following conditions with respect to the
distribution of any work based on the Program:
@enumerate A
@item
If you have modified the Program, you must cause your work to carry
prominent notices stating that you have modified the Program's files and
the date of any change;
@item
You must cause any work that you distribute or publish, that in whole or
in part contains or is derived from the Program or any part thereof, to
be licensed as a whole and at no charge to all third parties under the
terms of this License;
@item
If the modified program normally reads commands interactively when run,
you must cause it, at each time the modified program commences
operation, to print or display an announcement including an appropriate
copyright notice and a notice that there is no warranty (or else, saying
that you provide a warranty). Such notice must also state that users
may redistribute the Program only under the conditions of this License
and tell the user how to view the copy of this License included with the
Program. (Exception: if the Program itself is interactive but does not
normally print such an announcement, your work based on the Program is
not required to print an announcement.);
@item
You must accompany any such work based on the Program with the complete
corresponding machine-readable source code, delivered on a medium
customarily used for software interchange. The source code for a work
means the preferred form of the work for making modifications to it.
For an executable work, complete source code means all the source code
for all modules it contains, plus any associated interface definition
files, plus the scripts used to control compilation and installation of
the executable code. However, the source code distributed need not
include anything that is normally distributed (in either source or
binary form) with the major components (compiler, kernel, and so on) of
the operating system on which the executable runs, unless that component
itself accompanies the executable code;
@item
If you distribute any written or printed material at all with the
Program or any work based on the Program, such material must include
either a written copy of this License, or a prominent written indication
that the Program or the work based on the Program is covered by this
License and written instructions for printing and/or displaying the copy
of the License on the distribution medium;
@item
You may not impose any further restrictions on the recipient's
exercise of the rights granted herein.

If distribution of executable or object code is made by offering the
equivalent ability to copy from a designated place, then offering
equivalent ability to copy the source code from the same place counts as
distribution of the source code, even though third parties are not
compelled to copy the source code along with the object code.
@end enumerate
@end enumerate
@item
Reservation of Rights.

No rights are granted to the Program except as expressly set forth
herein. You may not copy, modify, sublicense, or distribute the Program
except as expressly provided under this License. Any attempt otherwise
to copy, modify, sublicense or distribute the Program is void, and will
automatically terminate your rights under this License. However, parties
who have received copies, or rights, from you under this License will not
have their licenses terminated so long as such parties remain in full
compliance.

@item
Other Restrictions.

If the distribution and/or use of the Program is restricted in certain
countries for any reason, Licensor may add an explicit geographical
distribution limitation excluding those countries, so that distribution
is permitted only in or among countries not thus excluded. In such case,
this License incorporates the limitation as if written in the body of
this License.

@item
Limitations.

THE PROGRAM IS PROVIDED TO YOU "AS IS," WITHOUT WARRANTY. THERE IS NO
WARRANTY FOR THE PROGRAM, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT
NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF THIRD PARTY RIGHTS. THE
ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH
YOU.  SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL
NECESSARY SERVICING, REPAIR OR CORRECTION.

IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL LICENSOR, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE
PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS
OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR
THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
POSSIBILITY OF SUCH DAMAGES.
@end enumerate

@c This node name is special
@node Win license, Function Index, Public license, Top
@appendix The @strong{MySQL} license for Microsoft operating systems

@center @strong{MySQL shareware license for Microsoft operating systems}
@center (Version 1, September 4, 1998)

@center Copyright (C) 1998 TcX AB & Monty Program KB & Detron HB
@center Stockholm SWEDEN, Helsingfors FINLAND and Uppsala SWEDEN
@center All rights reserved.

This License applies to the computer program known as "MySQL". 

This License applies when running MySQL on any Microsoft operating system. 
Microsoft operating systems include all versions of Microsoft Windows NT 
and Microsoft Windows.

YOU SHOULD CAREFULLY READ THE FOLLOWING TERMS AND CONDITIONS BEFORE
USING, COPYING OR DISTRIBUTING MySQL. BY USING, COPYING AND DISTRIBUTING
MySQL, YOU INDICATE YOUR ACCEPTANCE OF THIS LICENSE TO DO SO, AND ALL
ITS TERMS AND CONDITIONS FOR USING, COPYING AND DISTRIBUTING MySQL OR
WORKS BASED ON IT.  NOTHING OTHER THAN THIS LICENSE GRANTS YOU
PERMISSION TO USE, COPY OR DISTRIBUTE MySQL OR ITS DERIVATIVE
WORKS. THESE ACTIONS ARE PROHIBITED BY LAW. IF YOU DO NOT ACCEPT THESE
TERMS AND CONDITIONS, DO NOT USE, COPY OR DISTRIBUTE MySQL.

@enumerate
@item
Evaluation and License Registration.

This is an evaluation version of MySQL for Win32. Subject to the terms
below, you are hereby licensed to use MySQL for evaluation purposes
without charge for a period of 30 days. If you use MySQL after the 30
day evaluation period the registration and purchase of a MySQL license
is required.

The price for a MySQL license is currently 200 US dollars and email
support starts from 200 US dollars/year. Quantity discounts are
available. If you pay by credit card, the currency is EURO (The European
Unions common currency) so the prices will differ slightly.

The easiest way to register or find options about how to pay for MySQL
is to use the license form at TcX's secure server at
@uref{https://www.tcx.se/license.htmy}. This can be used also when
paying with credit card over the Internet.

Other applicable methods for paying are SWIFT payments, cheques and
credit cards.

Payment should be made to: 

@example
Postgirot Bank AB
105 06 STOCKHOLM, SWEDEN

T.C.X DataKonsult AB
BOX 6434
11382 STOCKHOLM, SWEDEN

SWIFT address: PGSI SESS
Account number: 96 77 06 - 3
@end example

Specify: license and/or support and your name and email address.

In Europe and Japan, EuroGiro (that should be cheaper) can be used to
the same account.

If you want to pay by cheque make it payable to "Monty Program KB" and
mail it to the address below.

@example
T.C.X DataKonsult AB
BOX 6434
11382 STOCKHOLM, SWEDEN
@end example
For more information about commercial licensing, please contact: 

@example
David Axmark
Kungsgatan 65 B
753 21 UPPSALA
SWEDEN
Voice Phone +46-18-10 22 80     (Swedish and English spoken)
Fax +46-8-729 69 05             (Email *much* preferred)
E-Mail: mysql-licensing@@mysql.com
@end example

For more about the license prices and commercial support, like email
support, please refer to the MySQL manual. @xref{Cost}. @xref{Support}.

The use of MySQL or any work based on MySQL after the 30-day evaluation
period is in violation of international copyright laws.

@item
Registered version of MySQL.

After you have purchased a MySQL license we will send you a receipt by
paper mail. You are allowed to use MySQL or any work based on MySQL
after the 30-days evaluation period. The use of MySQL is, however,
restricted to one physical computer, but there are no restrictions on
concurrent uses of MySQL or the number of MySQL servers run on the
computer.

We will also email you an address and password for a password-protected
WWW page that always has the newest MySQL-Win32 version. Our current
policy is that a user with the MySQL license can get free upgrades. The
best way to ensure that you get the best possible support is to purchase
commercial support!

@item
Registration for use in education and university or government-sponsored
research.

You may obtain a MySQL license for the use in education and university
or government-sponsored research for free. In that case, send a detailed
application for licensing MySQL for such use to the email address
@email{mysql-licensing@@mysql.com}.

The following information is required in the application:
@itemize @bullet
@item
the name of the school or institute.
@item
a short description of the school or institute and of the type of education, resarch
or other functions it provides.
@item
a detailed report of the use of MySQL in the institution.
@end itemize

In this case you will be provided with a license that entitles you to
use MySQL in a specified manner.

@item
Distribution.

Provided that you verify that you are distributing an evaluation or
educational/research version of MySQL you are hereby licensed to make as
many literal (i.e., verbatim) copies of the evaluation version of MySQL
and documentation as you wish.

@item
Restrictions.

The client code of MySQL is in the Public Domain or under the GPL (for
example the code for readline) license.  You are not allowed to modify,
recompile, translate or create derivative works based upon any part of
the server code of MySQL.

@item
Reservation of Rights.

No rights are granted to MySQL except as expressly set forth herein.
You may not copy or distribute MySQL except as expressly provided under
this License. Any attempt otherwise to copy or distribute MySQL is void,
and will automatically terminate your rights under this License.
However, parties who have received copies, or rights, from you under
this License will not have their licenses terminated so long as such
parties remain in full compliance.

@item
Other Restrictions.

If the distribution and/or use of MySQL is restricted in certain
countries for any reason, the Licensor may add an explicit geographical
distribution limitation excluding those countries, so that distribution
is permitted only in or among countries not thus excluded. In such case,
this License incorporates the limitation as if written in the body of
this License.

@item
Limitations.

MySQL IS PROVIDED TO YOU "AS IS," WITHOUT WARRANTY. THERE IS NO WARRANTY
FOR MySQL, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE AND NONINFRINGEMENT OF THIRD PARTY RIGHTS. THE ENTIRE RISK AS TO
THE QUALITY AND PERFORMANCE OF MySQL IS WITH YOU.  SHOULD MySQL PROVE
DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR
CORRECTION.

IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL THE LICENSOR, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE
MySQL AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE MySQL (INCLUDING BUT NOT LIMITED TO LOSS OF DATA
OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF MySQL TO OPERATE WITH ANY OTHER PROGRAMS), EVEN
IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
@end enumerate

@page
@node Function Index, Concept Index, Win license, Top
@unnumbered SQL command, type and function index

@printindex fn

@page
@node Concept Index,  , Function Index, Top
@unnumbered Concept Index

@printindex cp

@summarycontents
@contents

@bye
