Table of Contents

Advertisement

Quick Links

MySQL 5.0 Reference Manual

Advertisement

Table of Contents
loading

Summary of Contents for Oracle 5.0

  • Page 1 MySQL 5.0 Reference Manual...
  • Page 2 This manual describes features that are not included in every edition of MySQL 5.0 and such features may not be included in the edition of MySQL 5.0 licensed to you. If you have any questions about the features included in your edition of MySQL 5.0, refer to your MySQL 5.0 license agreement or contact your Oracle representative.
  • Page 3: Table Of Contents

    2.10. Installing MySQL on Microsoft Windows ..............60 2.10.1. Choosing An Installation Package ..............61 2.10.2. Installing MySQL on Microsoft Windows Using an MSI Package ......62 2.10.3. MySQL Server Instance Configuration Wizard ........... 67 2.10.4. Installing MySQL on Microsoft Windows Using a Zip Archive ...
  • Page 4 2.14. Installing MySQL on i5/OS ..................101 2.15. Installing MySQL on NetWare ................... 105 2.16. Installing MySQL from Generic Binaries on Other Unix-Like Systems ......107 2.17. Installing MySQL from Source ................... 109 2.17.1. Installing MySQL from a Standard Source Distribution ........110 2.17.2.
  • Page 5 4.6.18. — Kill Processes That Match a Pattern ........370 mysql_zap 4.7. MySQL Program Development Utilities ................ 370 4.7.1. — Convert mSQL Programs for Use with MySQL ......371 msql2mysql 4.7.2. — Display Options for Compiling Clients ........371 mysql_config 4.7.3.
  • Page 6 6.1.3. Making MySQL Secure Against Attackers ............569 6.1.4. Security-Related Options and Variables ..........570 mysqld 6.1.5. How to Run MySQL as a Normal User ............. 571 6.1.6. Security Issues with ............572 LOAD DATA LOCAL 6.1.7. Client Programming Security Guidelines ............573 6.2.
  • Page 7 8.9. Optimizing the MySQL Server ..................718 8.9.1. System Factors and Startup Parameter Tuning ..........718 8.9.2. Tuning Server Parameters ................718 8.9.3. How MySQL Uses Threads for Client Connections ..........723 8.9.4. How MySQL Uses Memory ................724 8.9.5. Disk Issues ..................... 725 8.9.6.
  • Page 8 10.1.10. Unicode Support ..................791 10.1.11. UTF-8 for Metadata ..................792 10.1.12. Column Character Set Conversion ..............793 10.1.13. Character Sets and Collations That MySQL Supports ........794 10.2. Setting the Error Message Language ................ 804 10.3. Adding a Character Set .................... 805 10.3.1.
  • Page 9 12.6.1. Arithmetic Operators ..................905 12.6.2. Mathematical Functions .................. 907 12.7. Date and Time Functions ..................915 12.8. What Calendar Is Used By MySQL? ................934 12.9. Full-Text Search Functions ..................934 12.9.1. Natural Language Full-Text Searches ............. 935 12.9.2. Boolean Full-Text Searches ................938 12.9.3.
  • Page 10 Syntax .................... 1082 SELECT 13.2.9. Subquery Syntax ..................1098 13.2.10. Syntax ..................1108 UPDATE 13.3. MySQL Transactional and Locking Statements ............1110 13.3.1. TRANSACTION, COMMIT, and Syntax ....... 1110 START ROLLBACK 13.3.2. Statements That Cannot Be Rolled Back ............1113 13.3.3.
  • Page 11 Storage Engine ................1318 BLACKHOLE 15. High Availability and Scalability ..................1321 15.1. Oracle VM Template for MySQL Enterprise Edition ........... 1324 15.2. Overview of MySQL with DRBD/Pacemaker/Corosync/Oracle Linux ......1324 15.3. Overview of MySQL with Windows Failover Clustering ..........1327 15.4.
  • Page 12 17.1. MySQL Cluster Overview ..................1514 17.1.1. MySQL Cluster Core Concepts ..............1516 17.1.2. MySQL Cluster Nodes, Node Groups, Replicas, and Partitions ....... 1518 17.1.3. MySQL Cluster Hardware, Software, and Networking Requirements ....1520 17.1.4. MySQL Cluster Development History ............1521 17.1.5.
  • Page 13 17.4.18. — NDBCLUSTER Size Requirement Estimator ..... 1647 ndb_size.pl 17.4.19. — Wait for MySQL Cluster to Reach a Given Status ....1648 ndb_waiter 17.4.20. Options Common to MySQL Cluster Programs — Options Common to MySQL Cluster Programs ....................1650 17.5. Management of MySQL Cluster ................1653 17.5.1.
  • Page 14 20.4.1. MySQL Connector/C Supported Platforms ............. 2126 20.4.2. MySQL Connector/C Distribution Contents ............ 2126 20.4.3. Obtaining MySQL Connector/C ..............2126 20.4.4. Installing MySQL Connector/C from a Binary Distribution ........ 2127 20.4.5. Installing MySQL Connector/C from Source ........... 2127 20.4.6. Testing MySQL Connector/C ................ 2129...
  • Page 15 MySQL 5.0 Reference Manual 20.4.7. Building MySQL Connector/C Applications ............ 2129 20.5. libmysqld, the Embedded MySQL Server Library ............2129 20.6. MySQL C API ......................2130 20.6.1. MySQL C API Implementations ..............2131 20.6.2. Example C API Client Programs ..............2132 20.6.3.
  • Page 16 B.9. MySQL 5.0 FAQ: Security ..................2878 B.10. MySQL 5.0 FAQ: MySQL Cluster ................2879 B.11. MySQL 5.0 FAQ: MySQL Chinese, Japanese, and Korean Character Sets ....2891 B.12. MySQL 5.0 FAQ: Connectors & APIs ..............2903 B.13. MySQL 5.0 FAQ: Replication .................. 2903 C.
  • Page 17 MySQL 5.0 Reference Manual C.5.6. Optimizer-Related Issues ................2973 C.5.7. Table Definition-Related Issues ..............2974 C.5.8. Known Issues in MySQL ................2975 D. MySQL Release Notes ......................2979 E. Restrictions and Limits ......................2981 E.1. Restrictions on Stored Programs ................2981 E.2.
  • Page 18 xviii...
  • Page 19: Preface And Legal Notices

    Appendix A, Licenses for Third-Party Components. This manual is not intended for use with older versions of the MySQL software due to the many functional and other differences between MySQL 5.0 and previous versions. If you are using an earlier release of the MySQL software, please refer to the appropriate manual.
  • Page 20 Oracle. Oracle and/ or its affiliates reserve any and all rights to this documentation not expressly granted above. For more information on the terms of this license, or for details on how the MySQL documentation is built and produced, please visit MySQL Contact &...
  • Page 21: General Information

    Customer without Oracle's express written authorization. Other names may be trademarks of their respective owners. The MySQL software is Dual Licensed. Users can choose to use the MySQL software as an Open Source product under the terms of the GNU General Public License (http://www.fsf.org/licenses/) or can purchase a standard commercial license from Oracle.
  • Page 22: About This Manual

    Appendix A, Licenses for Third-Party Components. This manual is not intended for use with older versions of the MySQL software due to the many functional and other differences between MySQL 5.0 and previous versions. If you are using an earlier release of the MySQL software, please refer to the appropriate manual.
  • Page 23: Typographical And Syntax Conventions

    This manual was originally written by David Axmark and Michael “Monty” Widenius. It is maintained by the MySQL Documentation Team, consisting of Paul DuBois, Stefan Hinz, Philip Olson, John Russell, and Jon Stephens. 1.2. Typographical and Syntax Conventions This manual uses certain typographical conventions: •...
  • Page 24: Overview Of The Mysql Database Management System

    MySQL Server. Since computers are very good at handling large amounts of data, database management systems play a central role in computing, as standalone utilities, or as parts of other applications.
  • Page 25 • The MySQL Database Server is very fast, reliable, scalable, and easy to use. If that is what you are looking for, you should give it a try. MySQL Server can run comfortably on a desktop or laptop, alongside your other applications, web servers, and so on, requiring little or no attention.
  • Page 26: The Main Features Of Mysql

    The Main Features of MySQL The official way to pronounce “MySQL” is “My Ess Que Ell” (not “my sequel”), but we do not mind if you pronounce it as “my sequel” or in some other localized way. 1.3.2. The Main Features of MySQL This section describes some of the important characteristics of the MySQL Database Software.
  • Page 27 We also know of users who use MySQL Server with 200,000 tables and about 5,000,000,000 rows. • Support for up to 64 indexes per table (32 before MySQL 4.1.2). Each index may consist of 1 to 16 columns or parts of columns. The maximum index width is 767 bytes for...
  • Page 28: History Of Mysql

    History of MySQL • MySQL client programs can be written in many languages. A client library written in C is available for clients written in C or C++, or for any language that provides C bindings. • APIs for C, C++, Eiffel, Java, Perl, PHP, Python, Ruby, and Tcl are available, enabling MySQL clients to be written in many languages.
  • Page 29: What Is New In Mysql 5.0

    What Is New in MySQL 5.0 The name of the MySQL Dolphin (our logo) is “Sakila,” which was chosen from a huge list of names suggested by users in our “Name the Dolphin” contest. The winning name was submitted by Ambrose Twebaze, an Open Source software developer from Swaziland, Africa.
  • Page 30 NOT IN NOT BETWEEN queries making use of them by mean of range analysis. The performance of MySQL with regard to these relations now matches its performance with regard to and BETWEEN. • XA Transactions.
  • Page 31: Mysql Development History

    1.6.1. MySQL Mailing Lists This section introduces the MySQL mailing lists and provides guidelines as to how the lists should be used. When you subscribe to a mailing list, you receive all postings to the list as email messages. You can also send your own questions and answers to the list.
  • Page 32 MySQL Mailing Lists Your local site may have many subscribers to a MySQL mailing list. If so, the site may have a local mailing list, so that messages sent from to your site are propagated to the local lists.mysql.com list. In such cases, please contact your system administrator to be added to or dropped from the local MySQL list.
  • Page 33 The list for all topics concerning Perl support for MySQL with DBD::mysql. If you're unable to get an answer to your questions from a MySQL mailing list or forum, one option is to purchase support from Oracle. This puts you in direct contact with MySQL developers.
  • Page 34: Mysql Community Support At The Mysql Forums

    • Monthly Rapid Updates and Quarterly Service Packs • MySQL Knowledge Base • 24x7 Technical and Consultative Support MySQL Enterprise is available in multiple tiers, giving you the flexibility to choose the level of service that best matches your needs. For more information, see MySQL Enterprise.
  • Page 35 Any bug that we are able to repeat has a high chance of being fixed in the next MySQL release. It is most helpful when a good description of the problem is included in the bug report. That is, give a good example of everything you did that led to the problem and describe, in exact detail, the problem itself.
  • Page 36 The most common errors made in bug reports are (a) not including the version number of the MySQL distribution that you use, and (b) not fully describing the platform on which the MySQL server is installed (including the platform type and version number).
  • Page 37 Files tab in the bug report for instructions on uploading the archive to the bugs database. • If you believe that the MySQL server produces a strange result from a statement, include not only the result, but also your opinion of what the result should be, and an explanation describing the basis for your opinion.
  • Page 38 • Guesses about what the bug is, why it occurs, or what it depends on are usually wrong. Even the MySQL team cannot guess such things without first using a debugger to determine the real cause of a bug.
  • Page 39: Mysql Standards Compliance

    SQL modes control aspects of server operation such as what SQL syntax MySQL should support and what kind of data validation checks it should perform. This makes it easier to use MySQL in different environments and to use MySQL together with other database servers.
  • Page 40: Running Mysql In Ansi Mode

    MySQL extensions, but is still portable, by using comments of the following form: MySQL-specific code In this case, MySQL Server parses and executes the code within the comment as it would any other SQL statement, but other SQL servers will ignore the extensions. For example, MySQL Server recognizes the...
  • Page 41 MySQL Extensions to Standard SQL by renaming the .MYD, .MYI, and files to which the table corresponds. (Nevertheless, it is .frm preferable to use and let the server rename the RENAME TABLE ALTER TABLE ... RENAME files.) Database and table names cannot contain path name separator characters (“/”, “\”).
  • Page 42 ZEROFILL • Functions and operators • To make it easier for users who migrate from other SQL environments, MySQL Server supports aliases for many functions. For example, all string functions support both standard SQL syntax and ODBC syntax.
  • Page 43: Mysql Differences From Standard Sql

    Clauses”. GROUP BY 1.8.5. MySQL Differences from Standard SQL We try to make MySQL Server follow the ANSI SQL standard and the ODBC SQL standard, but MySQL Server performs operations differently in some cases: • For columns, trailing spaces are removed when the value is stored. (This is fixed in MySQL VARCHAR 5.0.3).
  • Page 44 You can normally fix tables perfectly with no data integrity loss just by using the MySQL log or even adding one extra log.
  • Page 45 (which can happen with transactional tables if you are not very careful). MySQL Server also guarantees that there are no dirty reads.
  • Page 46 You can think of this as though MySQL Server changed the preceding statement to: UPDATE tbl_name SET row_flag=1 WHERE id=ID AND row_flag <> 1;...
  • Page 47 Standard SQL uses “--” as a start-comment sequence. MySQL Server uses “#” as the start comment character. MySQL Server 3.23.3 and up also supports a variant of the “--” comment style. That is, the “--” start-comment sequence must be followed by a space (or by a control character such as a newline).
  • Page 48: How Mysql Deals With Constraints

    We do this in most cases, but not yet for all. The options MySQL has when an error occurs are to stop the statement in the middle or to recover as well as possible from the problem and continue. By default, the server follows the latter course. This means, for example, that the server may coerce illegal values to the closest legal values.
  • Page 49 SIMPLE MySQL requires that foreign key columns be indexed; if you create a table with a foreign key constraint but no index on a given column, an index is created. You can obtain information about foreign keys from the INFORMATION_SCHEMA.KEY_COLUMN_USAGE...
  • Page 50 • If you try to store an out of range value into a numeric column, MySQL Server instead stores zero, the smallest possible value, or the largest possible value, whichever is closest to the invalid value. • For strings, MySQL stores either the empty string or as much of the string as can be stored in the column.
  • Page 51 To avoid problems in the first place, do not use MySQL to check column content. It is safest (and often faster) to let the application ensure that it passes only legal values to the database.
  • Page 52: Credits

    David J. Hughes.) • Patrick Lynch For helping us acquire http://www.mysql.com/. • Fred Lindberg For setting up qmail to handle the MySQL mailing list and for the incredible help we got in managing the MySQL mailing lists. • Igor Romanenko <igor@frog.kiev.ua>...
  • Page 53 <tommy@valley.ne.jp> character set macros and the ujis and sjis character sets. • Joshua Chamas <joshua@chamas.com> Base for concurrent insert, extended date syntax, debugging on NT, and answering on the MySQL mailing list. • Yves Carlier <Yves.Carlier@rug.ac.be> mysqlaccess, a program to show the access rights for a user.
  • Page 54 • John Birrell Emulation of for OS/2. pthread_mutex() • Benjamin Pflugmann Extended tables to handle INSERTS. Active member on the MySQL mailing lists. MERGE • Jocelyn Fournier Excellent spotting and reporting innumerable bugs (especially in the MySQL 4.1 subquery code).
  • Page 55 <psmith@BayNetworks.com>, <duane@connect.com.au>, Ted Deppner <ted@psyber.com>, Mike Simons, Jaakko Hyvatti. And lots of bug report/patches from the folks on the mailing list. A big tribute goes to those that help us answer questions on the MySQL mailing lists: • Daniel Koch <dkoch@amcity.com>...
  • Page 56: Documenters And Translators

    Helped to rewrite Monty's and David's early attempts at English into English. • Michael J. Miller Jr. <mke@terrapin.turbolift.com> For the first MySQL manual. And a lot of spelling/language fixes for the FAQ (that turned into the MySQL manual a long time ago). • Yan Cailin First translator of the MySQL Reference Manual into simplified Chinese in early 2000 on which the Big5 and HK coded (http://mysql.hitstar.com/) versions were based.
  • Page 57: Packages That Support Mysql

    MySQL. We cannot list every possible package here because the list would then be way to hard to maintain. For other packages, please refer to the software portal at http://solutions.mysql.com/software/. • Tim Bunce, Alligator Descartes...
  • Page 58: Tools That Were Used To Create Mysql

    1.9.4. Tools that were used to create MySQL The following is a list of some of the tools we have used to create MySQL. We use this to express our thanks to those that has created them as without these we could not have made MySQL what it is today.
  • Page 59 Supporters of MySQL • NuSphere Editing of the MySQL manual. • Stork Design studio The MySQL Web site in use between 1998-2000. • Intel Contributed to development on Windows and Linux platforms. • Compaq Contributed to Development on Linux/Alpha. • SWSoft Development on the embedded version.
  • Page 61: Installing And Upgrading Mysql

    2.10. Installing MySQL on Microsoft Windows ................60 2.10.1. Choosing An Installation Package ................61 2.10.2. Installing MySQL on Microsoft Windows Using an MSI Package ......... 62 2.10.3. MySQL Server Instance Configuration Wizard ............67 2.10.4. Installing MySQL on Microsoft Windows Using a Zip Archive ....
  • Page 62: Mysql Installation Overview

    To install MySQL Community Server, see Section 2.4, “Notes for MySQL Community Server”. If you plan to upgrade an existing version of MySQL to a newer version rather than install MySQL for the first time, see Section 2.19.1, “Upgrading MySQL”, for information about upgrade procedures and...
  • Page 63: Notes For Mysql Enterprise Server

    The platforms that are officially supported for MySQL Enterprise are listed at http://www.mysql.com/support/supportedplatforms.html. MySQL Enterprise Server is available for download in the form of Quarterly Service Pack (QSP) or Monthly Rapid Update (MRU) binary releases. To install MySQL Enterprise Server, you should use the latest available Quarterly Service Pack (QSP).
  • Page 64: Enterprise Server Distribution Types

    1. Determine whether MySQL runs and is supported on your platform. Not all platforms are equally suitable for running MySQL, and not all platforms on which MySQL is known to run are officially supported by Oracle Corporation. For a list of platforms on which MySQL Community Server runs, see Section 2.4.2, “Operating Systems Supported by MySQL Community...
  • Page 65: Operating Systems Supported By Mysql Community Server

    MySQL Web site. We use GNU Autoconf, so it is possible to port MySQL to all modern systems that have a C++ compiler and a working implementation of POSIX threads. (Thread support is needed for the server. To compile only the client code, the only requirement is a C++ compiler.)
  • Page 66: Choosing Which Mysql Distribution To Install

    Notes”. Some porting effort might be required for current versions of MySQL on these systems. Not all platforms are equally well suited for running MySQL. How well a certain platform is suited for a high-load mission-critical MySQL server is determined by the following factors: •...
  • Page 67 See http://www.mysql.com/about/legal/lifecycle/ for information about support policies and schedules. Normally, if you are beginning to use MySQL for the first time or trying to port it to some system for which there is no binary distribution, use the most recent General Availability series listed in the preceding descriptions.
  • Page 68 All releases of MySQL are run through our standard tests and benchmarks to ensure that they are relatively safe to use. Because the standard tests are extended over time to check for all previously found bugs, the test suite keeps getting better.
  • Page 69 • You want to read (or modify) the C and C++ code that makes up MySQL. For this purpose, you should get a source distribution, because the source code is always the ultimate manual.
  • Page 70: How To Get Mysql

    2.6. Verifying Package Integrity Using MD5 Checksums or GnuPG After you have downloaded the MySQL package that suits your needs and before you attempt to install it, you should make sure that it is intact and has not been tampered with. There are three means of integrity checking: •...
  • Page 71: Signature Checking Using Gnupg

    To verify the signature for a specific package, you first need to obtain a copy of our public GPG build key, which you can download from http://pgp.mit.edu/. The key that you want to obtain is named mysql-build@oss.oracle.com. Alternatively, you can cut and paste the key directly from the following text: -----BEGIN PGP PUBLIC KEY BLOCK----- Version: PGP Universal 2.9.1 (Build 347)
  • Page 72 This refers to your level of trust in your belief that you possess our real public key. This is a personal decision. Ideally, a MySQL developer would hand you the key in person, but more commonly, you downloaded it. Was the download tampered with? Probably not, but this decision is up to you.
  • Page 73: Signature Checking Using Gpg4Win For Windows

    Download and install Gpg4win, and then load Kleopatra. The dialog should look similar to: Figure 2.1. Initial screen after loading Kleopatra Next, add the MySQL Release Engineering certificate. Do this by clicking File, Lookup Certificates on Server. Type "Mysql Release Engineering" into the search box and press Search.
  • Page 74 Figure 2.3. Changing the Trust level Next, verify the downloaded MySQL package file. This requires files for both the packaged file, and the signature. The signature file must have the same name as the packaged file but with an appended extension, as shown by the example in the following table.
  • Page 75 Signature Checking Using for Windows Gpg4win Figure 2.4. The Decrypt/Verify Files dialog Click Decrypt/Verify to check the file. The two most common results will look like the following, and although the yellow warning looks problematic, the following means that the file check passed with success.
  • Page 76 Signature Checking Using for Windows Gpg4win Figure 2.5. The Decrypt/Verify Results: Good Seeing a red "The signature is bad" error means the file is invalid. Do not execute the MSI file if you see this error.
  • Page 77: Signature Checking Using Rpm

    Rather, RPM maintains a separate keyring because it is a system-wide application and a user's GPG public keyring is a user-specific file. To import the MySQL public key into the RPM keyring, first obtain the key, then use rpm -- to import the key.
  • Page 78: Installation Layouts

    For MySQL 5.0 on Windows, the default installation directory is C:\Program Files\MySQL\MySQL 5.0. (Some Windows users prefer to install in C:\mysql, the directory that formerly was Server used as the default. However, the layout of the subdirectories remains the same.) The installation directory has the following subdirectories: Table 2.3.
  • Page 79: Compiler-Specific Build Characteristics

    Benchmarks sql-bench By default, when you install MySQL after compiling it from a source distribution, the installation step installs files under /usr/local. Components are installed in the directories shown in the following table. To configure particular installation locations, use the options described at Section 2.17.3,...
  • Page 80: Standard Mysql Installation From A Binary Distribution

    Standard MySQL Installation from a Binary Distribution In some cases, the compiler used to build MySQL affects the features available for use. The notes in this section apply for binary distributions provided by Oracle Corporation or that you compile yourself from source.
  • Page 81: Choosing An Installation Package

    Choosing An Installation Package • If you need tables with a size larger than 4GB, install MySQL on an NTFS or newer file system. Do not forget to use when you create tables. See Section 13.1.10, MAX_ROWS AVG_ROW_LENGTH “CREATE TABLE Syntax”.
  • Page 82: Installing Mysql On Microsoft Windows Using An Msi Package

    2.10.2. Installing MySQL on Microsoft Windows Using an MSI Package New MySQL users can use the MySQL Installation Wizard and MySQL Configuration Wizard to install MySQL on Windows. These are designed to install and configure MySQL in such a way that new users can immediately get started using MySQL.
  • Page 83 Port number text box. Also ensure that the TCP protocol radio button is selected. If you wish, you can also limit access to the MySQL server by choosing the Change scope button. Confirm your choices by clicking the OK button.
  • Page 84 Next button, you advance to the custom installation dialog, described in Section 2.10.2.1.3, “The Custom Installation Dialog”. 2.10.2.1.3. The Custom Installation Dialog If you wish to change the installation path or the specific components that are installed by the MySQL Installation Wizard, choose the Custom installation type.
  • Page 85 Installing MySQL on Microsoft Windows Using an MSI Package A tree view on the left side of the custom install dialog lists all available components. Components that are not installed have a red X icon; components that are installed have a gray icon. To change whether a component is installed, click that component's icon and choose a new option from the drop-down list that appears.
  • Page 86 Installing MySQL on Microsoft Windows Using an MSI Package To install MySQL if you are satisfied with your settings, click the Install button. To change your settings, click the Back button. To exit the MySQL Installation Wizard without installing MySQL, click the Cancel button.
  • Page 87: Mysql Server Instance Configuration Wizard

    • MySQL Documentation: This is a link to the MySQL server documentation that is stored locally in the MySQL server installation directory. This option is not available when the MySQL server is installed using the Essentials installation package.
  • Page 88 If you chose not to open a port prior to installing MySQL on Windows Vista or newer, you can choose to use the MySQL Server Configuration Wizard after installation. However, you must open a port in the Windows Firewall.
  • Page 89 \WINDOWS). Under Windows Server 2003, Windows Server 2000 and Windows XP, MySQL Server Instance Configuration Wizard will configure MySQL to work as a Windows service. To start and stop MySQL you use the application that is supplied as part of the Windows Administrator Tools.
  • Page 90 If you are new to MySQL and need a server configured as a single-user developer machine, the Standard Configuration should suit your needs. Choosing the Standard Configuration option causes the MySQL Configuration Wizard to set all configuration options automatically with the exception of Service Options and Security Options.
  • Page 91 • Dedicated MySQL Server Machine: Choose this option for a server machine that is intended to run only the MySQL server. It is assumed that no other applications are running. The MySQL server is configured to use all available system resources.
  • Page 92 MySQL Server Instance Configuration Wizard • Multifunctional Database: This option enables both the storage engines and InnoDB MyISAM divides resources evenly between the two. This option is recommended for users who use both storage engines on a regular basis. • Transactional Database Only: This option enables both the...
  • Page 93 To prevent the server from running out of resources, it is important to limit the number of concurrent connections to the MySQL server that can be established. The Concurrent Connections dialog enables you to choose the expected usage of your server, and sets the limit for concurrent connections...
  • Page 94 2.10.3.8. The Networking and Strict Mode Options Dialog Use the Networking Options dialog to enable or disable TCP/IP networking and to configure the port number that is used to connect to the MySQL server.
  • Page 95 Enable TCP/IP Networking option. Port 3306 is used by default. To change the port used to access MySQL, choose a new port number from the drop-down box or type a new port number directly into the drop-down box. If the port number you choose is in use, you are prompted to confirm your choice of port number.
  • Page 96 The MySQL Server Instance Configuration Wizard installs the MySQL server as a service by default, using the service name MySQL. If you do not wish to install the service, uncheck the box next to the Install As Windows Service option. You can change the service name by picking a new service name from the drop-down box provided or by entering a new service name into the drop-down box.
  • Page 97 For example, you might install MySQL 5.x as mysql5, or specific versions such as MySQL 5.0.56 as mysql50056. To install the MySQL server as a service but not have it started automatically at startup, uncheck the box next to the Launch the MySQL Server Automatically option.
  • Page 98 The MySQL Configuration Wizard then writes these options to the corresponding configuration file. If you chose to create a service for the MySQL server, the MySQL Server Instance Configuration Wizard creates and starts the service. If you are reconfiguring an existing service, the MySQL Server Instance Configuration Wizard restarts the service to apply your configuration changes.
  • Page 99: Installing Mysql On Microsoft Windows Using A Noinstall Zip Archive

    3. Choose an installation location. Traditionally, the MySQL server is installed in C:\mysql. The MySQL Installation Wizard installs MySQL under Files\MySQL. If you do not install C:\Program MySQL at C:\mysql, you must specify the path to the install directory during startup or in an option file. See Section 2.10.4.2, “Creating an Option File”.
  • Page 100 Files”. On Windows, the MySQL installer places the data directory directly under the directory where you install MySQL. If you would like to use a data directory in a different location, you should copy the entire contents of the directory to the new location. For example, if MySQL is installed in data 5.0, the data directory is by default in...
  • Page 101 2.10.4.4. Starting the Server for the First Time This section gives a general overview of starting the MySQL server. The following sections provide more specific information for starting the MySQL server from the command line or as a Windows service.
  • Page 102 Section 2.18, “Postinstallation Setup and Testing”. 2.10.4.5. Starting MySQL from the Windows Command Line The MySQL server can be started manually from the command line. This can be done on any version of Windows. To start the server from the command line, you should start a console window (or “DOS mysqld window”) and enter this command:...
  • Page 103 Services operations from the command line. Before installing MySQL as a Windows service, you should first stop the current server if it is running by using the following command: shell> "C:\Program Files\MySQL\MySQL Server 5.0\bin\mysqladmin"...
  • Page 104 [240] is more flexible because it enables you to specify multiple startup options defaults-file for the server by placing them in the named option file. Also, in MySQL 5.0, use of an option different from [240] is not supported until 5.0.3.
  • Page 105 The error log is located in the MySQL data directory (for example, 5.0\data). It is the file with a suffix of C:\Program Files\MySQL\MySQL Server .err.
  • Page 106: Troubleshooting A Mysql Installation Under Windows

    2.10.5. Troubleshooting a MySQL Installation Under Windows When installing and running MySQL for the first time, you may encounter certain errors that prevent the MySQL server from starting. The purpose of this section is to help you diagnose and correct some of these errors.
  • Page 107: Upgrading Mysql On Windows

    Methods”. 3. Download the latest Windows distribution of MySQL from http://dev.mysql.com/downloads/. 4. Before upgrading MySQL, you must stop the server. If the server is installed as a service, stop the service with the following command from the command prompt: shell>...
  • Page 108: Windows Postinstallation Procedures

    MySQL installation (usually located at C:\mysql), or install it into a different directory, such as C:\mysql5. Overwriting the existing installation is recommended. 8. If you were running MySQL as a Windows service and you had to remove the service earlier in this procedure, reinstall the service. (See Section 2.10.4.7, “Starting MySQL as a Windows...
  • Page 109 The preceding command (and commands for other MySQL programs such as mysql) may not work if the correct MySQL account does not exist. For example, the program may fail with an error, or you may not be able to view all databases. If you installed using the MSI packages and used the MySQL Server...
  • Page 110: Installing Mysql From Source On Windows

    Installing MySQL from Source on Windows If you are running a version of Windows that supports services, you can set up the MySQL server to run automatically when Windows starts. See Section 2.10.4.7, “Starting MySQL as a Windows Service”. 2.10.8. Installing MySQL from Source on Windows These instructions describe how to build binaries from source for MySQL 5.0 on Windows.
  • Page 111 Installing MySQL from Source on Windows • Build from the MySQL Windows source distribution. The Windows source distribution includes ready- made Visual Studio solution files that enable support for all storage engines (except NDB). To build using using method you only need Visual C++ Express Edition or Visual Studio. To use this method, Section 2.10.8.2, “Building MySQL from a Windows Source...
  • Page 112 Using this method you are not able to select the storage engines that are included in your build. Note VC++ workspace files for MySQL 4.1 and above are compatible with Microsoft Visual Studio 7.1 and tested by us before each release. Follow this procedure to build MySQL: 1.
  • Page 113 C:\mysql\bin\mysqld-debug.exe C:\workdir> xcopy scripts\*.* C:\mysql\scripts /E C:\workdir> xcopy share\*.* C:\mysql\share /E If you want to compile other clients and link them to MySQL, you should also copy several libraries and header files: C:\workdir> copy lib_debug\mysqlclient.lib C:\mysql\lib\debug C:\workdir> copy lib_debug\libmysql.* C:\mysql\lib\debug C:\workdir>...
  • Page 114 You can also run the standard test script, mysql-test-run.pl. This script is written in Perl, so you'll need either Cygwin or ActiveState Perl to run it. You may also need to install the modules required by the script. To run the test script, change location into the...
  • Page 115: Installing Mysql On Mac Os X

    2.11. Installing MySQL on Mac OS X You can install MySQL on Mac OS X 10.3.x (“Panther”) or newer using a Mac OS X binary package in PKG format instead of the binary tarball distribution. Please note that older versions of Mac OS X (for example, 10.1.x or 10.2.x) are not supported by this package.
  • Page 116 If you are upgrading from Marc's 3.23.x versions or from the Mac OS X Server version of MySQL to the official MySQL PKG, you also need to convert the existing MySQL privilege tables to the current format, because some new security privileges have been added.
  • Page 117: Installing Mysql From Rpm Packages On Linux

    MySQL Programs”. If you are upgrading an existing installation, note that installing a new MySQL PKG does not remove the directory of an older installation. Unfortunately, the Mac OS X Installer does not yet offer the functionality required to properly upgrade previously installed packages.
  • Page 118 5.0.27 on. • MySQL-server-VERSION.glibc23.i386.rpm, MySQL-server- community-VERSION.glibc23.i386.rpm The MySQL server. You need this unless you only want to connect to a MySQL server running on another machine. • MySQL-client-VERSION.glibc23.i386.rpm, MySQL-client- community-VERSION.glibc23.i386.rpm The standard MySQL client programs. You probably always want to install this package.
  • Page 119 Installing MySQL from RPM Packages on Linux applications installed that are dynamically linked against older versions of MySQL but you want to upgrade to the current version without breaking the library dependencies. • MySQL-clustermanagement-communityVERSION.glibc23.i386.rpm, MySQL-clusterstorage-communityVERSION.glibc23.i386.rpm, MySQL- clustertools-communityVERSION.glibc23.i386.rpm, MySQL-clusterextra- communityVERSION.glibc23.i386.rpm Packages that contain additional files for MySQL Cluster installations. These are platform-specific RPMs, in contrast to the platform-independent RPMs.
  • Page 120: Installing Mysql On Solaris

    .mysqlgui, lost+found, .mysqlgui, .bash_history, .fonts.cache-1, .lesshst, .mysql_history, .profile, .viminfo, and similar files created by MySQL or operating system utilities. You can safely ignore these error messages or remove the files or directories that cause them if you do not need them.
  • Page 121: Installing Mysql On I5/Os

    Installing MySQL on i5/OS If you install MySQL using a binary tarball distribution on Solaris, you may run into trouble even before you get the MySQL distribution unpacked, as the Solaris cannot handle long file names. This means that you may see errors when you try to unpack MySQL.
  • Page 122 QSECOFR WRKUSRPRF your user profile. • For network connections to MySQL, you must have TCP/IP enabled. You should also check the following: • Ensure that a name has defined for the system. Run the Configure TCP/IP (CFGTCP) command and select option 12 (Change TCP/IP domain information) to display this setting. Make sure that a value is listed in the Host name field.
  • Page 123 • DIR('/QOpenSys/usr/local/'): Sets the installation location for the MySQL files. The directory will be created if it does not already exist. This is the directory that the MySQL server will be installed into, inside a directory with a name matching the version and release. For example, if installing MySQL 5.0.82 with the...
  • Page 124 > cd /opt/mysql/mysql > bin/mysqladmin -u root shutdown If the session that you started and stopped MySQL are the same, you may get the log output from mysqld: STOPPING server from pid file »...
  • Page 125: Installing Mysql On Netware

    INSMYSQL CHGJOB CSSID. • If you want to use the Perl scripts that are included with MySQL, you need to download the iSeries Tools for Developers (5799-PTL). See http://www-03.ibm.com/servers/enable/site/porting/tools/. 2.15. Installing MySQL on NetWare Porting MySQL to NetWare was an effort spearheaded by Novell. Novell customers should be pleased to note that NetWare 6.5 ships with bundled MySQL binaries, complete with an automatic commercial...
  • Page 126 • PHP: http://forge.novell.com/modules/xfcontent/downloads.php/php/Modules/ If there was an existing installation of MySQL on the NetWare server, be sure to check for existing MySQL startup commands in autoexec.ncf, and edit or delete them as necessary. Note The accounts that are listed in the MySQL grant tables initially have no passwords.
  • Page 127: Installing Mysql From Generic Binaries On Other Unix-Like Systems

    MySQL distribution. You should download and install GNU tar, or if available, use a preinstalled version of GNU tar. Usually this is available as gnutar, gtar, or as within a GNU or Free Software directory, such as or /usr/local/bin.
  • Page 128 You might want to call the user and group something else instead of mysql. If so, substitute the appropriate name in the preceding commands and in the following steps. Obtain and Unpack the Distribution Pick the directory under which you want to unpack the distribution and change location into it.
  • Page 129: Installing Mysql From Source

    2.17. Installing MySQL from Source Building MySQL from the source code enables you to customize build parameters, compiler optimizations, and installation location. For a list of systems on which MySQL is known to run, see Section 2.4.2, “Operating Systems Supported by MySQL Community Server”.
  • Page 130: Installing Mysql From A Standard Source Distribution

    Problems”. 2.17.1. Installing MySQL from a Standard Source Distribution To install MySQL from source, first configure, build, and install from a source package. Then follow the same postinstallation setup sequence as for a binary installation. If you start from a source RPM, use the following command to make a binary RPM that you can install.
  • Page 131 Unix, or they may have different names such groupadd and addgroup. adduser You might want to call the user and group something else instead of mysql. If so, substitute the appropriate name in the following steps. 2. Perform the following steps as the user, except as noted.
  • Page 132 11. If you have not installed MySQL before, you must create the MySQL data directory and initialize the grant tables: shell> bin/mysql_install_db --user=mysql If you run the command as root, include the option as shown.
  • Page 133: Installing Mysql From A Development Source Tree

    Do not use a development tree for production systems. If your goal is simply to get MySQL up and running on your system, you should use a standard release distribution (either a binary or source distribution). See Section 2.5, “How to Get...
  • Page 134 Installing MySQL from a Development Source Tree 1. To obtain a copy of the MySQL source code, you must create a new Bazaar branch. If you do not already have a Bazaar repository directory set up, you must initialize a new directory: shell>...
  • Page 135: Mysql Source-Configuration Options

    PATH them. 2.17.3. MySQL Source-Configuration Options script provides a great deal of control over how you configure a MySQL source configure distribution. Typically, you do this using options on the command line. For a full list of...
  • Page 136 MySQL Source-Configuration Options Table 2.7. MySQL Source-Configuration Option Reference (configure) Formats Description Default Introduced R emoved User executables --bindir=DIR EPREFIX/bin Configure for building on --build=BUILD guessed BUILD Cache test results in FILE --cache-file=FILE disabled Alias for `--cache- file=config.cache' --config-cache Read-only architecture-...
  • Page 137 MySQL Source-Configuration Options Formats Description Default Introduced R emoved Info documentation --infodir=DIR PREFIX/info Object code libraries --libdir=DIR EPREFIX/lib Program executables --libexecdir=DIR EPREFIX/ libexec Modifiable single-machine --localstatedir=DIR PREFIX/var data man documentation --mandir=DIR PREFIX/man Do not create output files --no-create C header files for non-gcc...
  • Page 138 MySQL Source-Configuration Options Formats Description Default Introduced R emoved Support tables with more 5.0.4 --with-big- [123] than 4 G rows even on 32 bit tables platforms Enable the Blackhole Storage 5.0.4 --with-blackhole- Engine storage-engine [122] Default character set --with-charset Extra linking arguments for...
  • Page 139 Force use of pthread library --with-pthread Enable RAID Support 5.0.3 --with-raid Append value to the version --with-server-suffix string Set the system type, like 5.0.44 --with-system-type "sun-solaris10" Include additional --with-tags automatic configurations [121] Which port to use for MySQL --with-tcp-port 3306 services...
  • Page 140 [422] --basedir --port --socket options for mysqld. • To compile just the MySQL client libraries and client programs and not the server, use the [120] option: without-server shell> ./configure --without-server If you have no C++ compiler, some client programs such as...
  • Page 141 MySQL Source-Configuration Options should still try to build all clients, but you can ignore any warnings about files such as mysql.cc. (If stops, try to tell it to continue with the rest of the build even if errors occur.) make make -k •...
  • Page 142 MySQL Source-Configuration Options CFLAGS="-O3 -mpentiumpro" CXX=gcc CXXFLAGS="-O3 -mpentiumpro \ -felide-constructors -fno-exceptions -fno-rtti" In most cases, you can get a reasonably optimized MySQL binary by using the options from the preceding list and adding the following options to the line: configure...
  • Page 143: Dealing With Problems Compiling Mysql

    2.17.4. Dealing with Problems Compiling MySQL All MySQL programs compile cleanly for us with no warnings on Solaris or Linux using gcc. On other systems, warnings may occur due to differences in system include files. For other problems, check the following list.
  • Page 144 Another way to fix these problems is to install g++, libg++, and libstdc++. However, do not use with MySQL because this only increases the binary size of without libg++ libstdc++ mysqld providing any benefits.
  • Page 145 • The file is generated from sql_yacc.yy. Normally, the build process does not need sql_yacc.cc to create because MySQL comes with a pregenerated copy. However, if you do need sql_yacc.cc to re-create it, you might encounter this error: "sql_yacc.yy", line fatal: default action causes potential...
  • Page 146: Compiling And Linking An Optimized Mysqld Server

    Here is a list of some measurements that we have made: • If you link dynamically (without -static), the result is 13% slower on Linux. Note that you still can use a dynamically linked MySQL library for your client applications. It is the server that is most critical for performance.
  • Page 147: Postinstallation Setup And Testing

    2.18.1. Unix Postinstallation Procedures After installing MySQL on Unix, you must initialize the grant tables, start the server, and make sure that the server works satisfactorily. You may also wish to arrange for the server to be started and stopped automatically when your system starts and stops.
  • Page 148 2. If necessary, ensure that the distribution contents are accessible to mysql. If you unpacked the distribution as mysql, no further action is required. If you unpacked the distribution as root, its contents will be owned by root. Change its ownership to...
  • Page 149 /etc/mysql/my.cnf for the first time. If you do not copy one of the standard configuration files, the MySQL server will be started with the default settings. If you want MySQL to start automatically when you boot your machine, you can copy support- to the location where your system has its startup files.
  • Page 150 The output from varies slightly depending on your platform and version of mysqladmin version MySQL, but should be similar to that shown here: shell> bin/mysqladmin version mysqladmin Ver 14.12 Distrib 5.0.96, for pc-linux-gnu on i686 Server version 5.0.96...
  • Page 151 The expected result of the test can be found in the file. ./tests/auto_increment.res 13. At this point, you should have the server running. However, none of the initial MySQL accounts have a password, and the server permits permissive access to test databases. To tighten security, follow the instructions in Section 2.18.2, “Securing the Initial MySQL...
  • Page 152 This can happen when you have an existing MySQL installation, but want to put a new installation in a different location. For example, you might have a production installation, but you want to create a second installation for testing purposes.
  • Page 153 GRANT REVOKE If you want to install MySQL on several machines with the same privileges, you can put the statements in a file and execute the file as a script using after running GRANT REVOKE mysql mysql_install_db.
  • Page 154 MySQL in the future, so you should make a copy of your edited version that you can reinstall.) stops the server by sending a signal to it. You can also stop the server mysql.server stop...
  • Page 155 As an alternative to the preceding setup, some operating systems also use /etc/rc.local /etc/ to start additional services on startup. To start up MySQL using this method, init.d/boot.local you could append a command like the one following to the appropriate startup file: /bin/sh -c 'cd /usr/local/mysql;...
  • Page 156 [425] [400] options. --verbose --help If the default locations do not match the MySQL installation layout on your system, you can override them by specifying options to on the command line or in an option file. mysqld mysqld_safe To specify the location of the data directory explicitly, use the [404] option.
  • Page 157 -R mysql /usr/local/mysql/var If it possible that even with correct ownership, MySQL may fail to start up if there is other security software running on your system that manages application access to various parts of the file system. In...
  • Page 158: Securing The Initial Mysql Accounts

    If no other server is running, try to execute the command telnet your_host_name tcp_ip_port_number. (The default MySQL port number is 3306.) Then press Enter a couple of times. If you do not get an error message like telnet: Unable to connect to remote host: refused, some other program is using the TCP/IP port that is trying to use.
  • Page 159 The following instructions describe how to set up passwords for the initial MySQL accounts, first for accounts, then for the anonymous accounts. The instructions also cover how to remove the root anonymous accounts, should you prefer not to permit anonymous access at all, and describe how to remove permissive access to test databases.
  • Page 160: Assigning Account Passwords

    This method works on any platform: mysql.user shell> mysql -u root mysql> UPDATE mysql.user SET Password = PASSWORD('newpwd') -> WHERE User = 'root'; mysql> FLUSH PRIVILEGES; statement causes the server to reread the grant tables. Without it, the password change FLUSH remains unnoticed by the server until you restart it.
  • Page 161 If you want to remove any-user access to test databases, do so as follows: shell> mysql -u root -p Enter password: (enter root password here) mysql> DELETE FROM mysql.db WHERE Db LIKE 'test%';...
  • Page 162: Upgrading Or Downgrading Mysql

    MySQL 4.1, and then proceed with the upgrade to MySQL 5.0. For example, if you currently are running MySQL 4.0 and wish to upgrade to a newer series, upgrade to MySQL 4.1 first before upgrading to 5.0, and so forth. For information on upgrading to MySQL 4.1 or earlier releases, see the MySQL 3.23, 4.0, 4.1 Reference Manual.
  • Page 163 If you are cautious about using new versions, you can always rename your old before mysqld installing a newer one. For example, if you are using a version of MySQL 4.1 and want to upgrade to 5.0, rename your current server from to mysqld-4.1. If your new...
  • Page 164 If your MySQL installation contains a large amount of data that might take a long time to convert after an in-place upgrade, you might find it useful to create a “dummy” database instance for assessing what...
  • Page 165 DROP TRIGGER name (schema name is optional and, if omitted, the current schema will be used). When upgrading from a version of MySQL 5 older than 5.0.10 to MySQL 5.0.10 or newer, you must drop all triggers and re-create them or will not work after the upgrade.
  • Page 166 VARBINARY columns in MySQL 5.0.3 and later are 65,535 characters and 65,535 bytes, respectively. When a binary upgrade (file system-level copy of data files) to MySQL 5.0 is performed for a table with a column, the column is space-padded to the full permissible width of the column.
  • Page 167 99.9. Before MySQL 5.0.3, the server permitted larger numbers to be stored. That is, it stored a value such as 100.0 as 100.0. As of MySQL 5.0.3, the server clips 100.0 to the maximum permissible value of 99.9. If you have tables that were created before MySQL 5.0.3 and that contain floating-point data not strictly legal for the data type, you should alter the data types of those columns.
  • Page 168 ALTER TABLE TIMESTAMP(N) causes the backup to fail. This holds true regardless of the logging format used by a MySQL 5.1 or newer server. It may be possible to fix such issues using a hex editor, by replacing any width arguments used with TIMESTAMP, and the parentheses containing them, with space characters (hexadecimal 20).
  • Page 169 DAYNAME() MONTHNAME() Section 10.7, “MySQL Server Locale Support”. • In MySQL 5.0.6, binary logging of stored routines and triggers was changed. This change has implications for security, replication, and data recovery, as discussed in Section 18.6, “Binary Logging of Stored Programs”.
  • Page 170 Upgrading MySQL • Incompatible change: If you have created a user-defined function (UDF) with a given name and upgrade MySQL to a version that implements a new built-in function with the same name, the UDF becomes inaccessible. To correct this, use...
  • Page 171 0 to 255. That is, the value is clipped to the nearest endpoint of the range. However, the result is version-specific: • Before MySQL 5.0.13, the expression is evaluated but is treated as the equivalent 64-bit signed value (–1) for the assignment. The value of –1 is clipped to the nearest endpoint of the column range, resulting in a value of 0: mysql>...
  • Page 172 MySQL 4.1 may FLOAT DOUBLE not do so in 5.0. Values of these types are imprecise in all MySQL versions, and you are strongly advised to avoid such comparisons as col_name=some_double, regardless of the MySQL WHERE version you are using.
  • Page 173: Downgrading Mysql

    MySQL and the version to which you are downgrading. If so and these changes result in an incompatibility between MySQL versions, you will need to downgrade the affected tables using the instructions in Section 2.19.4, “Rebuilding or Repairing Tables or...
  • Page 174: Checking Whether Tables Or Indexes Must Be Rebuilt

    5.1. SUPER TRIGGER • Triggers were added in MySQL 5.0, so if you downgrade from 5.0 to 4.1, you cannot use triggers at all. • The column definition changed between MySQL 5.1 and 5.5. After a mysql.proc.comment...
  • Page 175 1. Stop the server for the existing version if it is running. 2. Install a different version of MySQL. This is an upgrade if the new version is higher than the original version, a downgrade if the version is lower.
  • Page 176: Rebuilding Or Repairing Tables Or Indexes

    2.19.4. Rebuilding or Repairing Tables or Indexes This section describes how to rebuild a table. This can be necessitated by changes to MySQL such as how data types are handled or changes to character set handling. For example, an error in a collation might have been corrected, necessitating a table rebuild to update the indexes for character columns that use the collation.
  • Page 177 --repair --databases db_name ... shell> mysqlcheck --repair --all-databases For incompatibilities introduced in MySQL 5.1.24 by the fix for Bug #27877 that corrected the collations, a workaround is implemented as of MySQL utf8_general_ci ucs2_general_ci 5.1.62, 5.5.21, and 5.6.5. Upgrade to one of those versions, then convert each affected table using one of the following methods.
  • Page 178: Copying Mysql Databases To Another Machine

    You can copy the .frm, .MYI, and files for tables between different architectures .MYD MyISAM that support the same floating-point format. (MySQL takes care of any byte-swapping issues.) See Section 14.1, “The Storage Engine”. MyISAM In cases where you need to transfer databases between different architectures, you can use to create a file containing SQL statements.
  • Page 179: Operating System-Specific Notes

    2.20.1.2. Linux Binary Distribution Notes The Linux-Intel binary and RPM releases of MySQL are configured for the highest possible speed. We are always trying to use the fastest stable compiler available. The binary release is linked with -static, which means you do not normally need to worry about which version of the system libraries you have.
  • Page 180 2.1 is very poor for programs with many threads that hold glibc the mutex only for a short time. This produces a paradoxical result: If you link MySQL against an unmodified LinuxThreads, removing processors from an SMP actually improves MySQL performance in many cases.
  • Page 181 STACK_SIZE PTHREAD_THREADS_MAX. We hope that the defaults is corrected to some more acceptable values for high-load MySQL setup in the future, so that the commands needed to produce your own build can be reduced to ./configure; make; make install.
  • Page 182 MySQL (as long as one minute), and it may take just as long to shut it down. On multiple-CPU systems, we have observed a gradual drop in query speed as the number of clients increases. In the process of trying to find a solution, we have received a kernel patch from one of our users who claimed it helped for his site.
  • Page 183 [500] option. mysqld --thread-stack=192K This stack size is the default on MySQL 4.0.10 and above, so you should not see the problem. If you are using 3.0 and above to compile MySQL, you must install the libstdc+ library before compiling MySQL; if you do not do this, you get an error about a missing symbol during linking.
  • Page 184 2.20.1.7. Linux Alpha Notes We have tested MySQL 5.0 on Alpha with our benchmarks and test suite, and it appears to work well. We currently build the MySQL binary packages on SuSE Linux 7.0 for AXP, kernel 2.4.4-SMP, Compaq C compiler (V6.2-505) and Compaq C++ compiler (V6.3-006) on a Compaq DS20 machine with an Alpha EV6 processor.
  • Page 185: Mac Os X Notes

    For current versions of Mac OS X Server, no operating system changes are necessary before compiling MySQL. Compiling for the Server platform is the same as for the client version of Mac OS X. For older versions (Mac OS X Server 1.2, a.k.a. Rhapsody), you must first install a pthread package before trying to configure MySQL.
  • Page 186 Section 2.13, “Installing MySQL on Solaris”. On Solaris, you may run into trouble even before you get the MySQL distribution unpacked, as the Solaris cannot handle long file names. This means that you may see errors when you try to unpack MySQL.
  • Page 187 Solaris does not provide static versions of all system libraries (libpthreads and libdl), so you cannot compile MySQL with --static. If you try to do so, you get one of the following errors: ld: fatal: library -ldl: not found undefined reference to `dlopen'...
  • Page 188 /etc/rc3.d/S99mysql.server. etc/init.d If too many processes try to connect very rapidly to mysqld, you should see this error in the MySQL log: Error in accept: Protocol error You might try starting the server with the [437] option as a workaround for this.
  • Page 189: Bsd Notes

    Using these ports gives you the following benefits: • A working MySQL with all optimizations enabled that are known to work on your version of FreeBSD. • Automatic configuration and build. • Startup scripts installed in /usr/local/etc/rc.d.
  • Page 190 To compile on NetBSD, you need GNU make. Otherwise, the build process fails when tries to run make on C++ files. lint 2.20.4.3. OpenBSD 2.5 Notes On OpenBSD 2.5, you can compile MySQL with native threads with the following options:...
  • Page 191 2.20.4.6. BSD/OS Version 4.x Notes BSDI 4.x has some thread-related bugs. If you want to use MySQL on this, you should install all thread- related patches. At least M400-023 should be installed. On some BSDI 4.x systems, you may get problems with shared libraries. The symptom is that you can't execute any client programs, for example, mysqladmin.
  • Page 192: Other Unix Notes

    2.20.5. Other Unix Notes 2.20.5.1. HP-UX Version 10.20 Notes If you install MySQL using a binary tarball distribution on HP-UX, you may run into trouble even before you get the MySQL distribution unpacked, as the HP-UX cannot handle long file names. This means that you may see errors when you try to unpack MySQL.
  • Page 193 We have also received reports that the HP-UX 10.20 binaries supplied by MySQL can be run successfully on HP-UX 11. If you encounter problems, you should be sure to check your HP-UX patch level.
  • Page 194 (5300-07). If you have problems with signals (MySQL dies unexpectedly under high load), you may have found an OS bug with threads and signals. In this case, you can tell MySQL not to use signals by configuring as follows: CFLAGS=-DDONT_USE_THR_ALARM CXX=gcc \ CXXFLAGS="-felide-constructors -fno-exceptions -fno-rtti \...
  • Page 195 (WINDOW *); 2.20.5.4. SunOS 4 Notes On SunOS 4, MIT-pthreads is needed to compile MySQL. This in turn means you need GNU make. Some SunOS 4 systems have problems with dynamic libraries and libtool. You can use the...
  • Page 196 If you get a problem with when compiling with shared libraries as just shown, when linking libtool mysql, you should be able to get around this by issuing these commands: cd mysql /bin/sh ../libtool --mode=link cxx -pthread -O3 -DDBUG_OFF \...
  • Page 197 CFLAGS=-D_PTHREAD_USE_D4 CXX=gcc CXXFLAGS=-O3 ./configure ... If you have problems with signals (MySQL dies unexpectedly under high load), you may have found an OS bug with threads and signals. In this case, you can tell MySQL not to use signals by configuring with:...
  • Page 198 2.20.5.7. SGI Irix Notes As of MySQL 5.0, we do not provide binaries for Irix any more. If you are using Irix 6.5.3 or newer, is able to create threads only if you run it as a user that...
  • Page 199 There has also been progress on a port to sco3.2v4.2. Open Server 5.0.8 (Legend) has native threads and permits files greater than 2GB. The current maximum file size is 2GB. We have been able to compile MySQL with the following command on OpenServer with configure 2.95.3.
  • Page 200 Other Unix Notes By default, the entries in are set as follows: /etc/conf/cf.d/mtune Value Default ----- ------- NBUF 450000 NHBUF 524288 NMPBUF MAX_INODE 64000 MAX_FILE 64000 CTBUFSIZE MAX_PROC 16000 MAX_REGION 160000 NCLIST 16640 MAXUP 16000 NOFILES 11000 NHINODE 8192 NAUTOUP NGROUPS BDFLUSHR MAX_FLCKREC...
  • Page 201 You also need SCO-3.2v4.2-includes.tar.gz. This file contains the changes to the SCO Development include files that are needed to get MySQL to build. You need to replace the existing system include files with these modified header files. They can be obtained from ftp://ftp.zenez.com/pub/zenez/prgms/SCO-3.2v4.2-includes.tar.gz.
  • Page 202 It is probably a good idea to install these patches before trying to compile/use MySQL. Beginning with Legend/OpenServer 6.0.0, there are native threads and no 2GB file size limit. 2.20.5.9. SCO OpenServer 6.0.x Notes OpenServer 6 includes these key improvements: •...
  • Page 203 Use the latest production release of MySQL. Should you choose to use an older release of MySQL on OpenServer 6.0.x, you must use a version of MySQL at least as recent as 3.22.13 to get fixes for some portability and OS problems.
  • Page 204 CC=gcc CXX=g++ ../configure ... The version of Berkeley DB that comes with either UnixWare 7.1.4 or OpenServer 6.0.0 is not used when building MySQL. MySQL instead uses its own version of Berkeley DB. The configure command needs to build both a static and a dynamic library in src_directory/bdb/build_unix/, but it does not with MySQL's own version.
  • Page 205 Use the latest production release of MySQL. Should you choose to use an older release of MySQL on UnixWare 7.1.x, you must use a version of MySQL at least as recent as 3.22.13 to get fixes for some portability and OS problems.
  • Page 206 • The following formulas are recommended to calculate values for SEMMSL, SEMMNS, and SEMMNU: SEMMSL = 13 13 is what has been found to be the best for both Progress and MySQL. SEMMNS = SEMMSL * number of db servers to be run on the system...
  • Page 207: Os/2 Notes

    When using 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. MySQL must be installed on a partition with a type that supports long file names, such as HPFS, FAT32, and so on.
  • Page 208: Perl Installation Notes

    The default TCP/IP port number. MYSQL_TCP_PORT The default Unix socket file name; used for connections to localhost. MYSQL_UNIX_PORT Used by the shell to find MySQL programs. PATH The directory where temporary files are created. TMPDIR This should be set to your local time zone. See Section C.5.4.6, “Time Zone...
  • Page 209: Installing Perl On Unix

    These tests attempt to connect to the local DBD::mysql MySQL server using the default user name and password. (The default user name is your login name on Unix, and on Windows. The default password is “no password.”) If you cannot connect to ODBC the server with those values (for example, if your account has a password), the tests fail.
  • Page 210: Installing Activestate Perl On Windows

    DBD::mysql release of MySQL. This ensures that the latest versions of the MySQL client libraries are installed correctly. If you do not have access rights to install Perl modules in the system directory or if you want to install local Perl modules, the following reference may be useful: http://servers.digitaldaze.com/extensions/...
  • Page 211 Another cause of this problem may be that Perl and MySQL are not both compiled with gcc. In this case, you can solve the mismatch by compiling both with gcc. You may see the following error from...
  • Page 212 If you want to use the Perl module on a system that does not support dynamic linking (such as SCO), you can generate a static version of Perl that includes and DBD::mysql. The way this works is that you generate a version of Perl with the code linked in and install it on top of your current Perl.
  • Page 213: Tutorial

    MySQL server is available mysql to which you can connect. If this is not true, contact your MySQL administrator. (If you are the administrator, you need to consult the relevant portions of this manual, such as...
  • Page 214: Entering Queries

    If you are logging in on the same machine that MySQL is running on, you can omit the host, and simply use the following: shell> mysql -u user -p...
  • Page 215 1 row in set (0.01 sec) mysql> This query illustrates several things about mysql: • A command normally consists of an SQL statement followed by a semicolon. (There are some exceptions where a semicolon may be omitted. QUIT, mentioned earlier, is one of them. We'll get to others later.)
  • Page 216 | USER() +---------------+ | jon@localhost | +---------------+ prompts occur during string collection (another way of saying that MySQL is waiting for '> "> completion of a string). In MySQL, you can write strings surrounded by either “'” or “"” characters (for...
  • Page 217: Creating And Using A Database

    `> an unterminated string, any further lines you type appear to be ignored by mysql—including a line containing QUIT. This can be quite confusing, especially if you do not know that you need to supply the terminating quote before you can cancel the current command.
  • Page 218: Creating And Selecting A Database

    For this reason, you should probably ask your MySQL administrator for permission to use a database of your own. Suppose that you want to call yours menagerie. The administrator needs to execute a command like this: mysql>...
  • Page 219: Creating A Table

    Creating a Table you can select the database on the command line when you invoke mysql. Just specify its name after any connection parameters that you might need to provide. For example: shell> mysql -h host -u user -p menagerie...
  • Page 220: Loading Data Into A Table

    Loading Data into a Table Note Prior to MySQL 5.0.3, the upper limit was 255.) If you make a poor choice and it turns out later that you need a longer field, MySQL provides an ALTER TABLE statement. Several types of values can be chosen to represent sex in animal records, such as...
  • Page 221: Retrieving Information From A Table

    These are sufficient for the statement to read the file properly. pet.txt If the statement fails, it is likely that your MySQL installation does not have local file capability enabled by default. See Section 6.1.6, “Security Issues with LOCAL”, for information on how to LOAD DATA change this.
  • Page 222 DELETE LOAD DATA: mysql> DELETE FROM pet; mysql> LOAD DATA LOCAL INFILE 'pet.txt' INTO TABLE pet; However, if you do this, you must also re-enter the record for Puffball.
  • Page 223 Retrieving Information from a Table +----------+-------+---------+------+------------+-------+ You can combine conditions, for example, to locate female dogs: mysql> SELECT * FROM pet WHERE species = 'dog' AND sex = 'f'; +-------+--------+---------+------+------------+-------+ | name | owner | species | sex | birth...
  • Page 224: Sorting Rows

    Notice that the query simply retrieves the column from each record, and some of them appear owner more than once. To minimize the output, retrieve each unique output record just once by adding the keyword DISTINCT: mysql> SELECT DISTINCT owner FROM pet; +--------+ | owner +--------+...
  • Page 225 3.3.4.5. Date Calculations 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, use the [930] function.
  • Page 226 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 column. MySQL birth provides several functions for extracting parts of dates, such as...
  • Page 227 Because the result of any arithmetic comparison with is also NULL, you cannot obtain any NULL meaningful results from such comparisons. In MySQL, means false and anything else means true. The default truth value from a NULL boolean operation is 1.
  • Page 228 NULL 3.3.4.7. Pattern Matching 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 vi, grep, and sed. SQL pattern matching enables you to use “_” to match any single character and “%” to match an arbitrary number of characters (including zero characters).
  • Page 229 Retrieving Information from a Table The other type of pattern matching provided by MySQL uses extended regular expressions. When you test for a match for this type of pattern, use the [899] [899] operators (or REGEXP NOT REGEXP [899] [899], which are synonyms).
  • Page 230 Retrieving Information from a Table To find names containing exactly five characters, use “^” and “$” to match the beginning and end of the name, and five instances of “.” in between: mysql> SELECT * FROM pet WHERE name REGEXP '^..$'; +-------+--------+---------+------+------------+-------+...
  • Page 231 Retrieving Information from a Table | snake +---------+----------+ Number of animals per sex: mysql> SELECT sex, COUNT(*) FROM pet GROUP BY sex; +------+----------+ | sex | COUNT(*) | +------+----------+ | NULL | +------+----------+ (In this output, indicates that the sex is unknown.)
  • Page 232 | Harold | +--------+----------+ 1 row in set (0.00 sec) See also Section 12.15.3, “MySQL Extensions to GROUP BY”. 3.3.4.9. Using More Than one Table 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.
  • Page 233: 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 (for example, what its columns are called)? MySQL addresses this problem through several statements that provide information about the databases and tables it supports.
  • Page 234: Using Mysql In Batch Mode

    To do this, put the commands you want to run in a file, then tell mysql mysql to read its input from the file: shell> mysql < batch-file If you are running under Windows and have some special characters in the file that cause mysql problems, you can do this:...
  • Page 235 C:\> mysql -e "source batch-file" If you need to specify connection parameters on the command line, the command might look like this: shell> mysql -h host -u user -p < batch-file Enter password: ******** When you use this way, you are creating a script file, then executing the script.
  • Page 236: Examples Of Common Queries

    Section 4.5.1.5, “Executing SQL Statements from a Text File”, for more information. 3.6. Examples of Common Queries Here are examples of how to solve some common problems with MySQL. Some of the examples use the table to hold the price of each article (item number) for certain shop traders (dealers).
  • Page 237: Maximum Of Column Per Group

    | 19.95 | +---------+--------+-------+ Other solutions are to use a or to sort all rows descending by price and get only the first LEFT JOIN row using the MySQL-specific clause: LIMIT SELECT s1.article, s1.dealer, s1.price FROM shop s1 LEFT JOIN shop s2 ON s1.price < s2.price WHERE s2.article IS NULL;...
  • Page 238: Using User-Defined Variables

    “JOIN s2.price Syntax”. 3.6.5. Using User-Defined Variables You can employ MySQL user variables to remember results without having to store them in temporary variables in the client. (See Section 9.4, “User-Defined Variables”.) For example, to find the articles with the highest and lowest price you can do this: mysql>...
  • Page 239 Using Foreign Keys CREATE TABLE person ( id SMALLINT UNSIGNED NOT NULL AUTO_INCREMENT, name CHAR(60) NOT NULL, PRIMARY KEY (id) CREATE TABLE shirt ( id SMALLINT UNSIGNED NOT NULL AUTO_INCREMENT, style ENUM('t-shirt', 'polo', 'dress') NOT NULL, color ENUM('red', 'blue', 'orange', 'white', 'black') NOT NULL, owner SMALLINT UNSIGNED NOT NULL REFERENCES person(id), PRIMARY KEY (id) INSERT INTO person VALUES (NULL, 'Antonio Paz');...
  • Page 240: Searching On Two Keys

    [881]: SELECT field1_index, field2_index FROM test_table WHERE field1_index = '1' OR field2_index = '1' This case is optimized from MySQL 5.0.0. See Section 8.3.1.4, “Index Merge Optimization”. You can also solve the problem efficiently by using a that combines the output of two separate UNION statements.
  • Page 241 4 | lax 5 | whale 6 | ostrich | +----+---------+ No value was specified for the column, so MySQL assigned sequence numbers AUTO_INCREMENT automatically. You can also explicitly assign or 0 to the column to generate sequence numbers. NULL...
  • Page 242: Using Mysql With Apache

    Variables”. 3.7. Using MySQL with Apache There are programs that let you authenticate your users from a MySQL database and also let you write your log files into a MySQL table. You can change the Apache logging format to be easily readable by MySQL by putting the following...
  • Page 243: Mysql Programs

    4.6.18. — Kill Processes That Match a Pattern ..........370 mysql_zap 4.7. MySQL Program Development Utilities ................370 4.7.1. — Convert mSQL Programs for Use with MySQL ......... 371 msql2mysql 4.7.2. — Display Options for Compiling Clients .......... 371 mysql_config 4.7.3.
  • Page 244: Overview Of Mysql Programs

    If you appear to be missing one or more programs, see Chapter 2, Installing and Upgrading MySQL, for information on types of distributions and what they contain. It may be that you have a distribution that does not include all programs and you need to install an additional package.
  • Page 245 — Check Tables for MySQL Upgrade”. • make_win_src_distribution This program is used on Unix or Unix-like systems to create a MySQL source distribution that can be compiled on Windows. See Section 2.10.8.5, “Creating a Windows Source Package from the Bazaar Repository”, and Section 4.4.3,...
  • Page 246 A table-maintenance client that checks, repairs, analyzes, and optimizes tables. See Section 4.5.3, “mysqlcheck — A Table Maintenance Program”. • mysqldump A client that dumps a MySQL database into a file as SQL, text, or XML. See Section 4.5.4, “mysqldump — A Database Backup Program”. • mysqlimport A client that imports text files into their respective tables using INFILE.
  • Page 247 MyISAM “mysqlhotcopy — A Database Backup Program”. • mysqlmanager The MySQL Instance Manager, a program for monitoring and managing MySQL servers. See Section 4.6.10, “mysqlmanager — The MySQL Instance Manager”. Important MySQL Instance Manager has been deprecated and is removed in MySQL 5.4.
  • Page 248 MySQL. Additional GUI tools include MySQL Notifier for Microsoft Windows MySQL for Excel. MySQL client programs that communicate with the server using the MySQL client/server library use the following environment variables. Environment Variable Meaning The default Unix socket file;...
  • Page 249: Using Mysql Programs

    4.2.2. Connecting to the MySQL Server For a client program to be able to connect to the MySQL server, it must use the proper connection parameters, such as the name of the host where the server is running and the user name and password of your MySQL account.
  • Page 250 • No password is sent if neither [231] is given. --password • For mysql, the first nonoption argument is taken as the name of the default database. If there is no such option, does not select a default database. mysql...
  • Page 251 The host where the server is running. The default value is localhost. • [231], --password[=pass_val] -p[pass_val] The password of the MySQL account. As described earlier, the password value is optional, but if given, there must be no space between [231] and the password following it. --password= The default is to send no password.
  • Page 252: Specifying Program Options

    • [232], --user=user_name -u user_name The user name of the MySQL account you want to use. The default user name is on Windows ODBC or your Unix login name on Unix. It is possible to 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.
  • Page 253 • An option argument begins with one dash or two dashes, depending on whether it is a short form or long form of the option name. Many options have both short and long forms. For example, are the short and long forms of the option that instructs a MySQL program to display its help help message.
  • Page 254 For example, you can use the following command to obtain a list of user accounts: mysql> mysql -u root -p --execute="SELECT User, Host FROM mysql.user" Enter password: ****** +------+-----------+ | User | Host...
  • Page 255 Most MySQL programs can read startup options from option files (also sometimes called configuration files). Option files provide a convenient way to specify commonly used options so that they need not be entered on the command line each time you run a program. For the MySQL server, MySQL provides a number of preconfigured option files.
  • Page 256 See Section 2.10.3.1, “Starting the MySQL Server Instance Configuration Wizard”. On Unix, Linux and Mac OS X, MySQL programs read startup options from the following files, in the specified order (top items are used first). File Name Purpose Global options /etc/my.cnf...
  • Page 257 MySQL looks for option files in the order just described and reads any that exist. If an option file that you want to use does not exist, create it with a plain text editor.
  • Page 258 [458] [466] variables. key_buffer_size max_allowed_packet Here is a typical user option file: [client] # The following password will be sent to all standard MySQL clients password="my_password" [mysql] no-auto-rehash connect_timeout=2 [mysqlhotcopy] interactive-timeout If you want to create option groups that should be read by...
  • Page 259 Read this option file after the global option file but (on Unix) before the user option file. As of MySQL 5.0.6, if the file does not exist or is otherwise inaccessible, the program exits with an error. is the full path name to the file.
  • Page 260 [240] --print-defaults Print the program name and all options that it gets from option files. 4.2.3.5. Using Options to Set Program Variables Many MySQL programs have internal variables that can be set at runtime using the statement. Section 13.7.4, “SET Syntax”, and...
  • Page 261 “tonfisk” using an account with the user name “jon”. Due to this behavior, problems can occasionally arise when no value is provided for an option that expects one. Consider the following example, where a user connects to a MySQL server running on host...
  • Page 262 MySQL in & the background; it is ignored by MySQL itself.) Now suppose that you wish to log errors to a file named my-errors.err. You might try starting the server with my-errors, but this does not...
  • Page 263: Setting Environment Variables

    --user [266], with the result shown here: --host=--user shell> mysql ERROR 2005 (HY000): Unknown MySQL server host '--user' (1) However, in option files, an equal sign is not assumed. Suppose the file is as shown here: my.cnf [mysql] user jon...
  • Page 264: Mysql Server And Server-Startup Programs

    — The MySQL Server mysqld mysqld, also known as MySQL Server, is the main program that does most of the work in a MySQL installation. MySQL Server manages access to the MySQL data directory that contains databases and tables. The data directory is also the default location for other information such as log files and status...
  • Page 265: Mysql Server Startup Script

    --verbose --help MySQL Server also has a set of system variables that affect its operation as it runs. System variables can be set at server startup, and many of them can be changed at runtime to effect dynamic server reconfiguration.
  • Page 266 Description Introduced autoclose [247] On NetWare, mysqld_safe provides a screen autoclose [247] presence basedir [247] The path to the MySQL installation directory basedir=path [247] --core-file- core-file- The size of the core file that mysqld should be size=size [247] size [247]...
  • Page 267: Mysqld_Safe

    The name of an option file to be read in addition to the usual option files. This must be the first option on the command line if it is used. As of MySQL 5.0.6, if the file does not exist or is otherwise inaccessible, the server will exit with an error.
  • Page 268 ID user_id. mysqld user_name (“User” in this context refers to a system login account, not a MySQL user listed in the grant tables.) If you execute with the [247]...
  • Page 269: Mysql.server - Mysql Server Startup Script

    — MySQL Server Startup Script mysql.server distribution at the time it was built. They should be correct if MySQL is installed in the location specified at configuration time. Because tries to find the server and databases relative to its own working directory,...
  • Page 270: Mysqld_Multi

    The default value is 900. A value of 0 means not to wait at mysql.server all for startup. Negative values mean to wait forever (no timeout). This option was added in MySQL 5.0.40. Before that, a value of 900 is always used.
  • Page 271 [251] --help Display a help message and exit. • [251] --config-file=file_name As of MySQL 5.0.42, this option is deprecated. If given, it is treated the same way as --defaults- [251], described earlier. [251] is removed in MySQL 5.5. extra-file --config-file Before MySQL 5.0.42, this option specifies the name of an extra option file.
  • Page 272 [252] --tcp-ip Connect to each MySQL server through the TCP/IP port instead of the Unix socket file. (If a socket file is missing, the server might still be running, but accessible only through the TCP/IP port.) By default, connections are made using the Unix socket file. This option affects...
  • Page 273 — Manage Multiple MySQL Servers mysqld_multi • Make sure that the MySQL account used for stopping the servers (with the mysqld mysqladmin program) has the same user name and password for each server. Also, make sure that the account has the [578] privilege.
  • Page 274: Mysql Installation-Related Programs

    = /usr/local/share/mysql/japanese user = jani Section 4.2.3.3, “Using Option Files”. 4.4. MySQL Installation-Related Programs The programs in this section are used when installing or upgrading MySQL. 4.4.1. — Compile MySQL Error Message File comp_err creates the file that is used by...
  • Page 275: Package Mysql Distribution As Zip Archive

    — Package MySQL Distribution as Zip Archive make_win_bin_dist This script is used on Windows after building a MySQL distribution from source to create executable programs. It packages the binaries and support files into a Zip archive that can be unpacked at the location where you want to install MySQL.
  • Page 276: Make_Win_Src_Distribution

    (See the instructions at Section 2.10.8.5, “Creating a Windows Source Package from the Bazaar Repository”.) Invoke like this from the top-level directory of a MySQL source make_win_src_distribution distribution: shell> make_win_src_distribution [options]...
  • Page 277: Mysqlbug - Generate Bug Report

    Some releases of MySQL introduce changes to the structure of the system tables in the mysql database to add new privileges or support new features. When you update to a new version of MySQL, you should update your system tables as well to make sure that their structure is up to date. Otherwise, there might be capabilities that you cannot take advantage of.
  • Page 278: Initialize Mysql Data Directory

    To invoke mysql_install_db, use the following syntax: shell> mysql_install_db [options] Because the MySQL server, mysqld, needs to access the data directory when it runs later, you should either run from the same system account that will be used for running...
  • Page 279: Improve Mysql Installation Security

    For internal use. This option is used for creating Windows distributions. 4.4.7. — Improve MySQL Installation mysql_secure_installation Security This program enables you to improve the security of your MySQL installation in the following ways: • You can set a password for accounts. root • You can remove accounts that are accessible from outside the local host.
  • Page 280: Load The Time Zone Tables

    MySQL. It supersedes the older mysql_upgrade script, which should no longer be used.
  • Page 281 To ignore this file and perform the check regardless, use the [261] option. force If you install MySQL from RPM packages on Linux, you must install the server and client RPMs. is included in the server RPM but requires the client RPM because the latter includes mysql_upgrade mysqlcheck. (See Section 2.12, “Installing MySQL from RPM Packages on...
  • Page 282: Mysql_Upgrade

    MySQL. mysql_upgrade • [262], --tmpdir=path -t path The path name of the directory to use for creating temporary files. This option was added in MySQL 5.0.62. • [262], --user=user_name -u user_name The MySQL user name to use when connecting to the server.
  • Page 283 --force [266] force [266] Continue even if an SQL error occurs --help [265] Display help message and exit host [266] Connect to the MySQL server on the given host host=host_name [266] --html [267] html [267] Produce HTML output --ignore- ignore-...
  • Page 284 — The MySQL Command-Line Tool mysql Format Option File Description Introduced --no-auto- Disable automatic rehashing rehash [267] --no-beep [267] no-beep [267] Do not beep when errors occur --no-named- no-named- Disable named mysql commands commands [267] commands [267] --no-pager [267] no-pager [267]...
  • Page 285 Append a copy of output to the given file tee=file_name [270] unbuffered [270] Flush the buffer after each query unbuffered [270] user [270] MySQL user name to use when connecting to user=user_name [270] server --verbose [270] Verbose mode --version [270]...
  • Page 286 — The MySQL Command-Line Tool mysql • [266] --character-sets-dir=path The directory where character sets are installed. See Section 10.5, “Character Set Configuration”. • [266] --column-names Write column names in results. • [266], --comments Whether to preserve comments in statements sent to the server. The default is --skip-comments (discard comments), enable with --comments (preserve comments).
  • Page 287 — The MySQL Command-Line Tool mysql Connect to the MySQL server on the given host. • [267], --html Produce HTML output. • [267], --ignore-spaces Ignore spaces after function names. The effect of this is described in the discussion for the...
  • Page 288 -P port_num The TCP/IP port number to use for the connection. • [268] --prompt=format_str Set the prompt to the specified format. The default is mysql>. The special sequences that the prompt can contain are described in Section 4.5.1.2, “mysql Commands”.
  • Page 289 • [269] --show-warnings Cause warnings to be shown after each statement if there are any. This option applies to interactive and batch mode. This option was added in MySQL 5.0.6. • [269] --sigint-ignore Ignore signals (typically the result of typing Control+C).
  • Page 290 If the connection cannot be established, wait and retry instead of aborting. • [270], --xml Produce XML output. Note Prior to MySQL 5.0.26, there was no differentiation in the output when using this option between columns containing the value and columns NULL containing the string literal 'NULL'; both were represented as...
  • Page 291 “mysqldump — A Database Backup Program” mysqldump --xml details. Beginning with MySQL 5.0.40, the XML output also uses an XML namespace, as shown here: shell> mysql --xml -uroot -e "SHOW VARIABLES LIKE 'version%'" <?xml version="1.0"?> <resultset statement="SHOW VARIABLES LIKE 'version%'" xmlns:xsi="http://www.w3.org/2001/XMLSchema-ins <row>...
  • Page 292 If you provide an argument to the command, uses it as a search string to access help mysql server-side help from the contents of the MySQL Reference Manual. For more information, see Section 4.5.1.4, “mysql Server-Side Help”. • charset...
  • Page 293 (“\”) character. Backslash should be avoided outside of quoted strings because it is the escape character for MySQL. For an unquoted argument, the delimiter is read up to the first space or end of line. For a quoted argument, the delimiter is read up to the matching quote on the line.
  • Page 294 — The MySQL Command-Line Tool mysql Enable display of warnings after each statement. This command was added in MySQL 5.0.6. • pager [command], \P [command] Enable output paging. By using the [268] option when you invoke mysql, it is possible to...
  • Page 295 Additionally, file logging can be turned on and pager off interactively from within mysql. This is useful when you want to log some queries to a file, but not others. command reconfigures the default prompt.
  • Page 296 For example: shell> mysql --prompt="(\u@\h) [\d]> " (user@host) [database]> • Use an option file. You can set the option in the group of any MySQL option file, prompt [mysql] such as or the file in your home directory. For example: /etc/my.cnf...
  • Page 297 For example: mysql> prompt (\u@\h) [\d]>\_ PROMPT set to '(\u@\h) [\d]>\_' (user@host) [database]> (user@host) [database]> prompt Returning to default PROMPT of mysql> mysql> 4.5.1.3. Logging mysql On Unix, the client logs statements executed interactively to a history file. By default, this file...
  • Page 298 MySQL Reference Manual. The proper operation of this command requires that the help tables in the database be initialized with help topic information (see mysql Section 5.1.8, “Server-Side...
  • Page 299 USE db_name database name on the command line: shell> mysql < text_file If you are already running mysql, you can execute an SQL script file using the command or source command: mysql>...
  • Page 300 — The MySQL Command-Line Tool mysql 4.5.1.6. Tips mysql This section describes some techniques that can help you use more effectively. mysql 4.5.1.6.1. Input-Line Editing supports input-line editing, which enables you to modify the current input line in place or recall mysql previous input lines.
  • Page 301 SET @a=1; Query OK, 0 rows affected (0.05 sec) mysql> INSERT INTO t VALUES(@a); ERROR 2006: MySQL server has gone away No connection. Trying to reconnect... Connection id: Current database: test Query OK, 1 row affected (1.30 sec) mysql>...
  • Page 302: Mysqladmin - Client For Administering A Mysql Server

    — Client for Administering a MySQL Server mysqladmin For more information about auto-reconnect and its effect on state information when a reconnection occurs, see Section 20.6.14, “Controlling Automatic Reconnection Behavior”. 4.5.2. — Client for Administering a MySQL Server mysqladmin is a client for performing administrative operations. You can use it to check the server's mysqladmin configuration and current status, to create and drop databases, and more.
  • Page 303 — Client for Administering a MySQL Server mysqladmin • password new-password Set a new password. This changes the password to for the account that you use new-password with for connecting to the server. Thus, the next time you invoke (or any...
  • Page 304 • Open tables The number of tables that currently are open. • Memory in use The amount of memory allocated directly by mysqld. This value is displayed only when MySQL has been compiled with [122]. --with-debug=full • Maximum memory used The maximum amount of memory allocated directly by mysqld.
  • Page 305 Continue even if an SQL error occurs --help [286] Display help message and exit host [286] Connect to the MySQL server on the given host host=host_name [286] password [286] The password to use when connecting to the server password[=password] [286]...
  • Page 306 — Client for Administering a MySQL Server mysqladmin Format Option File Description user [287] MySQL user name to use when connecting to server user=user_name, [287] --verbose [287] Verbose mode --version [287] Display version information and exit --vertical [287] vertical [287]...
  • Page 307 SSL keys and certificates. See Section 6.3.6.4, “SSL Command Options”. • [287], --user=user_name -u user_name The MySQL user name to use when connecting to the server. • [287], --verbose Verbose mode. Print more information about what the program does. • [287], --version Display version information and exit.
  • Page 308: Mysqlcheck - A Table Maintenance Program

    — A Table Maintenance Program mysqlcheck The maximum number of seconds to wait for server shutdown. The default value is 3600 (1 hour). It is also possible to set variables by using --var_name=value. The format is --set-variable deprecated. 4.5.3. — A Table Maintenance Program mysqlcheck client performs table maintenance: It checks, repairs, optimizes, or analyzes tables.
  • Page 309 [291] Continue even if an SQL error occurs --help [290] Display help message and exit host [291] Connect to the MySQL server on the given host host=host_name [291] --medium- medium- Do a check that is faster than an --extended...
  • Page 310 [292] Overrides the --databases or -B option --use-frm [293] use-frm [293] For repair operations on MyISAM tables user [293] MySQL user name to use when connecting to user=user_name, [293] server --verbose [293] Verbose mode --version [293] Display version information and exit •...
  • Page 311 CHECK TABLE FOR UPGRADE current version of the server. This option was added in MySQL 5.0.19. • [291] --compress Compress all information sent between the client and the server if both support compression.
  • Page 312 The connection protocol to use for connecting to the server. It is useful when the other connection parameters normally would cause a protocol to be used other than the one you want. For details on the permissible values, see Section 4.2.2, “Connecting to the MySQL Server”. •...
  • Page 313: Mysqldump - A Database Backup Program

    SQL server (not necessarily a MySQL server). The dump typically contains SQL statements to create the table, populate it, or both. However, can also be used to generate files in CSV, other delimited mysqldump text, or XML format.
  • Page 314 The significance of this behavior is that if you dump and restore the table, the new table has contents that differ from the original contents. This problem is fixed as of MySQL 4.1.2; you cannot insert the table, so this behavior is only relevant when you deal with old servers.
  • Page 315 --compact [299] compact [299] Produce more compact output compatible [299] Produce output that is more compatible with other compatible=name[,name,...] [299] database systems or with older MySQL servers --complete- complete- Use complete INSERT statements that include insert [299] insert [299] column names...
  • Page 316 LOAD DATA INFILE --first- first-slave [300] Deprecated; use --lock-all-tables instead slave [300] --flush- flush-logs [300] Flush the MySQL server log files before starting logs [300] the dump --flush- flush- Emit a FLUSH PRIVILEGES statement after privileges [301] privileges [301]...
  • Page 317 — A Database Backup Program mysqldump Format Option File Description Introduced password [303] The password to use when connecting to the password[=password] [303] server --pipe [303] On Windows, connect to server using a named pipe port [303] The TCP/IP port number to use for the connection port=port_num [303] --quick [304] quick [304]...
  • Page 318 Dump triggers for each dumped table --tz-utc [306] tz-utc [306] Add SET TIME_ZONE='+00:00' to the dump file 5.0.15 user [306] MySQL user name to use when connecting to user=user_name [306] server --verbose [306] Verbose mode --version [306] Display version information and exit...
  • Page 319 • [299] --compatible=name Produce output that is more compatible with other database systems or with older MySQL servers. The value of can be ansi, mysql323, mysql40, postgresql, oracle, mssql, db2, maxdb, name no_key_options, no_table_options, or no_field_options. To use several values, separate them by commas.
  • Page 320 --lock-all-tables --first-slave MySQL 5.5. • [300], --flush-logs Flush the MySQL server log files before starting the dump. This option requires the [577] RELOAD privilege. If you use this option in combination with the [298] option, the logs --all-databases are flushed for each database dumped.
  • Page 321 SQL comment containing the view definition to the dump output and continues executing. • [301], --host=host_name -h host_name Dump data from the MySQL server on the given host. The default host is localhost. • [301] --hex-blob Dump binary columns using hexadecimal notation (for example, becomes 0x616263).
  • Page 322 — A Database Backup Program mysqldump Log warnings and errors by appending them to the named file. The default is to do no logging. This option was added in MySQL 5.0.42. • [302] --master-data[=value] Use this option to dump a master replication server to produce a dump file that can be used to set up another server as a slave of the master.
  • Page 323 [304]. It should insert --lock-tables --quick --set-charset give you a fast dump operation and produce a dump file that can be reloaded into a MySQL server quickly. [303] option is enabled by default. Use [305] to disable it. See the...
  • Page 324 MySQL account that has appropriate privileges for the database. mysql This option was added in MySQL 5.0.13. Before that, stored routines are not dumped. Routine values are not dumped until MySQL 5.0.20. This means that before 5.0.20, when routines DEFINER are reloaded, they will be created with the definer set to the reloading user.
  • Page 325 LOCK TABLES This option is not supported for MySQL Cluster tables; the results cannot be guaranteed to be consistent due to the fact that the storage engine supports only the...
  • Page 326 — A Database Backup Program mysqldump Include triggers for each dumped table in the output. This option is enabled by default; disable it with [305]. This option was added in MySQL 5.0.11. Before that, triggers are not --skip-triggers dumped. •...
  • Page 327 You can load the dump file back into the server like this: shell> mysql db_name < backup-file.sql Or like this: shell> mysql -e "source /path-to-backup/backup-file.sql" db_name is also very useful for populating databases by copying data from one MySQL server to mysqldump another:...
  • Page 328: Mysqlimport - A Data Import Program

    MySQL server may get stalled until those statements finish. After that, the dump becomes lock free and does not disturb reads and writes on the tables. If the update statements that the MySQL server receives are short (in terms of execution time), the initial lock period should not be noticeable, even with many updates.
  • Page 329 [310] Continue even if an SQL error occurs --help [310] Display help message and exit host [311] Connect to the MySQL server on the given host host=host_name [311] --ignore [311] ignore [311] See the description for the --replace option...
  • Page 330 The server's Common Name value in its certificate is cert [312] cert [312] verified against the host name used when connecting to the server user [312] MySQL user name to use when connecting to server user=user_name, [312] --verbose [312] Verbose mode --version [312] Display version information and exit •...
  • Page 331 --force mysqlimport • [311], --host=host_name -h host_name Import data to the MySQL server on the given host. The default host is localhost. • [311], --ignore See the description for the [312] option. --replace •...
  • Page 332: Mysqlshow - Display Database, Table, And Column Information

    SSL keys and certificates. See Section 6.3.6.4, “SSL Command Options”. • [312], --user=user_name -u user_name The MySQL user name to use when connecting to the server. • [312], --verbose Verbose mode. Print more information about what the program does. • [312], --version Display version information and exit.
  • Page 333 [314] set=charset_name [314] --help [314] Display help message and exit host [314] Connect to the MySQL server on the given host host=host_name [314] --keys [314] keys [314] Show table indexes password [314] The password to use when connecting to the...
  • Page 334 'd:t:o'. • [314] --default-character-set=charset_name as the default character set. See Section 10.5, “Character Set Configuration”. charset_name • [314], --host=host_name -h host_name Connect to the MySQL server on the given host. • [314], --keys Show table indexes. • [314], --password[=password] -p[password]...
  • Page 335: Mysql Administrative And Utility Programs

    Display extra information about each table. • [315], --user=user_name -u user_name The MySQL user name to use when connecting to the server. • [315], --verbose Verbose mode. Print more information about what the program does. This option can be used multiple times to increase the amount of information.
  • Page 336: Myisam_Ftdump

    — Display Full-Text Index information myisam_ftdump prints checksums for files. This tool reads an tablespace file, innochecksum InnoDB InnoDB calculates the checksum for each page, compares the calculated checksum to the stored checksum, and reports mismatches, which indicate damaged pages. It was originally developed to speed up verifying the integrity of tablespace files after power outages but can also be used after file copies.
  • Page 337: Myisamchk - Myisam Table-Maintenance Utility

    1 If the path name to the database directory is /usr/local/mysql/data/test, you can test also specify the table name argument using that path name. This is useful if you do not invoke in the database directory: myisam_ftdump shell>...
  • Page 338 If you are not in the database directory, you can check all the tables there by specifying the path to the directory: shell> myisamchk /path/to/database_dir/*.MYI You can even check all tables in all databases by specifying a wildcard with the path to the MySQL data directory: shell> myisamchk /path/to/datadir/*/*.MYI...
  • Page 339 — MyISAM Table-Maintenance Utility myisamchk that has died without closing the file properly, which can sometimes lead to the corruption of one or more tables. MyISAM is running, you must force it to flush any table modifications that are mysqld still buffered in memory by using TABLES.
  • Page 340 — MyISAM Table-Maintenance Utility myisamchk Format Option File Description --max-record- max-record- Skip rows larger than the given length if myisamchk length=len [324] length [324] cannot allocate memory to hold them --medium- medium- Do a check that is faster than an --extend-check check [323] check [323] operation...
  • Page 341 262136 write_buffer_size It is also possible to set variables by using --set-variable=var_name=value syntax. However, this syntax is deprecated as of MySQL 4.0. var_name=value The possible variables and their default values can be examined with myisamchk myisamchk -- help:...
  • Page 342 Variables”, and Section 8.5.4, “MyISAM Index Statistics Collection”. For MySQL 5.0, stats_method was added in MySQL 5.0.14. For older versions, the statistics collection method is equivalent to nulls_equal. indicate the minimum and maximum word length for ft_min_word_len ft_max_word_len indexes. names the stopword file. These need to be set under the...
  • Page 343 — MyISAM Table-Maintenance Utility myisamchk Check the table for errors. This is the default operation if you specify no option that selects an operation type explicitly. • [323], --check-only-changed Check only tables that have changed since the last check. • [323], --extend-check Check the table very thoroughly.
  • Page 344 --no-symlinks Do not follow symbolic links. Normally repairs the table that a symlink points to. This myisamchk option does not exist as of MySQL 4.0 because versions from 4.0 on do not remove symlinks during repair operations. • [324] --max-record-length=len Skip rows larger than the given length if cannot allocate memory to hold them.
  • Page 345 • [325] --set-collation=name Specify the collation to use for sorting table indexes. The character set name is implied by the first part of the collation name. This option was added in MySQL 5.0.3. • [325], --sort-recover Force to use sorting to resolve the keys even if the temporary files would be very large.
  • Page 346 • myisamchk -d tbl_name Runs in “describe mode” to produce a description of your table. If you start the MySQL myisamchk server with external locking disabled, may report an error for a table that is updated myisamchk while it runs.
  • Page 347 — MyISAM Table-Maintenance Utility myisamchk Suppose also that the table has these data and index file sizes: -rw-rw---- 1 mysql mysql 9347072 Aug 19 11:47 person.MYD -rw-rw---- 1 mysql mysql 6066176 Aug 19 11:47 person.MYI Example of output: myisamchk -dvv...
  • Page 348 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 MySQL yet. For fixed tables, this is a row address. For dynamic tables, this is a byte address.
  • Page 349 • Blocksize The size of each index block. By default this is 1024, but the value may be changed at compile time when MySQL is built from source. • Rec/key This is a statistical value used by the optimizer. It tells how many rows there are per value for this index.
  • Page 350 — MyISAM Table-Maintenance Utility myisamchk • no endspace Do not store endspace. • no endspace, not_always Do not store endspace and do not do endspace compression for all values. • no endspace, no empty Do not store endspace. Do not store empty values. •...
  • Page 351 (very near theoretical maximum). • Packed MySQL tries to pack key values that have a common suffix. This can only be used for indexes on columns. For long indexed strings that have similar leftmost parts, this can CHAR VARCHAR significantly reduce the space used.
  • Page 352 — MyISAM Table-Maintenance Utility myisamchk • Recordblocks How many blocks (links) are used. For fixed-format tables, this is the same as the number of rows. • Deleteblocks How many blocks (links) are deleted. • Recorddata How many bytes in the data file are used. •...
  • Page 353: Myisamlog - Display Myisam Log File Contents

    — Display MyISAM Log File Contents myisamlog You can check the length of the keys and the with row_pointer_length myisamchk - (see Section 4.6.3.5, “Obtaining Table Information with myisamchk”). The dv tbl_name values are the row_pointer_length number_of_rows Datafile pointer Data values in the table description.
  • Page 354: Myisampack - Generate Compressed, Read-Only Myisam Tables

    If mmap() mmap() does not work, MySQL falls back to normal read/write file operations. Please note the following: • If the server was invoked with external locking disabled, it is not a good idea to invoke mysqld if the table might be updated by the server during the packing process.
  • Page 355 — Generate Compressed, Read-Only MyISAM Tables myisampack Produce a packed table even if it becomes larger than the original or if the intermediate file from an earlier invocation of exists. (myisampack creates an intermediate file named myisampack in the database directory while it compresses the table. If you kill myisampack, tbl_name.TMD file might not be deleted.) Normally, exits with an error if it finds that...
  • Page 356 — Generate Compressed, Read-Only MyISAM Tables myisampack table description: Key Start Len Index Type Root Blocksize Rec/key unique unsigned long 1024 1024 multip. text 10240 1024 Field Start Length Type shell> myisampack station.MYI Compressing station.MYI: (1192 records) - Calculating statistics normal: empty-space: empty-zero:...
  • Page 357 — Generate Compressed, Read-Only MyISAM Tables myisampack 87.14% Remember to run myisamchk -rq on compressed tables shell> ls -l station.* -rw-rw-r-- 1 monty 127874 Apr 17 19:00 station.MYD -rw-rw-r-- 1 monty 55296 Apr 17 19:04 station.MYI -rw-rw-r-- 1 monty 5767 Apr 17 19:00 station.frm shell>...
  • Page 358 — Generate Compressed, Read-Only MyISAM Tables myisampack no endspace, no empty no empty no empty no endspace no empty no empty no zeros, zerofill(2) no zeros, zerofill(1) displays the following kinds of information: myisampack • normal The number of columns for which no extra packing is used. •...
  • Page 359: Mysqlaccess - Client For Checking Access Privileges

    After you run myisampack, you must run to re-create any indexes. At this time, you myisamchk can also sort the index blocks and create statistics needed for the MySQL optimizer to work more efficiently: shell> myisamchk -rq --sort-index --analyze tbl_name.MYI...
  • Page 360 [341] Display some examples that show how to use mysqlaccess --old_server [341] old_server [341] Assume that the server is an old MySQL server (prior to MySQL 3.21) password [341] The password to use when connecting to the server password[=password] [341]...
  • Page 361 [341] --howto Display some examples that show how to use mysqlaccess. • [341] --old_server Assume that the server is an old MySQL server (before MySQL 3.21) that does not yet know how to handle full clauses. WHERE • [341], --password[=password] -p[password] The password to use when connecting to the server.
  • Page 362: Mysqlbinlog - Utility For Processing Binary Log Files

    The user name to use in the access privileges. • [342], --version Display version information and exit. If your MySQL distribution is installed in some nonstandard location, you must change the location where expects to find the client. Edit the script at approximately...
  • Page 363 Section 7.5, “Point-in-Time (Incremental) Recovery Using the Binary Log”. Normally, you use to read binary log files directly and apply them to the local MySQL mysqlbinlog server. It is also possible to read binary logs from a remote server by using the --read-from- [346] option.
  • Page 364 --to-last- to-last-log [347] Do not stop at the end of requested binary log log [347] from a MySQL server, but rather continue printing to end of last binary log user [347] MySQL user name to use when connecting to user=user_name, [347]...
  • Page 365 Disable binary logging. This is useful for avoiding an endless loop if you use the --to-last- [347] option and are sending the output to the same MySQL server. This option also is useful when restoring after a crash to avoid duplication of the statements you have logged. This option requires that you have the [578] privilege.
  • Page 366 Section 4.2.2, “Connecting to the MySQL Server”. • [346], --read-from-remote-server Read the binary log from a MySQL server rather than reading a local log file. Any connection parameter options are ignored unless this option is given as well. These options are [345], --host [345],...
  • Page 367 Do not stop at the end of the requested binary log from a MySQL server, but rather continue printing until the end of the last binary log. If you send the output to the same MySQL server, this may lead to an endless loop.
  • Page 368 10:30 a.m.”). If you have more than one binary log to execute on the MySQL server, the safe method is to process them all using a single connection to the server. Here is an example that demonstrates what may be unsafe: shell>...
  • Page 369 Meaning This event should never be present in the log. 00 UNKNOWN_EVENT This indicates the start of a log file written by MySQL 4 or earlier. 01 START_EVENT_V3 The most common type of events. These contain statements executed on 02 QUERY_EVENT the master.
  • Page 370: Mysqldumpslow - Summarize Slow Query Log Files

    4.6.8. — Summarize Slow Query Log Files mysqldumpslow The MySQL slow query log contains information about queries that take a long time to execute (see Section 5.2.4, “The Slow Query Log”). parses MySQL slow query log files and prints mysqldumpslow a summary of their contents.
  • Page 371 [351], --verbose Verbose mode. Print more information about what the program does. Example of usage: shell> mysqldumpslow Reading mysql slow query log from /usr/local/mysql/data/mysqld51-apple-slow.log Count: 1 Time=4.32s (4s) Lock=0.00s (0s) Rows=0.0 (0), root[root]@localhost insert into t2 select * from t1 Count: 3 Time=2.53s (7s)
  • Page 372: Mysqlhotcopy - A Database Backup Program

    [353] Flush logs after all tables are locked --help [353] Display help message and exit host [353] Connect to the MySQL server on the given host host=host_name [353] --keepold [353] keepold [353] Do not delete previous (renamed) target when done...
  • Page 373 Reset the master.info file after locking all the tables socket [354] For connections to localhost socket=path [354] --tmpdir=path [354] tmpdir [354] The temporary directory user [354] MySQL user name to use when connecting to server user=user_name, [354] • [353], --help Display a help message and exit. • [353] --addtodest Do not rename target directory (if it exists);...
  • Page 374: Mysqlmanager - The Mysql Instance Manager

    Database Server instances. MySQL Instance Manager is available for Unix-like operating systems, and also on Windows as of MySQL 5.0.13. It runs as a daemon that listens on a TCP/IP port. On Unix, it also listens on a Unix socket file.
  • Page 375 • Instance Manager provides remote instance management. That is, it runs on the host where you want to control MySQL Server instances, but you can connect to it from a remote host to perform instance-management operations.
  • Page 376 The IP address to bind to. • [356] --default-mysqld-path=path The path name of the MySQL Server binary. This path name is used for all server instance sections in the configuration file for which no option is present. The default value of this mysqld-path option is the compiled-in path name, which depends on how the MySQL distribution was configured.
  • Page 377 • [357] --standalone This option is used on Windows to run Instance Manager in standalone mode. You should specify it when you start Instance Manager from the command line. This option was added in MySQL 5.0.13. • [357] --user=user_name On Unix, the user name of the system account to use for starting and running mysqlmanager. This...
  • Page 378 — The MySQL Instance Manager mysqlmanager This option was added in MySQL 5.0.19. Before that, the timeout is 30 seconds and cannot be changed. 4.6.10.2. MySQL Instance Manager Configuration Files Important MySQL Instance Manager is been deprecated in MySQL 5.1 and is removed in MySQL 5.5.
  • Page 379 (the MySQL Instance Manager binary) to start MySQL. (In prior versions of MySQL mysqlmanager script is used for this purpose.) Starting from MySQL 5.0.4, the behavior of the mysqld_safe startup script was changed again to incorporate both setup schemes. In version 5.0.4, the startup script...
  • Page 380 Instance Manager password encryption is the same as that used by MySQL Server. It is a one-way operation; no means are provided for decrypting encrypted passwords. Instance Manager accounts differ somewhat from MySQL Server accounts: •...
  • Page 381 You are not required to create this account for MySQL Server; in fact, it is expected that it will not exist. Instance Manager can tell that a server is operational if the server accepts the connection attempt but refuses access for the account by returning a login error.
  • Page 382 --port=2273 --host=im.example.org --user=mysql --password Instance Manager supports the version of the MySQL client/server protocol used by the client tools and libraries distributed with MySQL 4.1 or later, so other programs that use the MySQL C API also can connect to it.
  • Page 383 If no log file path is specified in the instance section of the configuration file (for example, log=/var/mysql.log), the Instance Manager tries to guess its placement. If Instance Manager is unable to guess the log file placement you should specify the log file location explicitly by using a log option in the appropriate instance section of the configuration file.
  • Page 384: Mysql_Convert_Table_Format - Convert Tables To Use A Given Storage

    SET mysqld2.port=3322; Query OK, 0 rows affected (0.00 sec) Changes made to the configuration file do not take effect until the MySQL server is restarted. In addition, these changes are not stored in the instance manager's local cache of instance settings until a command is executed.
  • Page 385: Mysql_Explain_Log

    Specify the storage engine that the tables should be converted to use. The default is if this MyISAM option is not given. • [365] --user=user_name The MySQL user name to use when connecting to the server. • [365] --verbose Verbose mode. Print more information about what the program does. • [365] --version Display version information and exit.
  • Page 386: Extract Sql Statements From Files

    The utility was written for use USE db_name with update log files (as used prior to MySQL 5.0) and as such expects statements to be terminated with semicolon (;) characters. It may be useful with other files that contain SQL statements as long as statements are terminated with semicolons.
  • Page 387: Mysql_Setpermission - Interactively Set Permissions In Grant Tables

    --help connect to the MySQL server. The account used when you connect determines which permissions you have when attempting to modify existing permissions in the grant tables. also reads options from the...
  • Page 388 [369] Generate column metadata into the col table --help [368] Display help message and exit host [369] Connect to the MySQL server on the given host host=host_name [369] --idx [369] idx [369] Generate index metadata into the idx table...
  • Page 389: Kill Process And Wait For Its Termination

    The password to use when connecting to the server. Note that the password value is not optional for this option, unlike for other MySQL programs. You can use an option file to avoid giving the password on the command line.
  • Page 390: Kill Processes That Match A Pattern

    Test mode. Display information about each process but do not kill it. 4.7. MySQL Program Development Utilities This section describes some utilities that you may find useful when developing MySQL programs. In shell scripts, you can use the program to parse option files and see my_print_defaults what options would be used by a given program.
  • Page 391: Msql2Mysql - Convert Msql Programs For Use With Mysql

    C++ program that handles multiply specified options this way but that 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 MySQL clients to see how to do this.
  • Page 392: My_Print_Defaults

    -lz -lpthread -lcrypt -lnsl -lm -lpthread -lrt] You can use within a command line using backticks to include the output that it mysql_config produces for a particular option. For example, to compile and link a MySQL client program, use as follows: mysql_config shell>...
  • Page 393: Resolve_Stack_Dump

    4.8. Miscellaneous Programs 4.8.1. — Explain Error Codes perror For most system errors, MySQL displays, in addition to an internal text message, the system error code in one of the following styles: message ... (errno: #) message ... (Errcode: #)
  • Page 394: Replace - A String-Replacement Utility

    Example: shell> perror 13 64 OS error code Permission denied OS error code Machine is not on the network To obtain the error message for a MySQL Cluster error code, invoke with the [374] perror --ndb option: shell> perror --ndb errorcode Note that the meaning of system error messages may be dependent on your operating system.
  • Page 395: Resolveip - Resolve Host Name To Ip Address Or Vice Versa

    -- file1 file2 ... program is used by msql2mysql. See Section 4.7.1, “msql2mysql — Convert mSQL replace Programs for Use with MySQL”. supports the following options. replace • -?, Display a help message and exit. • -#debug_options Enable debugging.
  • Page 397: Mysql Server Administration

    Please consider upgrading to a recent version. MySQL Server (mysqld) is the main program that does most of the work in a MySQL installation. This chapter provides an overview of MySQL Server and covers general server administration: • Server configuration •...
  • Page 398: Server Option And Variable Reference

    Where appropriate, a direct link to further information on the item as available. For a version of this table that is specific to MySQL Cluster, see Section 17.3.4.1, “MySQL Cluster Server Option and Variable Reference”.
  • Page 399 Server Option and Variable Reference Name Cmd-Line Option file System Var Status Var Var Scope Dynamic bdb_log_buffer_size [438] Global bdb-logdir [1309] Global - Variable: Global bdb_logdir bdb_max_lock [439] Global bdb-no- recover [1310] bdb-shared- Global data [1310] - Variable: Global bdb_shared_data bdb- Global tmpdir [1310]...
  • Page 400 Server Option and Variable Reference Name Cmd-Line Option file System Var Status Var Var Scope Dynamic - Variable: Both character_set_server character_set_system [443] Global character-sets- Global dir [402] - Variable: Global character_sets_dir chroot [403] collation_connection [443] Both collation_database [444] Both collation- Both server [403] - Variable:...
  • Page 401 Server Option and Variable Reference Name Cmd-Line Option file System Var Status Var Var Scope Dynamic Com_drop_user [523] Both Com_execute_sql [523] Both Com_flush [523] Both Com_grant [523] Both Com_ha_close [523] Both Com_ha_open [523] Both Com_ha_read [523] Both Com_help [523] Both Com_insert [523] Both Com_insert_select [523]...
  • Page 402 Server Option and Variable Reference Name Cmd-Line Option file System Var Status Var Var Scope Dynamic Com_show_engine_status [523] Both Com_show_errors [523] Both Com_show_events [523] Both Com_show_fields [523] Both Com_show_grants [523] Both Com_show_innodb_status [523] Both Com_show_keys [523] Both Com_show_logs [523] Both Com_show_master_status [523] Both Com_show_ndb_status [523]...
  • Page 403 Server Option and Variable Reference Name Cmd-Line Option file System Var Status Var Var Scope Dynamic completion_type [444] Both Compression [524] Session concurrent_insert [445] Global connect_timeout [445] Global Connections [524] Global console [404] core-file [404] Created_tmp_disk_tables [524] Both Created_tmp_files [524] Global Created_tmp_tables [524] Both...
  • Page 404 Server Option and Variable Reference Name Cmd-Line Option file System Var Status Var Var Scope Dynamic enable- locking [407] enable-named- pipe [407] - Variable: named_pipe enable- pstack [407] engine-condition- Both pushdown [407] - Variable: Both engine_condition_pushdown error_count [450] Session exit-info [408] expire_logs_days [450] Global external-...
  • Page 405 Server Option and Variable Reference Name Cmd-Line Option file System Var Status Var Var Scope Dynamic Handler_update [526] Both Handler_write [526] Both have_archive [454] Global have_bdb [454] Global have_blackhole_engine [454] Global have_community_features [454] Global have_compress [454] Global have_crypt [454] Global have_csv [454] Global have_example_engine [454]...
  • Page 406 Server Option and Variable Reference Name Cmd-Line Option file System Var Status Var Var Scope Dynamic Innodb_buffer_pool_pages_latched [526] Global Innodb_buffer_pool_pages_misc [526] Global Innodb_buffer_pool_pages_total [526] Global Innodb_buffer_pool_read_ahead_rnd [526] Global Innodb_buffer_pool_read_ahead_seq [526] Global Innodb_buffer_pool_read_requests [526] Global Innodb_buffer_pool_reads [527] Global innodb_buffer_pool_size [1238] Global Innodb_buffer_pool_wait_free [527] Global Innodb_buffer_pool_write_requests [527]...
  • Page 407 Server Option and Variable Reference Name Cmd-Line Option file System Var Status Var Var Scope Dynamic Innodb_log_write_requests [528] Global Innodb_log_writes [528] Global innodb_max_dirty_pages_pct [1248] Global innodb_max_purge_lag [1248] Global innodb_mirrored_log_groups [1249] Global innodb_open_files [1249] Global Innodb_os_log_fsyncs [528] Global Innodb_os_log_pending_fsyncs [528] Global Innodb_os_log_pending_writes [528] Global Innodb_os_log_written [528]...
  • Page 408 Server Option and Variable Reference Name Cmd-Line Option file System Var Status Var Var Scope Dynamic Key_blocks_unused [529] Global Key_blocks_used [529] Global key_buffer_size [458] Global key_cache_age_threshold [459] Global key_cache_block_size [460] Global key_cache_division_limit [460] Global Key_read_requests [529] Global Key_reads [529] Global Key_write_requests [529] Global Key_writes [529]...
  • Page 409 Server Option and Variable Reference Name Cmd-Line Option file System Var Status Var Var Scope Dynamic log-queries- Global not-using- indexes [412] - Variable: Global log_queries_not_using_indexes log-short- format [412] log-slave- Global updates [1451] - Variable: Global log_slave_updates log_slave_updates [1471] Global log-slow-admin- statements [412] log-slow- Global...
  • Page 410 Server Option and Variable Reference Name Cmd-Line Option file System Var Status Var Var Scope Dynamic master-ssl- ca [1454] master-ssl- capath [1454] master-ssl- cert [1454] master-ssl- cipher [1454] master-ssl- key [1454] master- user [1454] max_allowed_packet [466] Global max_binlog_cache_size [1471] Global max-binlog- dump- events [1470]...
  • Page 411 Server Option and Variable Reference Name Cmd-Line Option file System Var Status Var Var Scope Dynamic myisam- recover [415] - Variable: myisam_recover_options myisam_recover_options [475] Global myisam_repair_threads [475] Both myisam_sort_buffer_size [476] Both myisam_stats_method [476] Both named_pipe [477] Global ndb_autoincrement_prefetch_sz [1612] Both ndb_cache_check_time [1612] Global Ndb_cluster_node_id [1615]...
  • Page 412 Server Option and Variable Reference Name Cmd-Line Option file System Var Status Var Var Scope Dynamic open-files- Global limit [417] - Variable: Global open_files_limit Open_streams [530] Global Open_tables [530] Both Opened_tables [530] Both optimizer_prune_level [480] Both optimizer_search_depth [481] Both pid-file [417] Global - Variable: Global...
  • Page 413 Server Option and Variable Reference Name Cmd-Line Option file System Var Status Var Var Scope Dynamic rand_seed1 [487] Session rand_seed2 [487] Session range_alloc_block_size [487] Both read_buffer_size [488] Both read_only [488] Global read_rnd_buffer_size [489] Both relay-log [1455] Global - Variable: Global relay_log relay-log- Global...
  • Page 414 Server Option and Variable Reference Name Cmd-Line Option file System Var Status Var Var Scope Dynamic - Variable: Global report_password report- Global port [1461] - Variable: Global report_port report- Global user [1461] - Variable: Global report_user rpl_recovery_rank [1465] Global Rpl_status [531] Global safe- mode [418]...
  • Page 415 Server Option and Variable Reference Name Cmd-Line Option file System Var Status Var Var Scope Dynamic skip-concurrent- insert [420] - Variable: concurrent_insert skip-external- Global locking [420] - Variable: Global skip_external_locking skip-grant- tables [420] skip-host- cache [420] skip- locking [408] skip-log- warnings [414] skip- merge [420]...
  • Page 416 Server Option and Variable Reference Name Cmd-Line Option file System Var Status Var Var Scope Dynamic slave-load- Global tmpdir [1462] - Variable: Global slave_load_tmpdir slave-net- Global timeout [1462] - Variable: Global slave_net_timeout Slave_open_temp_tables [531] Global Slave_retried_transactions [531] Global Slave_running [531] Global slave-skip- Global...
  • Page 417 Server Option and Variable Reference Name Cmd-Line Option file System Var Status Var Var Scope Dynamic sql_slave_skip_counter [1467] Global sql_warnings [496] Session ssl [607] Ssl_accept_renegotiates [532] Global Ssl_accepts [532] Global ssl-ca [608] Global - Variable: ssl_ca Global Ssl_callback_cache_hits [532] Global ssl- Global capath [608]...
  • Page 418 Server Option and Variable Reference Name Cmd-Line Option file System Var Status Var Var Scope Dynamic storage_engine [497] Both symbolic- links [421] sync-bdb- Global logs [1310] - Variable: Global sync_bdb_logs sync_binlog [1472]Yes Global sync_frm [497] Global sysdate-is- now [423] system_time_zone [498] Global table_cache [498] Global...
  • Page 419: Server Configuration Defaults

    Section 5.1.4, “Server System Variables”. MySQL provides a number of preconfigured option files that can be used as a basis for tuning the MySQL server. Look for files named my-small.cnf, my-medium.cnf, my-large.cnf, and huge.cnf, which are sample option files for small, medium, large, and very large systems. On Windows, the extension is rather than .cnf.
  • Page 420 Suppose that the data directory is /var/mysql/data. If a file-valued option is given as a relative path name, it will be located under /var/mysql/data. If the value is an absolute path name, its location is as given by the path name.
  • Page 421 • [401] --ansi Command-Line Format --ansi Option-File Format ansi Use standard (ANSI) SQL syntax instead of MySQL syntax. For more precise control over the server SQL mode, use the [422] option instead. See Section 1.8.3, “Running MySQL in --sql-mode ANSI Mode”, and...
  • Page 422 Server Command Options The MySQL server listens on a single network socket for TCP/IP connections. This socket is bound to a single address, but it is possible for an address to map onto multiple network interfaces. The default address is 0.0.0.0. To specify an address explicitly, use the...
  • Page 423 Global, Session Dynamic Variable Permitted Values Type string The file system character set. This option sets the [442] system character_set_filesystem variable. It was added in MySQL 5.0.19. • [403], --character-set-server=charset_name -C charset_name Command-Line Format --character-set-server Option-File Format character-set-server Option Sets Variable...
  • Page 424 [247] option --core-file-size to mysqld_safe. See Section 4.3.2, “mysqld_safe — MySQL Server Startup Script”. On some systems, such as Solaris, you do not get a core file if you are also using the [424] option. --user There might be additional restrictions or limitations. For example, it might be necessary to execute before starting the server.
  • Page 425 'd:t:i:o,mysqld.trace'. See MySQL Internals: Porting to Other Systems. As of MySQL 5.0.25, using [122] to configure MySQL with debugging support --with-debug enables you to use the [405] option when you start the server. --debug="d,parser_debug" This causes the Bison parser that is used to process SQL statements to dump a parser trace to the server's standard error output.
  • Page 426 Server Command Options Option-File Format default-storage-engine Variable Name storage_engine Variable Scope Global, Session Dynamic Variable Set the default storage engine (table type) for tables. See Chapter 14, Storage Engines. • [406] --default-table-type=type Version Deprecated Command-Line Format --default-table-type=name Option-File Format default-table-type Deprecated 5.0, by default-storage-engine...
  • Page 427 Note If you set this variable to ALL, you should not use tables from within MyISAM another program (such as another MySQL server or myisamchk) when the tables are in use. Doing so leads to index corruption. • [407] --des-key-file=file_name...
  • Page 428 Default FALSE Enable external locking (system locking), which is disabled by default as of MySQL 4.0. Note that if you use this option on a system on which does not fully work (such as Linux), it is easy for lockd to deadlock.
  • Page 429 InnoDB binary log is smaller or shorter than it should be. See Section 5.2.3, “The Binary Log”. This option was removed in MySQL 5.0.3, having been made obsolete by the introduction of XA transaction support. • --innodb-xxx Set an option for the storage engine.
  • Page 430 (Windows only) Install the server as a Windows service that starts automatically during Windows startup. The default service name is if no value is given. For more MySQL service_name information, see Section 2.10.4.7, “Starting MySQL as a Windows Service”. • [410] --install-manual [service_name] Command-Line Format --install-manual [service_name] (Windows only) Install the server as a Windows service that must be started manually.
  • Page 431 Log errors and startup messages to this file. See Section 5.2.1, “The Error Log”. If you omit the file name, MySQL uses host_name.err. If the file name has no extension, the server adds an extension of .err. • [411]...
  • Page 432 [412].) The [412] option is available short-format --log-queries-not-using-indexes for the purpose of logging queries that do not use indexes to the slow query log. --log-long- [411] is removed in MySQL 5.5. format • [412] --log-queries-not-using-indexes Command-Line Format --log-queries-not-using-indexes Option-File Format...
  • Page 433 The default name is tc.log. The file is created under the data directory if not given as a full path name. Currently, this option is unused. Added in MySQL 5.0.3. •...
  • Page 434 Server Command Options The size in bytes of the memory-mapped transaction coordinator log. The default size is 24KB. Added in MySQL 5.0.3. • [414], --log-warnings[=level] -W [level] Command-Line Format --log-warnings[=#] -W [#] Option-File Format log-warnings Option Sets Variable Yes, [464]...
  • Page 435 Use of this option may require you to run the server as root, which, for reasons of security, is normally not a good idea. See Section 6.1.5, “How to Run MySQL as a Normal User”. On Linux and perhaps other systems, you can avoid the need to run the...
  • Page 436 Type boolean Default FALSE Enable old-style user limits. (Before MySQL 5.0.3, account resource limits were counted separately for each host from which a user connected rather than per account row in the table.) See user Section 6.3.4, “Setting Account Resource Limits”.
  • Page 437 Server Command Options Option-File Format one-thread Only use one thread (for debugging under Linux). This option is available only if the server is built with debugging enabled. See MySQL Internals: Porting to Other Systems. • [417] --open-files-limit=count Command-Line Format --open-files-limit=#...
  • Page 438 If the server is restarted quickly afterward, its attempt to reopen the port can fail. This option indicates how many seconds the server should wait for the TCP/IP port to become free if it cannot be opened. The default is not to wait. This option was added in MySQL 5.0.19. •...
  • Page 439 Option-File Format safe-user-create Permitted Values Type boolean Default FALSE If this option is enabled, a user cannot create new MySQL users by using the statement GRANT unless the user has the [577] privilege for the table or any column in the INSERT mysql.user...
  • Page 440 • [420] --skip-merge Disable the storage engine. This option was added in MySQL 5.0.24. It can be used if the MERGE following behavior is undesirable: If a user has access to table t, that user can create a MyISAM table that accesses t.
  • Page 441 Options”. • [421] --standalone Command-Line Format --standalone Option-File Format standalone Platform Specific windows Instructs the MySQL server not to run as a service. • [421], [421] --symbolic-links --skip-symbolic-links Command-Line Format --symbolic-links Option-File Format symbolic-links Enable or disable symbolic link support. This option has different effects on Windows and Unix: •...
  • Page 442 On Unix, this option specifies the Unix socket file to use when listening for local connections. The default value is /tmp/mysql.sock. If this option is given, the server creates the file in the data directory unless an absolute path name is given to specify a different directory. On Windows, the option specifies the pipe name to use when listening for local connections that use a named pipe.
  • Page 443 [928] Section 12.7, “Date and Time Functions” and for SYSDATE() SET TIMESTAMP Section 5.1.4, “Server System Variables”. This option was added in MySQL 5.0.20. • [423] --tc-heuristic-recover={COMMIT|ROLLBACK} Version Introduced 5.0.3 Command-Line Format --tc-heuristic-recover=name...
  • Page 444 Permitted Values Type string Run the server as the user having the name or the numeric user ID user_id. mysqld user_name (“User” in this context refers to a system login account, not a MySQL user listed in the grant tables.)
  • Page 445: Server System Variables

    32MB. key_buffer_size Note that when you assign a value to a variable, MySQL might automatically correct the value to stay within a given range, or adjust the value to the closest permissible value if only certain values are permitted.
  • Page 446 SHOW VARIABLES This section provides a description of each system variable. Variables with no version indicated are present in all MySQL 5.0 releases. For historical information concerning their implementation, please see http://www.mysql.com/products/enterprise//4.1/en/. The following table lists all available system variables.
  • Page 447 Server System Variables Name Cmd-Line Option file System Var Var Scope Dynamic character_set_database [442] Both character-set- filesystem [403] - Variable: Both character_set_filesystem character_set_results [443] Both character-set- server [403] - Variable: Both character_set_server character_set_system [443] Global character-sets- dir [402] - Variable: Global character_sets_dir collation_connection [443]...
  • Page 448 Server System Variables Name Cmd-Line Option file System Var Var Scope Dynamic flush [450] Global flush_time [451] Global foreign_key_checks [451] Session ft_boolean_syntax [451] Global ft_max_word_len [452] Global ft_min_word_len [452] Y es Global ft_query_expansion_limit [453] Global ft_stopword_file [453] Global group_concat_max_len [453] Both have_archive [454] Global...
  • Page 449 Server System Variables Name Cmd-Line Option file System Var Var Scope Dynamic innodb_checksums [1238] Global innodb_commit_concurrency [1239] Global innodb_concurrency_tickets [1239] Global innodb_data_file_path [1240] Global innodb_data_home_dir [1240] Global innodb_doublewrite [1240] Global innodb_fast_shutdown [1241] Global innodb_file_io_threads [1241] Global innodb_file_per_table [1241] Global innodb_flush_log_at_trx_commit [1242] Global innodb_flush_method [1243] Global...
  • Page 450 Server System Variables Name Cmd-Line Option file System Var Var Scope Dynamic large_page_size [461] Global large-pages [410] - Variable: Global large_pages last_insert_id [462] Session lc_time_names [462] Both license [462] Global local_infile [462] Global locked_in_memory [463] Global log [411] Global log_bin [1471] Global log-bin [1467] Global...
  • Page 451 Server System Variables Name Cmd-Line Option file System Var Var Scope Dynamic lower_case_file_system [465] Global lower_case_table_names [466] Global max_allowed_packet [466] Global max_binlog_cache_size [1471] Global max_binlog_size [1472] Global max_connect_errors [467] Global max_connections [467] Global max_delayed_threads [468] Both max_error_count [468] Both max_heap_table_size [468] Both max_insert_delayed_threads [469] Both...
  • Page 452 Server System Variables Name Cmd-Line Option file System Var Var Scope Dynamic old_passwords [480] Both open-files- limit [417] - Variable: Global open_files_limit optimizer_prune_level [480] Both optimizer_search_depth [481] Both pid-file [417] - Variable: pid_file Global plugin_dir [481] Global port [417] Global preload_buffer_size [482] Both prepared_stmt_count [482]...
  • Page 453 Server System Variables Name Cmd-Line Option file System Var Var Scope Dynamic - Variable: Global report_host report- password [1460] - Variable: Global report_password report-port [1461] - Variable: Global report_port report-user [1461] - Variable: Global report_user rpl_recovery_rank [1465] Global safe-show- Global database [418] secure-auth [419] - Variable:...
  • Page 454 Server System Variables Name Cmd-Line Option file System Var Var Scope Dynamic slave-load- tmpdir [1462] - Variable: Global slave_load_tmpdir slave-net- timeout [1462] - Variable: Global slave_net_timeout slave-skip- errors [1463] - Variable: Global slave_skip_errors slave_transaction_retries [1466] Global slow_launch_time [492] Global socket [422] Global sort_buffer_size [493]Yes...
  • Page 455 Server System Variables Name Cmd-Line Option file System Var Var Scope Dynamic ssl-key [608] - Variable: ssl_key Global storage_engine [497] Both sync-bdb- logs [1310] - Variable: Global sync_bdb_logs sync_binlog [1472] Global sync_frm [497] Global system_time_zone [498] Global table_cache [498] Global table_lock_wait_timeout [498] Global table_type [497]...
  • Page 456 Suppose that the data directory is /var/mysql/data. If a file-valued variable is given as a relative path name, it will be located under /var/mysql/data. If the value is an absolute path name, its location is as given by the path name.
  • Page 457 The number of outstanding connection requests MySQL can have. This comes into play when the main MySQL thread gets very many connection requests in a very short time. It then takes some time (although very little) for the main thread to check the connection and start a new thread. The...
  • Page 458 Variable Scope Global Dynamic Variable Permitted Values Type file name The MySQL installation base directory. This variable can be set with the [401] option. --basedir Relative path names for other variables usually are resolved relative to the base directory. •...
  • Page 459 Server System Variables Variable Scope Global Dynamic Variable Permitted Values Type numeric Range 262144 .. 4294967295 The size of the buffer that is allocated for caching indexes and rows for tables. If you do not tables, you should set this to 0 or start with [420] to not allocate...
  • Page 460 Server System Variables Dynamic Variable This is if you are using [1310] to start Berkeley DB in multi-process --bdb-shared-data mode. (Do not use when initializing Berkeley DB.) DB_PRIVATE • [440] bdb_tmpdir Command-Line Format --bdb-tmpdir=path Option-File Format bdb-tmpdir=path Option Sets Variable Yes, [440] bdb_tmpdir...
  • Page 461 • The client is from a version of MySQL older than MySQL 4.1, and thus does not request a character set.
  • Page 462 --skip-character-set-client-handshake which causes it to ignore client character set configuration. This reproduces MySQL 4.0 behavior and is useful should you wish to upgrade the server without upgrading all the clients. cannot be used as a client character set, which means that it also does not work for...
  • Page 463 For systems on which multi-byte file names are permitted, a different value may be more appropriate. For example, if the system represents file names using UTF-8, set [442] to 'utf8'. This variable was added in MySQL 5.0.19. character_set_filesystem •...
  • Page 464 Server System Variables Variable Name collation_connection Variable Scope Global, Session Dynamic Variable Permitted Values Type string The collation of the connection character set. • [444] collation_database Variable Name collation_database Variable Scope Global, Session Dynamic Variable Footnote This option is dynamic, but only the server should set this information. You should not set the value of this variable manually.
  • Page 465 For a MyISAM table with a hole, new rows are inserted at the end of the table if it is in use by another thread. Otherwise, MySQL acquires a normal write lock and inserts the row into the hole. See also Section 8.7.3, “Concurrent...
  • Page 466 The number of seconds that the server waits for a connect packet before responding with mysqld handshake. The default value is 10 seconds as of MySQL 5.0.52 and 5 seconds before that. Increasing the [445] value might help if clients frequently encounter errors of...
  • Page 467 DELAY_KEY_WRITE CREATE TABLE Option Description is ignored. DELAY_KEY_WRITE MySQL honors any option specified in DELAY_KEY_WRITE CREATE TABLE statements. This is the default value. All new opened tables are treated as if they were created with the DELAY_KEY_WRITE option enabled.
  • Page 468 Server System Variables Type numeric Default Range 1 .. 4294967295 Permitted Values Platform Bit Size Type numeric Default Range 1 .. 18446744073709547520 After inserting [447] delayed rows, the handler delayed_insert_limit INSERT DELAYED thread checks whether there are any statements pending. If so, it permits them to execute SELECT before continuing to insert delayed rows.
  • Page 469 | 0.1429 | +--------+ mysql> SET div_precision_increment = 12; mysql> SELECT 1/7; +----------------+ | 1/7 +----------------+ | 0.142857142857 | +----------------+ This variable was added in MySQL 5.0.6. • [449] engine_condition_pushdown Version Introduced 5.0.3 Command-Line Format --engine-condition-pushdown Option-File Format engine-condition-pushdown Option Sets Variable...
  • Page 470 Engine condition pushdown is used only by the storage engine. Enabling this NDBCLUSTER optimization on a MySQL Server acting as a MySQL Cluster SQL node causes conditions WHERE on unindexed columns to be evaluated on the cluster's data nodes and only the rows that match to be sent back to the SQL node that issued the query.
  • Page 471 If ON, the server flushes (synchronizes) all changes to disk after each SQL statement. Normally, MySQL does a write of all changes to disk only after each SQL statement and lets the operating system handle the synchronizing to disk. See Section C.5.4.2, “What to Do If MySQL Keeps...
  • Page 472 Server System Variables Default +-><()~*:""& The list of operators supported by boolean full-text searches performed using IN BOOLEAN MODE. Section 12.9.2, “Boolean Full-Text Searches”. The default variable value is -><()~*:""&|'. The rules for changing the value are as follows: • Operator function is determined by position within the string. •...
  • Page 473 Server System Variables Value The minimum length of the word to be included in a index. FULLTEXT Note indexes must be rebuilt after changing this variable. Use FULLTEXT REPAIR TABLE tbl_name QUICK. • [453] ft_query_expansion_limit Command-Line Format --ft_query_expansion_limit=# Option-File Format ft_query_expansion_limit Option Sets Variable Yes,...
  • Page 474 See Section 13.7.5.29, “SHOW PROFILES Syntax”. This variable was added in MySQL 5.0.82. • [454] have_compress if the compression library is available to the server, if not. If not, the...
  • Page 475 [1236] is used. mysqld InnoDB DISABLED --skip-innodb • [455] have_isam In MySQL 5.0, this variable appears only for reasons of backward compatibility. It is always because tables are no longer supported. ISAM • [455] have_merge_engine supports tables. [420] is used. This variable...
  • Page 476 Variable Scope Global Dynamic Variable Permitted Values Type string The server sets this variable to the server host name at startup. This variable was added in MySQL 5.0.38. • [456] identity This variable is a synonym for the [462] variable.
  • Page 477 No statement terminator such as ;, \g, or should be given at the end of each statement. Note that the [409] option is unavailable if MySQL was configured with the --init-file [123] option. See Section 2.17.3, “MySQL Source-Configuration disable-grant-options Options”.
  • Page 478 MyISAM DATA DIRECTORY INDEX DIRECTORY file is found, MyISAM always returns an error. It will not overwrite a file in the specified .MYD .MYI directory. This variable was added in MySQL 5.0.48. • [458] key_buffer_size Command-Line Format --key_buffer_size=# Option-File Format...
  • Page 479 (for example, more than 50% of the machine's total memory), your system might start to page and become extremely slow. This is because MySQL relies on the operating system to perform file system caching for data reads, so you must leave some room for the file system cache.
  • Page 480 Server System Variables Type numeric Default Range 100 .. 4294967295 Permitted Values Platform Bit Size Type numeric Default Range 100 .. 18446744073709547520 This value controls the demotion of buffers from the hot sublist of a key cache to the warm sublist. Lower values cause demotion to happen more quickly.
  • Page 481 FALSE Whether large page support is enabled (via the [410] option). See Section 8.9.7, --large-pages “Enabling Large Page Support”. This variable was added in MySQL 5.0.3. For more information, see the entry for the [410] server option [410]. --large-pages •...
  • Page 482 If large page support is enabled, this shows the size of memory pages. Currently, large memory pages are supported only on Linux; on other platforms, the value of this variable is always 0. This variable was added in MySQL 5.0.3. For more information, see...
  • Page 483 If the DETERMINISTIC READS SQL DATA NO SQL variable is set to 1, MySQL does not enforce these restrictions on stored function creation. This variable also applies to trigger creation. See Section 18.6, “Binary Logging of Stored Programs”. This variable was added in MySQL 5.0.16.
  • Page 484 Permitted Values Type boolean Default Whether queries that do not use indexes are logged to the slow query log. See Section 5.2.4, “The Slow Query Log”. This variable was added in MySQL 5.0.23. • [464] log_slow_queries Command-Line Format --log-slow-queries[=name] Option-File Format...
  • Page 485 Server System Variables Permitted Values Platform Bit Size Type numeric Default Range 0 .. 18446744073709547520 Whether to produce additional warning messages. It is enabled (1) by default and can be disabled by setting it to 0. Aborted connections are not logged to the error log unless the value is greater than 1. •...
  • Page 486 Sensitivity”. You should not set this variable to 0 if you are running MySQL on a system that has case-insensitive file names (such as Windows or Mac OS X). If you set this variable to 0 on such a system and access tablenames using different lettercases, index corruption may result.
  • Page 487 [466] on the command line or in an option file. max_allowed_packet As of MySQL 5.0.84, the session value of this variable is read only. Before 5.0.84, setting the session value is permitted but has no effect. • [467] max_connect_errors...
  • Page 488 INSERT DELAYED attribute was not specified. If you set this to 0, MySQL never creates a thread to handle DELAYED rows; in effect, this disables entirely.
  • Page 489 This variable is also used in conjunction with [501] to limit the size of internal in- tmp_table_size memory tables. See Section 8.8.5, “How MySQL Uses Internal Temporary Tables”. is not replicated. See Section 16.4.1.14, “Replication and Tables”, max_heap_table_size MEMORY Section 16.4.1.28, “Replication and...
  • Page 490 The default value is 16,382. The permissible range of values is from 0 to 1 million. Setting the value to 0 disables prepared statements. This variable was added in MySQL 5.0.21. • [470]...
  • Page 491 Range 1 .. 18446744073709547520 Limit the assumed maximum number of seeks when looking up rows based on a key. The MySQL optimizer assumes that no more than this number of key seeks are required when searching for matching rows in a table by scanning an index, regardless of the actual cardinality of the index (see Section 13.7.5.18,...
  • Page 492 Stored procedure recursion increases the demand on thread stack space. If you increase the value [472], it may be necessary to increase thread stack size by max_sp_recursion_depth increasing the value of [500] at server startup. thread_stack This variable was added in MySQL 5.0.17. • [472] max_tmp_tables This variable is unused. • [472]...
  • Page 493 0 (the default) means “no limit.” Before MySQL 5.0.3, this variable has only a global value that can be set at server startup or runtime. As of MySQL 5.0.3, it also has a read-only session value that indicates the effective simultaneous-connection limit that applies to the account associated with the current session.
  • Page 494 Permitted Values Platform Bit Size Type numeric Default 9223372036854775807 The maximum size of the temporary file that MySQL is permitted to use while re-creating a MyISAM index (during TABLE, or INFILE). If the file size would be REPAIR TABLE, ALTER LOAD DATA larger than this value, the index is created using the key cache instead, which is slower.
  • Page 495 The maximum amount of memory to use for memory mapping compressed files. If many MyISAM compressed tables are used, the value can be decreased to reduce the likelihood of MyISAM memory-swapping problems. This variable was added in MySQL 5.0.90. • [475] myisam_recover_options Variable Name myisam_recover_options...
  • Page 496 Server System Variables Permitted Values Platform Bit Size Type numeric Default Range 1 .. 18446744073709547520 If this value is greater than 1, table indexes are created in parallel (each index in its own MyISAM thread) during the process. The default value is 1. Repair by sorting Note Multi-threaded repair is still beta-quality code.
  • Page 497 Index Statistics Collection”. Any unique prefix of a valid value may be used to set the value of this variable. This variable was added in MySQL 5.0.14. For older versions, the statistics collection method is equivalent to nulls_equal. • [477]...
  • Page 498 The maximum value to which [477] can be set is net_buffer_length 1MB. As of MySQL 5.0.84, the session value of this variable is read only. Before 5.0.84, setting the session value is permitted but has no effect. • [478] net_read_timeout...
  • Page 499 Server System Variables Platform Bit Size Type numeric Default Range 1 .. 18446744073709547520 If a read or write on a communication port is interrupted, retry this many times before giving up. This value should be set quite high on FreeBSD because internal interrupts are sent to all threads. On Linux, the build flag (-DNO_ALARM) modifies how the binary treats both NO_ALARM...
  • Page 500 PASSWORD. The value determines whether CREATE USER or not to use “old” native MySQL password hashing. A value of 0 (or OFF) causes passwords to be encrypted using the format available from MySQL 4.1 on. A value of 1 (or ON) causes password encryption to use the older pre-4.1 format.
  • Page 501 If set to 0, the system automatically picks a reasonable value. If set to 63, the optimizer switches to the algorithm used in MySQL 5.0.0 (and previous versions) for performing searches. This variable was added in MySQL 5.0.1.
  • Page 502 Server System Variables The path name of the plugin directory. This variable was added in MySQL 5.0.67. If the value is nonempty, user-defined function object files must be located in this directory. If the value is empty, the behavior that is used before 5.0.67 applies: The UDF object files must be located in a directory that is searched by your system's dynamic linker.
  • Page 503 The default value is 15. The maximum value is 100. Setting the value to 0 effectively disables profiling. See Section 13.7.5.29, “SHOW PROFILES Syntax”. This variable was added in MySQL 5.0.37. Note: This option does not apply to MySQL Enterprise Server users. • [483] protocol_version Variable Name...
  • Page 504 Server System Variables Default 8192 Range 1024 .. 4294967295 Block 1024 Size Permitted Values Platform Bit Size Type numeric Default 8192 Range 1024 .. 18446744073709547520 Block 1024 Size The allocation size of memory blocks that are allocated for objects created during statement parsing and execution.
  • Page 505 Server System Variables Dynamic Variable Permitted Values Platform Bit Size Type numeric Default 4096 Range 512 .. 4294967295 Permitted Values Platform Bit Size Type numeric Default 4096 Range 512 .. 18446744073709547520 The minimum size (in bytes) for blocks allocated by the query cache. The default value is 4096 (4KB).
  • Page 506 Server System Variables Option Description Do not cache results in or retrieve results from the query cache. Note that this does not deallocate the query cache buffer. To do that, you should set [485] to 0. query_cache_size Cache all cacheable query results except for those that begin with SELECT SQL_NO_CACHE.
  • Page 507 Server System Variables Platform Bit Size Type numeric Default 8192 Range 8192 .. 18446744073709547520 Block 1024 Size The size of the persistent buffer used for statement parsing and execution. This buffer is not freed between statements. If you are running complex queries, a larger [486] query_prealloc_size value might be helpful in improving performance, because it can reduce the need for the server to...
  • Page 508 [488] does not apply to tables as of MySQL 5.0.16. This variable does read_only TEMPORARY not prevent the use of statements because its purpose is...
  • Page 509 PASSWORD series. When replicating from one MySQL release series to another (for example, from a MySQL 5.0 master to a MySQL 5.1 slave), you should check the documentation for the versions running on both master and slave to determine whether the behavior of...
  • Page 510 Server System Variables Disables or enables automatic purging of relay log files as soon as they are not needed any more. The default value is 1 (ON). • [490] relay_log_space_limit Command-Line Format --relay_log_space_limit=# Option-File Format relay_log_space_limit Option Sets Variable Yes, [490] relay_log_space_limit Variable Name...
  • Page 511 Platform Specific windows (Windows only.) The name of shared memory to use for shared-memory connections. This is useful when running multiple MySQL instances on a single physical machine. The default name is MYSQL. The name is case sensitive. • [491]...
  • Page 512 Default /tmp/mysql.sock On Unix platforms, this variable is the name of the socket file that is used for local client connections. The default is /tmp/mysql.sock. (For some distribution formats, the directory might be different, such as for RPMs.) /var/lib/mysql...
  • Page 513 On Linux, there are thresholds of 256KB and 2MB where larger values may significantly slow down memory allocation, so you should consider staying below one of those values. Experiment to find the best value for your workload. See Section C.5.4.4, “Where MySQL Stores Temporary Files”.
  • Page 514 SELECT temporary tables. This helps MySQL free the table locks early and can be beneficial in cases where it takes a long time to send results to the client. The default value is 0. •...
  • Page 515 Server System Variables Dynamic Variable Deprecated 5.0, by sql_log_bin Permitted Values Type boolean This variable is deprecated, and is mapped to [494]. It is removed in MySQL 5.5. sql_log_bin • [495] sql_mode Command-Line Format --sql-mode=name Option-File Format sql-mode Option Sets Variable...
  • Page 516 Variable Name ssl-ca Variable Scope Global Dynamic Variable Permitted Values Type file name The path to a file with a list of trusted SSL CAs. This variable was added in MySQL 5.0.23. • [496] ssl_capath Version Introduced 5.0.23 Command-Line Format --ssl-capath=name...
  • Page 517 Variable Name ssl-cipher Variable Scope Global Dynamic Variable Permitted Values Type file name A list of permissible ciphers to use for SSL encryption. This variable was added in MySQL 5.0.23. • [497] ssl_key Version Introduced 5.0.23 Command-Line Format --ssl-key=name Option-File Format...
  • Page 518 [500]. Although they might system_time_zone time_zone have the same value, the latter variable is used to initialize the time zone for each client that connects. See Section 10.6, “MySQL Server Time Zone Support”. • [498] table_cache Command-Line Format...
  • Page 519 Type enumeration This variable is a synonym for [497]. In MySQL 5.0, [497] storage_engine storage_engine is the preferred name; [499] is deprecated and is removed in MySQL 5.5. table_type • [499] thread_cache_size Command-Line Format --thread_cache_size=# Option-File Format thread_cache_size Option Sets Variable...
  • Page 520 See Section 8.1.3, “The MySQL Benchmark Suite”. The default of 192KB (256KB for 64-bit systems) is large enough for normal operation. If the thread stack size is too small, it limits the complexity of the SQL statements that the server can handle, the recursion depth of stored procedures, and other memory-consuming actions.
  • Page 521 = {timestamp_value | DEFAULT} Set the time for this client. This is used to get the original timestamp if you use the binary log to restore rows. should be a Unix epoch timestamp, not a MySQL timestamp. timestamp_value affects the value returned by...
  • Page 522 (“:”) on Unix and semicolon characters (“;”) on Windows, NetWare, and OS/2. The multiple-directory feature can be used to spread the load between several physical disks. If the MySQL server is acting as a replication slave, you should not set [502]...
  • Page 523 Server System Variables Default 8192 Range 1024 .. 4294967295 Block 1024 Size Permitted Values Platform Bit Size Type numeric Default 8192 Range 1024 .. 18446744073709547520 Block 1024 Size The amount in bytes by which to increase a per-transaction memory pool which needs memory. See the description of [503].
  • Page 524 Server System Variables • [504] tx_isolation Variable Name tx_isolation Variable Scope Global, Session Dynamic Variable Permitted Values Type enumeration Default REPEATABLE-READ Valid READ-UNCOMMITTED Values READ-COMMITTED REPEATABLE-READ SERIALIZABLE The default transaction isolation level. Defaults to [1120]. REPEATABLE-READ This variable can be set directly, or indirectly using the statement.
  • Page 525 -debug Variable Name version Variable Scope Global Dynamic Variable Starting with MySQL 5.0.24, the version number will also indicate whether the server is a standard release (Community) or Enterprise release (for example, 5.0.28-enterprise-gpl-nt). • [505] version_bdb storage engine version. •...
  • Page 526 Enterprise users, the version might be displayed as (GPL). The MySQL Enterprise Server corresponding license for your MySQL binary is shown in parentheses. For server compiled from source, the default value will be the same as that for Community releases. •...
  • Page 527: Using System Variables

    Section 13.7.5.37, “SHOW WARNINGS Syntax”. 5.1.5. Using System Variables The MySQL server maintains many system variables that indicate how it is configured. Section 5.1.4, “Server System Variables”, describes the meaning of these variables. Each system variable has a default value. System variables can be set at server startup using options on the command line or in an option file.
  • Page 528 When you refer to a system variable in an expression as (that is, when you do not @@var_name specify or @@session.), MySQL returns the session value if it exists and the global value @@global. otherwise. (This differs from value, which always refers to the session value.)
  • Page 529 | innodb_commit_concurrency | innodb_concurrency_tickets | 500 | innodb_data_file_path | ibdata1:10M:autoextend | innodb_data_home_dir | version | 5.0.19 | version_comment | MySQL Community Edition - (GPL) | version_compile_machine | i686 | version_compile_os | pc-linux-gnu | wait_timeout | 28800 +--------+--------------------------------------------------------------+ With a [896] clause, the statement displays only those variables that match the pattern.
  • Page 530 • There might be several instances of a given type of structured variable. Each one has a different name and refers to a different resource maintained by the server. MySQL 5.0 supports one structured variable type, which specifies parameters governing the operation of key caches. A key cache structured variable has these components: •...
  • Page 531 Structured variable values may be set and retrieved at runtime as well. For example, to set a key cache named to a size of 10MB, use either of these statements: hot_cache mysql> SET GLOBAL hot_cache.key_buffer_size = 10*1024*1024; mysql> SET @@global.hot_cache.key_buffer_size = 10*1024*1024;...
  • Page 532 Using System Variables The following table shows the full list of all dynamic system variables. The last column indicates for each variable whether (or both) apply. The table also lists session options that GLOBAL SESSION can be set with the statement.
  • Page 533 Using System Variables Variable Name Variable Type Variable Scope [451] string ft_boolean_syntax GLOBAL [453] numeric group_concat_max_len GLOBAL SESSION [456] numeric identity SESSION [456] string init_connect GLOBAL [1464] string init_slave GLOBAL [1237] numeric innodb_autoextend_increment GLOBAL [1239] numeric innodb_commit_concurrency GLOBAL [1239] numeric innodb_concurrency_tickets GLOBAL [1241]...
  • Page 534 Using System Variables Variable Name Variable Type Variable Scope [468] numeric max_error_count GLOBAL SESSION [468] numeric max_heap_table_size GLOBAL SESSION [469] numeric max_insert_delayed_threads GLOBAL SESSION [469] numeric max_join_size GLOBAL SESSION [470] numeric max_length_for_sort_data GLOBAL SESSION [470] numeric max_prepared_stmt_count GLOBAL [470] numeric max_relay_log_size GLOBAL [471]...
  • Page 535 Using System Variables Variable Name Variable Type Variable Scope [486] numeric query_prealloc_size GLOBAL SESSION [487] numeric rand_seed1 SESSION [487] numeric rand_seed2 SESSION [487] numeric range_alloc_block_size GLOBAL SESSION [488] numeric read_buffer_size GLOBAL SESSION [488] boolean read_only GLOBAL [489] numeric read_rnd_buffer_size GLOBAL SESSION [489] boolean...
  • Page 536: Server Status Variables

    5.0.2 is to return session values, this is incompatible with previous versions. To issue a statement that will retrieve global status SHOW STATUS values for all versions of MySQL, write it like this: SHOW /*!50002 GLOBAL */ STATUS; Many status variables are reset to 0 by the statement.
  • Page 537 Server Status Variables Variable Name Variable Type Variable Scope [523] numeric Bytes_sent GLOBAL SESSION [523] numeric Com_admin_commands GLOBAL SESSION [523] numeric Com_alter_db GLOBAL SESSION [523] numeric Com_alter_event GLOBAL SESSION [523] numeric Com_alter_table GLOBAL SESSION [523] numeric Com_analyze GLOBAL SESSION [523] numeric Com_backup_table GLOBAL...
  • Page 538 Server Status Variables Variable Name Variable Type Variable Scope [523] numeric Com_lock_tables GLOBAL SESSION [523] numeric Com_optimize GLOBAL SESSION [523] numeric Com_preload_keys GLOBAL SESSION [523] numeric Com_prepare_sql GLOBAL SESSION [523] numeric Com_purge GLOBAL SESSION [523] numeric Com_purge_before_date GLOBAL SESSION [523] numeric Com_rename_table GLOBAL...
  • Page 539 Server Status Variables Variable Name Variable Type Variable Scope [523] numeric Com_show_plugins GLOBAL SESSION [523] numeric Com_show_privileges GLOBAL SESSION [523] numeric Com_show_processlist GLOBAL SESSION [523] numeric Com_show_slave_hosts GLOBAL SESSION [523] numeric Com_show_slave_status GLOBAL SESSION [523] numeric Com_show_status GLOBAL SESSION [523] numeric Com_show_storage_engines GLOBAL...
  • Page 540 Server Status Variables Variable Name Variable Type Variable Scope [525] numeric Handler_prepare GLOBAL SESSION [525] numeric Handler_read_first GLOBAL SESSION [525] numeric Handler_read_key GLOBAL SESSION [525] numeric Handler_read_next GLOBAL SESSION [525] numeric Handler_read_prev GLOBAL SESSION [525] numeric Handler_read_rnd GLOBAL SESSION [525] numeric Handler_read_rnd_next GLOBAL...
  • Page 541 Server Status Variables Variable Name Variable Type Variable Scope [528] numeric Innodb_os_log_written GLOBAL [528] numeric Innodb_page_size GLOBAL [528] numeric Innodb_pages_created GLOBAL [528] numeric Innodb_pages_read GLOBAL [528] numeric Innodb_pages_written GLOBAL [528] numeric Innodb_row_lock_current_waits GLOBAL [528] numeric Innodb_row_lock_time GLOBAL [528] numeric Innodb_row_lock_time_avg GLOBAL [528] numeric...
  • Page 542 Server Status Variables Variable Name Variable Type Variable Scope [530] numeric Queries GLOBAL SESSION [530] numeric Questions GLOBAL SESSION [531] string Rpl_status GLOBAL [531] numeric Select_full_join GLOBAL SESSION [531] numeric Select_full_range_join GLOBAL SESSION [531] numeric Select_range GLOBAL SESSION [531] numeric Select_range_check GLOBAL SESSION...
  • Page 543 Uptime GLOBAL [534] numeric Uptime_since_flush_status GLOBAL The status variables have the following meanings. For meanings of status variables specific to MySQL Cluster, see Section 17.3.4.4, “MySQL Cluster Status Variables”. • [523] Aborted_clients The number of connections that were aborted because the client died without closing the connection properly.
  • Page 544 The number of internal on-disk temporary tables created by the server while executing statements. If an internal temporary table is created initially as an in-memory table but becomes too large, MySQL automatically converts it to an on-disk table. The maximum size for in-memory temporary tables is the minimum of the...
  • Page 545 The number of requests to read a row based on a fixed position. This value is high if you are doing a lot of queries that require sorting of the result. You probably have a lot of queries that require MySQL to scan entire tables or you have joins that do not use keys properly.
  • Page 546 The number of requests for a storage engine to place a savepoint. Added in MySQL 5.0.3. • [526] Handler_savepoint_rollback The number of requests for a storage engine to roll back to a savepoint. Added in MySQL 5.0.3. • [526] Handler_update The number of requests to update a row in a table.
  • Page 547 [527] Innodb_data_written The amount of data written so far, in bytes. Added in MySQL 5.0.2. • [527] Innodb_dblwr_pages_written The number of pages that have been written for doublewrite operations. Added in MySQL 5.0.2. See Section 14.2.10.1, “InnoDB Disk I/O”. •...
  • Page 548 The maximum time to acquire a row lock, in milliseconds. Added in MySQL 5.0.3. • [528] Innodb_row_lock_waits The number of times a row lock had to be waited for. Added in MySQL 5.0.3. • [528] Innodb_rows_deleted The number of rows deleted from tables.
  • Page 549 The default value of 0 means that no query has been compiled yet. This variable was added in MySQL 5.0.1, with a default value of -1. In MySQL 5.0.7, the default was changed to 0; also in version 5.0.7, the scope of [529] was changed to session rather than global.
  • Page 550 • [530] Prepared_stmt_count The current number of prepared statements. (The maximum number of statements is given by the [470] system variable.) This variable was added in MySQL 5.0.32. max_prepared_stmt_count • [530] Qcache_free_blocks The number of free memory blocks in the query cache.
  • Page 551 Server Status Variables The number of statements executed by the server. As of MySQL 5.0.72, this includes only statements sent to the server by clients and no longer includes statements executed within stored programs, unlike the variable. This variable does not count COM_PING, COM_STATISTICS,...
  • Page 552 Server Status Variables • [532] Sort_range The number of sorts that were done using ranges. • [532] Sort_rows The number of sorted rows. • [532] Sort_scan The number of sorts that were done by scanning the table. • [532] Ssl_accept_renegotiates The number of negotiates needed to establish the connection.
  • Page 553 Currently, this variable is unused: It is unneeded for binary log-based log-tc-size recovery, and the memory-mapped recovery log method is not used unless the number of storage engines capable of two-phase commit is greater than one. (InnoDB is the only applicable engine.) Added in MySQL 5.0.3. • [533] Tc_log_page_size...
  • Page 554: Server Sql Modes

    5.0.35. (MySQL Community only) 5.1.7. Server SQL Modes The MySQL server can operate in different SQL modes, and can apply these modes differently for different clients. This capability enables each application to tailor the server's operating mode to its own requirements.
  • Page 555 If a value could not be inserted as given into a transactional table, abort the statement. For a nontransactional table, abort the statement if the value occurs in a single-row statement or the first row of a multiple-row statement. More detail is given later in this section. (Implemented in MySQL 5.0.2) •...
  • Page 556 For IGNORE, MySQL generates a warning for INSERT IGNORE UPDATE divisions by zero, but the result of the operation is NULL. (Implemented in MySQL 5.0.2) • [536] HIGH_NOT_PRECEDENCE From MySQL 5.0.2 on, the precedence of the...
  • Page 557 Server SQL Modes • [537] NO_BACKSLASH_ESCAPES Disable the use of the backslash character (“\”) as an escape character within strings. With this mode enabled, backslash becomes an ordinary character like any other. (Implemented in MySQL 5.0.1) • [537] NO_DIR_IN_CREATE When creating a table, ignore all directives.
  • Page 558 (Added in MySQL 5.0.2) • [538] ONLY_FULL_GROUP_BY Do not permit queries for which the select list or (as of MySQL 5.0.23) list refers to HAVING nonaggregated columns that are not named in the clause.
  • Page 559 [539], MySQL converts an invalid value to the closest valid value STRICT_TRANS_TABLES for the column and insert the adjusted value. If a value is missing, MySQL inserts the implicit default value for the column data type. In either case, MySQL generates a warning rather than an error and continues processing the statement.
  • Page 560 Server SQL Modes The descriptions include all mode values that are available in the most recent version of MySQL. For older versions, a combination mode does not include individual mode values that are not available except in newer versions. •...
  • Page 561: Server-Side Help

    If you install MySQL using a binary or source distribution on Unix, help table setup occurs when you run mysql_install_db. For an RPM distribution on Linux or binary distribution on Windows, help table setup occurs as part of the MySQL installation process.
  • Page 562: The Shutdown Process

    In MySQL 5.0.80 and earlier, if the SQL thread was in the middle of a transaction at this point, the transaction was rolled back; in MySQL 5.0.81 and later, the server waits until the current replication event group (if any) has finished executing, or until the user issues a statement.
  • Page 563: Mysql Server Logs

    6. The server exits. 5.2. MySQL Server Logs MySQL Server has several logs that can help you find out what activity is taking place. Log Type Information Written to Log Error log...
  • Page 564: The General Query Log

    Note messages (such as information statements from individual storage engines) are not copied to the Event Log. The log entries have a source of MySQL. You cannot disable writing information to the Windows Event Log. If you flush the logs using...
  • Page 565: The Binary Log

    On Windows, you cannot rename a log file while the server has it open before MySQL 5.0.17. You must stop the server, rename the file, and then restart the server to create a new log file. As of 5.0.17, this applies only to the error log.
  • Page 566 The Binary Log [1467] options was treated as absolute rather than relative. The previous behaviors were restored in MySQL 5.0.54. (See Bug #28603 and Bug #28597.) If you supply an extension in the log name (for example, --log- [1467]), the extension is silently removed and ignored.
  • Page 567 INSERT ... ON DUPLICATE KEY UPDATE statement that encountered a duplicate key constraint—but did not actually change any data—was not logged. Beginning with MySQL 5.0.54, both of these statements are written to the binary log. (Bug #23333) Within an uncommitted transaction, all updates (UPDATE, DELETE, or INSERT) that change...
  • Page 568: The Slow Query Log

    The effect sync_binlog=1 of this option is that at restart after a crash, after doing a rollback of transactions, the MySQL server cuts rolled back transactions from the binary log. This ensures that the binary log reflects the...
  • Page 569: Server Log Maintenance

    When using MySQL with logging enabled, you may want to back up and remove old log files from time to time and tell MySQL to start logging to new files. See Section 7.2, “Database Backup...
  • Page 570: Running Multiple Mysql Instances On One Machine

    (For example, you might be an Internet Service Provider that wants to provide independent MySQL installations for different customers.) It is possible to use a different MySQL server binary per instance, or use the same binary for multiple instances, or any combination of the two approaches. For example, you might run a server from MySQL 4.1 and one from MySQL 5.0, to see how different versions handle a given workload.
  • Page 571 --bdb-tmpdir=path Having different temporary directories also makes it easier to determine which MySQL server created any given temporary file. If you have multiple MySQL installations in different locations, you can specify the base directory for each installation with the [401] option.
  • Page 572: Setting Up Multiple Data Directories

    100% reliably in every situation. Create a New Data Directory With this method, the data directory will be in the same state as when you first install MySQL. It will have the default set of MySQL accounts and no user data.
  • Page 573: Running Multiple Mysql Instances On Windows

    You can run multiple servers on Windows by starting them manually from the command line, each with appropriate operating parameters, or by installing several servers as Windows services and running them that way. General instructions for running MySQL from the command line or as a service are given in Section 2.10, “Installing MySQL on Microsoft...
  • Page 574 Windows Service”. To set up multiple MySQL services, you must make sure that each instance uses a different service name in addition to the other parameters that must be unique per instance. For the following instructions, suppose that you want to run the...
  • Page 575: Running Multiple Mysql Instances On Unix

    MySQL installation is located. If you have a MySQL server listening on a given port number, you can use the following command to find out what operating parameters it is using for several important configurable variables, including the...
  • Page 576: Using Client Programs In A Multiple-Server Environment

    You need not compile a new MySQL server just to start with a different Unix socket file and TCP/IP port number. It is also possible to use the same server binary and start each invocation of it with different parameter values at runtime.
  • Page 577 You can also have the program read option files by calling mysql_real_connect() mysql_options(). See Section 20.6.6, “C API Function Descriptions”. • If you are using the Perl module, you can read options from MySQL option files. For DBD::mysql example: $dsn = "DBI:mysql:test;mysql_read_default_group=client;" . "mysql_read_default_file=/usr/local/mysql/data/my.cnf"; $dbh = DBI->connect($dsn, $user, $password);...
  • Page 579: Security

    • Network security of MySQL and your system. The security is related to the grants for individual users, but you may also wish to restrict MySQL so that it is available only locally on the MySQL server host, or to a limited set of other hosts.
  • Page 580: Security Guidelines

    MySQL behind the firewall or in a demilitarized zone (DMZ). Checklist: • Try to scan your ports from the Internet using a tool such as nmap. MySQL uses port 3306 by default. This port should not be accessible from untrusted hosts. As a simple way to check...
  • Page 581: Keeping Passwords Secure

    MySQL users should use the following guidelines to keep passwords secure. When you run a client program to connect to the MySQL server, 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 here, along with an assessment of the risks of each method.
  • Page 582 Section 2.21, “Environment MYSQL_PWD Variables”. This method of specifying your MySQL password must be considered extremely insecure and should not be used. Some versions of include an option to display the environment of running processes. On some systems, if you set MYSQL_PWD, your password is exposed to any other user who runs ps.
  • Page 583 If these statements are logged PASSWORD() by the MySQL server as written, such passwords become available to anyone with access to the logs. This applies to the general query log, the slow query log, and the binary log (see Section 5.2, “MySQL...
  • Page 584 • Control over the permitted hashing methods for clients attempting to connect to the server The changes in MySQL 4.1 took place in two stages: • MySQL 4.1.0 used a preliminary version of the 4.1 hashing method. Because this method was so short lived, the following discussion says no more about it.
  • Page 585 41 bytes long Password automatically. • Upgrades from MySQL 4.1 or later to current versions of MySQL should not give rise to any issues in regard to the column because both versions use the same column length and password Password hashing method.
  • Page 586 [956] function or a password-generating statement. This is the behavior PASSWORD() that occurs if you have upgraded from a version of MySQL older than 4.1 to 4.1 or later but have not yet run the program to widen the column.
  • Page 587 Password generates only short password hashes anyway. This scenario occurs when a pre-4.1 MySQL installation has been upgraded to 4.1 or later but has not been run to upgrade the system tables in the database. (This is not a...
  • Page 588 But some applications use [956] for their own purposes anyway. PASSWORD() If you upgrade to 4.1 or later from a pre-4.1 version of MySQL and run the server under conditions where it generates long password hashes, an application using [956] for its own PASSWORD() passwords breaks.
  • Page 589: Making Mysql Secure Against Attackers

    API”. 6.1.3. Making MySQL Secure Against Attackers When you connect to a MySQL server, you should use a password. The password is not transmitted in clear text over the connection. Password handling during the client connection sequence was upgraded in MySQL 4.1.1 to be very secure. If you are still using pre-4.1.1-style passwords, the encryption algorithm is not as strong as the newer algorithm.
  • Page 590: Security-Related Mysqld Options And Variables

    [578] privilege, so that a mysqld SUPER MySQL user can log in and check server activity even if all normal connections are in use. root [578] privilege can be used to terminate client connections, change server operation by SUPER changing the value of system variables, and control replication servers.
  • Page 591: How To Run Mysql As A Normal User

    -R user_name /path/to/mysql/datadir If you do not do this, the server will not be able to access databases or tables when it runs as user_name. If directories or files within the MySQL data directory are symbolic links, might not chown -R follow symbolic links for you.
  • Page 592: Security Issues With Load Data Local

    LOAD DATA • The transfer of the file from the client host to the server host is initiated by the MySQL server. In theory, a patched server could be built that would tell the client program to transfer a file of the server's choosing rather than the file named by the client in the statement.
  • Page 593: Client Programming Security Guidelines

    Client Programming Security Guidelines 6.1.7. Client Programming Security Guidelines Applications that access MySQL should not trust any data entered by users, who can try to trick your code by entering special or escaped character sequences in Web forms, URLs, or whatever application you have built.
  • Page 594: The Mysql Access Privilege System

    The MySQL privilege system ensures that all users may perform only the operations permitted to them. As a user, when you connect to a MySQL server, your identity is determined by the host from which you connect and the user name you specify. When you issue requests after connecting, the system grants privileges according to your identity and what you want to do.
  • Page 595: Privileges Provided By Mysql

    Section 6.2.2, “Privilege System Grant Tables”). procs_priv mysql The MySQL server reads the contents of these tables into memory when it starts and reloads them under the circumstances indicated in Section 6.2.6, “When Privilege Changes Take Effect”. Access- control decisions are based on the in-memory copies of the grant tables.
  • Page 596 USAGE The following list provides a general description of each privilege available in MySQL. Particular SQL statements might have more specific privilege requirements than indicated here. If so, the description for the statement in question provides the details.
  • Page 597 FILE also enables the user to create new files in any directory where the MySQL server has write access. This includes the server's data directory containing the files that implement the privilege tables. As a security measure, the server will not overwrite existing files.
  • Page 598 FILE • The [577] privilege can be abused to read into a database table any files that the MySQL FILE server can read on the server host. This includes all world-readable files and files in the server's data directory. The table can then be accessed using to transfer its contents to the client host.
  • Page 599: Privilege System Grant Tables

    However, a user with write access to the table user Password column can change an account's password, and then connect to the MySQL server using that account. 6.2.2. Privilege System Grant Tables Normally, you manipulate the contents of the grant tables in the...
  • Page 600 INSERT, host UPDATE, and DELETE. It is not affected by statements such as GRANT that modify the grant tables indirectly. Most MySQL installations need REVOKE not use this table at all. • The...
  • Page 601 Resource control columns max_questions max_updates max_connections max_user_connections was present in MySQL 5.0.0, but did not become operational until MySQL 5.0.3. Execute_priv columns were added in MySQL 5.0.1. Create_view_priv Show_view_priv The Create_routine_priv, Alter_routine_priv, and [472] max_user_connections columns were added in MySQL 5.0.3.
  • Page 602 Host User Routine_name Routine_type Privilege columns Proc_priv Other columns Timestamp Grantor table exists as of MySQL 5.0.3. The column was added in MySQL procs_priv Routine_type 5.0.6. It is an column with values of to indicate the type of ENUM 'FUNCTION' 'PROCEDURE' routine the row refers to.
  • Page 603: Specifying Account Names

    SHOW GRANTS FOR 'bob'@'pc84.example.com'; 6.2.3. Specifying Account Names MySQL account names consist of a user name and a host name. This enables creation of accounts for users with the same name who can connect from different hosts. This section describes how to write account names, including special values and wildcard rules.
  • Page 604 192.168.1.somewhere.com. To foil such attempts, MySQL disallows matching on host names that start with digits and a dot. Thus, if you have a host named something like 1.2.example.com, its name never matches the host part of account names.
  • Page 605: Access Control, Stage 1: Connection Verification

    Access Control, Stage 1: Connection Verification IP addresses that satisfy this condition and can connect to the MySQL server are those in the range from to 192.58.197.255. 192.58.197.0 The netmask can only be used to tell the server to use 8, 16, 24, or 32 bits of the address. Examples: •...
  • Page 606 Section 6.3.1, “User Names and Passwords”. From MySQL's point of view, the encrypted password is the real password, so you should never give anyone access to it. In particular, do not give nonadministrative users read access to tables in the database.
  • Page 607 User Host matching table row. Suppose that connects and issues the following query: user jeffrey mysql> SELECT CURRENT_USER(); +----------------+ | CURRENT_USER() | +----------------+ | @localhost +----------------+ The result shown here indicates that the matching table row had a blank column value.
  • Page 608: Access Control, Stage 2: Request Verification

    Access Control, Stage 2: Request Verification 6.2.5. Access Control, Stage 2: Request Verification After you establish a connection, the server enters Stage 2 of access control. For each request that you issue through that connection, the server determines what operation you want to perform, then checks whether you have sufficient privileges to do so.
  • Page 609 Host, Db, and columns. The User Host columns are matched to the connecting user's host name and MySQL user name. The User column is matched to the database that the user wants to access. If there is no row for the Host and User, access is denied.
  • Page 610: When Privilege Changes Take Effect

    6.2.7. Causes of Access-Denied Errors If you encounter problems when you try to connect to the MySQL server, the following items describe some courses of action you can take to correct the problem.
  • Page 611 TCP/IP connections only locally on the loopback interface and will not accept remote connections. • Check to make sure that there is no firewall blocking access to MySQL. Your firewall may be configured on the basis of the application being executed, or the port number used by MySQL for communication (3306 by default).
  • Page 612 MySQL user name. • If the following error occurs when you try to connect from a host other than the one on which the MySQL server is running, it means that there is no row in the table with a...
  • Page 613 • If you specify a host name when trying to connect, but get an error message where the host name is not shown or is an IP address, it means that the MySQL server got an error when trying to resolve the IP address of the client host to a name: shell>...
  • Page 614 • If your privileges seem to have changed in the middle of a session, it may be that a MySQL administrator has changed them. Reloading the grant tables affects new client connections, but it also affects existing connections as indicated in Section 6.2.6, “When Privilege Changes Take...
  • Page 615: Mysql User Account Management

    Other Systems. • If you have any other problems with the MySQL grant tables and feel you must post the problem to the mailing list, always provide a dump of the MySQL grant tables. You can dump the tables with command.
  • Page 616 MySQL built-in authentication. These passwords have nothing to do with passwords for logging in to your operating system. There is no necessary connection between the “external” password you use to log in to a Windows or Unix machine and the password you use to access the MySQL server on that machine.
  • Page 617: Adding User Accounts

    CREATE USER GRANT Section 13.7.1, “Account Management Statements”. Another option for creating accounts is to use the GUI tool MySQL Workbench. Or one of several available third-party programs that offer capabilities for MySQL account administration. phpMyAdmin one such program. The following examples show how to use the client program to set up new accounts.
  • Page 618 Host, User, and columns in INSERT dummy Password table row are assigned values. None of the privilege columns are set explicitly, so MySQL user assigns them all the default value of 'N'. This is equivalent to what does. CREATE USER If strict SQL mode is enabled, all columns that have no default value must have a value specified.
  • Page 619 To create the accounts with and GRANT, use the following statements: CREATE USER shell> mysql --user=root mysql mysql> CREATE USER 'custom'@'localhost' IDENTIFIED BY 'obscure'; mysql> GRANT SELECT,INSERT,UPDATE,DELETE,CREATE,DROP -> ON bankaccount.* ->...
  • Page 620: Removing User Accounts

    • The number of times an account can connect to the server per hour • The number of simultaneous connections to the server by an account (available as of MySQL 5.0.3) Any statement that a client can issue counts against the query limit (unless its results are served from the query cache).
  • Page 621 Section 4.4.9, “mysql_upgrade — Check Tables for MySQL Upgrade”. Resource-use counting takes place when any account has a nonzero limit placed on its use of any of the resources. As the server runs, it counts the number of times each account uses resources. If an account reaches its limit on number of connections within the last hour, further connections for the account are rejected until that hour is up.
  • Page 622: Assigning Account Passwords

    6.3.5. Assigning Account Passwords Required credentials for clients that connect to the MySQL server can include a password. This section describes how to assign passwords for MySQL accounts. To assign a password when you create a new account with...
  • Page 623: Using Ssl For Secure Connections

    Syntax”. GRANT The standard configuration of MySQL is intended to be as fast as possible, so encrypted connections are not used by default. For applications that require the security provided by encrypted connections, the extra computation to encrypt the data is worthwhile.
  • Page 624 To get secure connections to work with MySQL and SSL, you must do the following: 1. If you are not using a binary (precompiled) version of MySQL that has been built with SSL support, and you are going to use OpenSSL rather than the bundled yaSSL library, install OpenSSL if it has not already been installed.
  • Page 625 For a complete list of SSL options, see Section 6.3.6.4, “SSL Command Options”. To start the MySQL server so that it permits clients to connect using SSL, use the options that identify the certificate and key files the server uses when establishing a secure connection: •...
  • Page 626 Using SSL for Secure Connections To establish a secure connection to a MySQL server with SSL support, the options that a client must specify depend on the SSL requirements of the MySQL account used by the client. (See the discussion...
  • Page 627 SSL connections, an unencrypted connection is used. The secure way to require use of an SSL connection is to create a MySQL account that includes at least a clause in the statement.
  • Page 628 The path to a file in PEM format that contains a list of trusted SSL certificate authorities. This option implies [607]. --ssl As of MySQL 5.0.40, if you use SSL when establishing a client connection, you can tell the client not to authenticate the server certificate by specifying neither [608] --ssl-ca --ssl- [608].
  • Page 629 6.3.6.5. Setting Up SSL Certificates and Keys for MySQL This section demonstrates how to set up SSL certificate and key files for use by MySQL servers and clients. The first example shows a simplified procedure such as you might use from the command line.
  • Page 630 Example 2: Creating SSL Files Using a Script on Unix Here is an example script that shows how to set up SSL certificate and key files for MySQL. After executing the script, use the files to test SSL connections as described in Section 6.3.6.3, “Using SSL...
  • Page 631 # Country Name (2 letter code) [AU]:FI # State or Province Name (full name) [Some-State]:. # Locality Name (eg, city) []: # Organization Name (eg, company) [Internet Widgits Pty Ltd]:MySQL AB # Organizational Unit Name (eg, section) []: # Common Name (eg, YOUR name) []:MySQL server...
  • Page 632 Using SSL for Secure Connections # State or Province Name (full name) [Some-State]:. # Locality Name (eg, city) []: # Organization Name (eg, company) [Internet Widgits Pty Ltd]:MySQL AB # Organizational Unit Name (eg, section) []: # Common Name (eg, YOUR name) []:MySQL user...
  • Page 633 Using SSL for Secure Connections If a message occurs during setup indicating '...critical component is missing: Redistributables', cancel the setup and download one of the Microsoft Visual C++ 2008 following packages as well, again depending on your architecture (32-bit or 64-bit): •...
  • Page 634: Connecting To Mysql Remotely From Windows With Ssh

    5. Log in to your server with the SSH session you just created. 6. On your Windows machine, start some ODBC application (such as Access). 7. Create a new file in Windows and link to MySQL using the ODBC driver the same way you normally do, except type in for the MySQL host server, not yourmysqlservername.
  • Page 635 SQL-Based MySQL Account Activity Auditing wildcards, whereas account values (as returned by [959]) may contain user name CURRENT_USER() and host name wildcards. For example, a blank user name matches any user, so an account of enables ''@'localhost' clients to connect as an anonymous user from the local host with any user name. If this case, if a client...
  • Page 637: Backup And Recovery

    Backups are also essential as a safeguard before upgrading a MySQL installation, and they can be used to transfer a MySQL installation to another system or to set up replication slave servers. MySQL offers a variety of backup strategies from which you can choose the methods that best suit the requirements for your installation.
  • Page 638: Backup And Recovery Types

    Logical backup methods have these characteristics: • The backup is done by querying the MySQL server to obtain database structure and content information. • Backup is slower than physical methods because the server must access database information and convert it to logical format.
  • Page 639 • Backups are portable only to other machines that have identical or similar hardware characteristics. • Backups can be performed while the MySQL server is not running. If the server is running, it is necessary to perform appropriate locking so that the server does not change database contents during the backup.
  • Page 640: Database Backup Methods

    Full Versus Incremental Backups A full backup includes all data managed by a MySQL server at a given point in time. An incremental backup consists of the changes made to the data during a given time span (from one point in time to another).
  • Page 641 To create a text file containing a table's data, you can use SELECT * INTO OUTFILE 'file_name' tbl_name. The file is created on the MySQL server host, not the client host. For this statement, FROM the output file cannot already exist because permitting files to be overwritten constitutes a security risk.
  • Page 642: Example Backup And Recovery Strategy

    InnoDB automatic crash recovery. Assume also that the MySQL server is under load at the time of the crash. If it were not, no recovery would ever be needed. For cases of operating system crashes or power failures, we can assume that MySQL's disk data is available after a restart.
  • Page 643: Establishing A Backup Policy

    MySQL server should always be started with the --log- [1467] option to enable that log. With binary logging enabled, the server writes each data change into a file while it updates data. Looking at the data directory of a MySQL server that was started with...
  • Page 644 Let's modify the previous command mysqldump a bit so that it flushes the MySQL binary logs at the moment of the full backup, and so that the dump file contains the name of the new current binary log: shell>...
  • Page 645: Using Backups For Recovery

    We now have recovered the data to its state as of Tuesday 1 p.m., but still are missing the changes from that date to the date of the crash. To not lose them, we would have needed to have the MySQL server store its MySQL binary logs into a safe location (RAID disks, SAN, ...) different from the place...
  • Page 646: Dumping Data In Sql Format With Mysqldump

    The output can be saved in a file and INSERT reloaded later using to recreate the dumped objects. Options are available to modify the mysql format of the SQL statements, and to control which objects are dumped. • With [305], produces two output files for each dumped table.
  • Page 647: Reloading Sql-Format Backups

    Then specify the database name when you load the dump file: shell> mysql db1 < dump.sql Alternatively, from within mysql, create the database, select it as the default database, and load the dump file: mysql> CREATE DATABASE IF NOT EXISTS db1;...
  • Page 648: Reloading Delimited-Text Format Backups

    To reload a table, first change location into the output directory. Then process the file with .sql to create an empty table and process the file to load the data into the table: mysql .txt shell> mysql db1 < t1.sql shell> mysqlimport db1 t1.txt...
  • Page 649: Mysqldump Tips

    • How to dump definitions and data separately 7.4.5.1. Making a Copy of a Database shell> mysqldump db1 > dump.sql shell> mysqladmin create db2 shell> mysql db2 < dump.sql Do not use [299] on the command line because that causes --databases mysqldump...
  • Page 650 Test for Upgrade Incompatibilities mysqldump When contemplating a MySQL upgrade, it is prudent to install the newer version separately from your current production version. Then you can dump the database and database object definitions from the production server and load them into the new server to verify that they are handled properly. (This is also useful for testing downgrades.)
  • Page 651: Point-In-Time (Incremental) Recovery Using The Binary Log

    | mysql -u root -p • Viewing log contents can be useful when you need to determine event times or positions to select partial log contents prior to executing events. To view events from the log, send...
  • Page 652: Point-In-Time Recovery Using Event Times

    Point-in-Time Recovery Using Event Times If you have more than one binary log to execute on the MySQL server, the safe method is to process them all using a single connection to the server. Here is an example that demonstrates what may be unsafe: shell>...
  • Page 653: Myisam Table Maintenance And Crash Recovery

    SQL statement recorded, mysqlbinlog SET TIMESTAMP the recovered data and related MySQL logs will reflect the original times at which the transactions were executed. 7.6. Table Maintenance and Crash Recovery MyISAM This section discusses how to use...
  • Page 654: Using Myisamchk For Crash Recovery

    7.6.1. Using for Crash Recovery myisamchk This section describes how to check for and deal with data corruption in MySQL databases. If your tables become corrupted frequently, you should try to find the reason why. See Section C.5.4.2, “What to Do If MySQL Keeps Crashing”.
  • Page 655: How To Repair Myisam Tables

    MySQL error code 135 = No more room in record file MySQL error code 136 = No more room in index file MySQL error code 141 = Duplicate unique key or constraint on write or update MySQL error code 144 = Table is crashed and last repair failed...
  • Page 656 How to Repair Tables MyISAM If you do not know the current table option values, use SHOW CREATE TABLE. For the other errors, you must repair your tables. can usually detect and fix most problems myisamchk that occur. The repair process involves up to four stages, described here. Before you begin, you should change location to the database directory and check the permissions of the table files.
  • Page 657: Myisam Table Optimization

    In this case, it is necessary to create a new index file. Do so as follows: 1. Move the data file to a safe place. 2. Use the table description file to create new (empty) data and index files: shell> mysql db_name mysql> SET autocommit=1; mysql> TRUNCATE TABLE tbl_name;...
  • Page 658 -s 24 hours. As you see that problems occur infrequently, you can back off the checking frequency to once a week or so. Normally, MySQL tables need little maintenance. If you are performing many updates to tables MyISAM with dynamic-sized rows (tables with VARCHAR, BLOB, or...
  • Page 659 8.9. Optimizing the MySQL Server ..................... 718 8.9.1. System Factors and Startup Parameter Tuning ............718 8.9.2. Tuning Server Parameters ..................718 8.9.3. How MySQL Uses Threads for Client Connections ............ 723 8.9.4. How MySQL Uses Memory ..................724 8.9.5. Disk Issues ......................725 8.9.6.
  • Page 660: Optimization Overview

    • All columns have default values. • If you insert an inappropriate or out-of-range value into a column, MySQL sets the column to the “best possible value” instead of reporting an error. For numeric values, this is 0, the smallest possible value or the largest possible value.
  • Page 661: The Mysql Benchmark Suite

    If you use some feature that is specific to a given database system (such as the statement, REPLACE which is specific to MySQL), you should implement the same feature for other SQL servers by coding an alternative method. Although the alternative might be slower, it enables the other servers to perform the same tasks.
  • Page 662: Using Your Own Benchmarks

    • The benchmark scripts are written in Perl and use the Perl DBI module to access database servers, so DBI must be installed. You also need the server-specific DBD drivers for each of the servers you want to test. For example, to test MySQL, PostgreSQL, and DB2, you must have the DBD::mysql, DBD::Pg, and modules installed.
  • Page 663: Obtaining Query Execution Plan Information

    MySQL would read them while processing the statement. MySQL resolves all joins using a nested-loop join method. This means that MySQL reads a row from the first table, and then finds a matching row in the second table, the third table, and so on. When all tables are processed, MySQL outputs the selected columns and backtracks through the table list until a table is found for which there are more matching rows.
  • Page 664 Output Format EXPLAIN • Output Interpretation EXPLAIN Output Columns EXPLAIN This section describes the output columns produced by EXPLAIN. Later sections provide additional information about the columns. type Extra Each output row from provides information about one table. Each row contains the values EXPLAIN summarized in Table 8.1,...
  • Page 665 To see what indexes a table has, use SHOW INDEX FROM tbl_name. • column indicates the key (index) that MySQL actually decided to use. If MySQL decides to use one of the indexes to look up rows, that index is listed as the key value. possible_keys...
  • Page 666 • rows column indicates the number of rows MySQL believes it must examine to execute the rows query. tables, this number is an estimate, and may not always be exact.
  • Page 667 • [647] ref_or_null This join type is like [646], but with the addition that MySQL does an extra search for rows that contain values. This join type optimization is used most often in resolving subqueries. In the NULL following examples, MySQL can use a...
  • Page 668 Extra MySQL can use this join type when the query uses only columns that are part of a single index. • A full table scan is done for each combination of rows from the previous tables. This is normally not good if the table is the first table not marked [646], and usually very bad in all other cases.
  • Page 669 NULL, and does not scan through the rest of the rows in that have the same value. In other words, for each row in t1, MySQL needs to do only a single lookup in t2, regardless of how many rows actually match in t2. •...
  • Page 670 Section 8.3.1.4, “Index Merge Optimization”. • Using temporary To resolve the query, MySQL needs to create a temporary table to hold the result. This typically happens if the query contains clauses that list columns differently. GROUP BY ORDER BY •...
  • Page 671 × 2135 × 74 × 3872 = 45,268,558,720 rows. If the tables were bigger, you can only imagine how long it would take. One problem here is that MySQL can use indexes on columns more efficiently if they are declared as the same type and size. In this context,...
  • Page 672: Explain Explain Extended

    Fortunately, it is easy to tell MySQL to analyze the key distribution: mysql> ANALYZE TABLE tt; With the additional index information, the join is perfect and...
  • Page 673 SELECT possibly other notes about the optimization process. Here is an example: mysql> EXPLAIN EXTENDED -> SELECT t1.a, t1.a IN (SELECT t2.a FROM t2) FROM t1\G *************************** 1.
  • Page 674: Estimating Query Performance

    / 3 * 2 / (index_length + data_pointer_length)) + In MySQL, an index block is usually 1,024 bytes and the data pointer is usually four bytes. For a 500,000-row table with a key value length of three bytes (the size of MEDIUMINT), the formula indicates seeks.
  • Page 675 (For unique indexes, this is always 1.) MySQL uses this to decide which index to choose when you join two tables based on a nonconstant expression. You can check the result from the table analysis by using...
  • Page 676 I/O block size. • In some cases, MySQL can read rows from the index without even consulting the data file. If all columns used from the index are numeric, only the index tree is used to resolve the query.
  • Page 677 BETWEEN 'bar' AND 'foo'; Note that some nonconstant values may be converted to constants during the constant propagation phase. MySQL tries to extract range conditions from the clause for each of the possible indexes. WHERE During the extraction process, conditions that cannot be used for constructing the range condition are dropped, conditions that produce overlapping ranges are combined, and conditions that produce empty ranges are removed.
  • Page 678 In general (and as demonstrated by the preceding example), the condition used for a range scan is less restrictive than the clause. MySQL performs an additional check to filter out rows that WHERE satisfy the range condition but not the full clause.
  • Page 679 Optimizing Statements SELECT NULL 'xyz' NULL 'foo' 'abc' 'xyz' 'abc' 'aaa' The condition defines this interval: key_part1 = 1 (1,-inf,-inf) <= (key_part1,key_part2,key_part3) < (1,+inf,+inf) The interval covers the 4th, 5th, and 6th tuples in the preceding data set and can be used by the range access method.
  • Page 680 Note If you have upgraded from a previous version of MySQL, you should be aware that this type of join optimization is first introduced in MySQL 5.0, and represents a significant change in behavior with regard to indexes. (Formerly, MySQL was able to use at most only one index for each referenced table.)
  • Page 681 • If your query has a complex clause with deep AND [880]/OR [881] WHERE nesting and MySQL doesn't choose the optimal plan, try distributing terms using the following identity laws: AND y) OR OR z) AND OR z) OR y) AND...
  • Page 682 For MySQL Cluster, this optimization can eliminate the need to send nonmatching rows over the network between the cluster's data nodes and the MySQL Server that issued the query, and can speed up queries where it is used by a factor of 5 to 10 times over cases where condition pushdown could be but is not used.
  • Page 683 Statements SELECT SELECT a, b FROM t1 WHERE b = 10; The use of condition pushdown can be seen in the output of EXPLAIN: mysql> EXPLAIN SELECT a,b FROM t1 WHERE b = 10\G *************************** 1. row *************************** id: 1...
  • Page 684 8.3.1.6. Optimization IS NULL MySQL can perform the same optimization on [877] that it can use for col_name IS NULL constant_value. For example, MySQL can use indexes and ranges to search for col_name = NULL with [877]. IS NULL Examples:...
  • Page 685 IS NULL WHERE col_name NULL, MySQL stops searching for more rows (for a particular key combination) after it has found one row that matches the condition. LEFT JOIN The implementation of...
  • Page 686 Syntax”.) 8.3.1.8. Nested-Loop Join Algorithms MySQL executes joins between tables using a nested-loop algorithm or variations on it. Nested-Loop Join Algorithm A simple nested-loop join (NLJ) algorithm reads rows from the first table in a loop one at a time, passing each row to a nested loop that processes the next table in the join.
  • Page 687 8.3.1.9. Nested Join Optimization As of MySQL 5.0.1, the syntax for expressing joins permits nested joins. The following discussion refers to the join syntax described in Section 13.2.8.2, “JOIN...
  • Page 688 (1,101) • Table contains row (101) In this case, the first expression returns a result set including the rows (1,1,101,101), (2,NULL,NULL,NULL), whereas the second expression returns the rows (1,1,101,101), (2,NULL,NULL,101): mysql> SELECT * -> FROM t1 -> LEFT JOIN ->...
  • Page 689 Optimizing Statements SELECT 2 | NULL | NULL | 101 | +------+------+------+------+ Therefore, if we omit parentheses in a join expression with outer join operators, we might change the result set for the original expression. More exactly, we cannot ignore parentheses in the right operand of the left outer join operation and in the left operand of a right join operation.
  • Page 690 Optimizing Statements SELECT WHERE P(T1,T2,T3). Here, are some join conditions (on expressions), whereas P1(T1,T2) P2(T3,T3) P(t1,t2,t3) is a condition over columns of tables T1,T2,T3. The nested-loop join algorithm would execute this query in the following manner: FOR each row t1 in T1 { FOR each row t2 in T2 such that P1(t1,t2) { FOR each row t3 in T3 such that P2(t2,t3) { IF P(t1,t2,t3) {...
  • Page 691 Optimizing Statements SELECT Note that for the query with inner joins, the optimizer could choose a different order of nested loops, such as this one: FOR each row t3 in T3 { FOR each row t2 in T2 such that P2(t2,t3) { FOR each row t1 in T1 such that P1(t1,t2) { IF P(t1,t2,t3) { t:=t1||t2||t3;...
  • Page 692 Optimizing Statements SELECT In this case, MySQL actually uses the following nested-loop schema for the execution of the query with inner joins: FOR each row t1 in T1 such that C1(t1) { FOR each row t2 in T2 such that P1(t1,t2) AND C2(t2)
  • Page 693 Fortunately, MySQL converts such a query into a query without an outer join operation if the WHERE condition is null-rejected. A condition is called null-rejected for an outer join operation if it evaluates to or to for any NULL-complemented row built for the operation.
  • Page 694 Optimizing Statements SELECT condition is null-rejected for the second outer join operation but is not null-rejected for the WHERE first one. If the condition is null-rejected for an outer join operation in a query, the outer join operation is WHERE replaced by an inner join operation.
  • Page 695 WHERE T3.D > 0 OR T1.D > 0 The algorithm that converts outer join operations into inner joins was implemented in full measure, as it has been described here, in MySQL 5.0.1. MySQL 4.1 performs only some simple conversions. 8.3.1.11.
  • Page 696 ... ORDER BY the same column list, MySQL optimizes it away without any speed penalty, although the sorting still occurs. If a query includes but you want to avoid the overhead of sorting the result, you can...
  • Page 697 If you want to increase speed, check whether you can get MySQL to use indexes rather ORDER BY than an extra sorting phase. If this is not possible, you can try the following strategies: •...
  • Page 698 (if any). In some cases, MySQL is able to do much better than that and to avoid creation of temporary tables by using index access.
  • Page 699 GROUP BY MySQL also avoids extra sorting operations because searching with prefixes in an ordered index already retrieves all the keys in order. Assume that there is an index on table t1(c1,c2,c3,c4).
  • Page 700 LIMIT row_count row_count unique rows. If you do not use columns from all tables named in a query, MySQL stops scanning any unused tables as soon as it finds the first match. In the following case, assuming that is used before...
  • Page 701 (If the subquery is a part of an NULL FALSE [881] [880] expression in the clause, MySQL assumes that you don't care.) WHERE When either or both of those conditions do not hold, optimization is more complex. Suppose that is known to be a non-NULL...
  • Page 702 NULL. FALSE FALSE As of MySQL 5.0.36, the optimizer chooses SQL compliance over speed, so it accounts for the possibility that might be NULL. outer_expr is NULL, to evaluate the following expression, it is necessary to run the...
  • Page 703 This fallback strategy is always the same: Do a full table scan. In EXPLAIN output, the fallback shows up as in the column: Full scan on NULL key Extra mysql> EXPLAIN SELECT t1.col1, -> t1.col1 IN (SELECT t2.key1 FROM t2 WHERE t2.col2=t1.col2) FROM t1\G *************************** 1. row *************************** id: 1 select_type: PRIMARY table: t1 *************************** 2.
  • Page 704 GROUP BY • As soon as MySQL has sent the required number of rows to the client, it aborts the query unless you are using SQL_CALC_FOUND_ROWS. • quickly returns an empty set. This can be useful for checking the validity of a query. When LIMIT 0 using one of the MySQL APIs, it can also be employed for obtaining the types of the result columns.
  • Page 705: Optimizing Non-Select Statements

    • You are using a key with low cardinality (many rows match the key value) through another column. In this case, MySQL assumes that by using the key it probably will do many key lookups and that a table scan would be faster.
  • Page 706 Optimizing Non-SELECT Statements faster in some cases) than using separate single-row statements. If you are adding data INSERT to a nonempty table, you can tune the [441] variable to make data bulk_insert_buffer_size insertion even faster. See Section 5.1.4, “Server System Variables”.
  • Page 707 2, 3, and 4 probably do not finish before 1 or 5, but the total time should be about 40% faster. INSERT, UPDATE, and operations are very fast in MySQL, but you can obtain better overall DELETE performance by adding locks around everything that does more than about five successive inserts or updates.
  • Page 708 Optimizing Non-SELECT Statements • For TABLE, the same principle applies, but because the repair is done by the server, REPAIR you set server system variables instead of variables. Also, In addition to setting myisamchk memory-allocation variables, increasing the [474] system variable myisam_max_sort_file_size increases the likelihood that the repair will use the faster filesort method and avoid the slower repair by key cache method.
  • Page 709: Other Optimization Tips

    • In some cases, it may make sense to introduce a column that is “hashed” based on information from other columns. If this column is short, reasonably unique, and indexed, it may be much faster than a “wide” index on many columns. In MySQL, it is very easy to use this extra column: SELECT * FROM...
  • Page 710 • Take advantage of the fact that columns have default values. Insert values explicitly only when the value to be inserted differs from the default. This reduces the parsing that MySQL must do and improves the insert speed.
  • Page 711: Controlling The Query Optimizer

    “good” and “bad” plans can be orders of magnitude (that is, seconds versus hours or even days), most query optimizers, including that of MySQL, perform a more or less exhaustive search for an optimal plan among all possible query evaluation plans. For join queries, the number of possible plans investigated by the MySQL optimizer grows exponentially with the number of tables referenced in a query.
  • Page 712: Optimization And Indexes

    8.5. Optimization and Indexes 8.5.1. Column Indexes All MySQL data types can be indexed. Use of indexes on the relevant columns is the best way to improve the performance of operations. SELECT The maximum number of indexes per table and the maximum index length is defined per storage engine.
  • Page 713 Multiple-Column Indexes MySQL can use multiple-column indexes for queries that test all the columns in the index, or queries that test just the first column, the first two columns, the first three columns, and so on. If you specify the columns in the right order in the index definition, a single composite index can speed up several kinds of queries on the same table.
  • Page 714: How Mysql Uses Indexes

    How MySQL Uses Indexes MySQL cannot use the index to perform lookups if the columns do not form a leftmost prefix of the index. Suppose that you have the statements shown here: SELECT SELECT * FROM tbl_name WHERE col1=val1; SELECT * FROM...
  • Page 715 (col1), col2), and (col1, (col1, col2, col3). MySQL cannot use an index if the columns do not form a leftmost prefix of the index. Suppose that you have the statements shown here: SELECT SELECT * FROM tbl_name WHERE col1=val1;...
  • Page 716: Myisam Index Statistics Collection

    When a given index value yields a large number of rows, the index is less useful and MySQL is less likely to use it.
  • Page 717 [476]: myisam_stats_method • You can force table statistics to be collected explicitly, as just described. However, MySQL may also collect statistics automatically. For example, if during the course of executing statements for a table, some of those statements modify the table, MySQL may collect statistics. (This may occur for bulk inserts or deletes, or some statements, for example.) If this happens, the statistics...
  • Page 718: Buffering And Caching

    • For index blocks, a special structure called the key cache (or key buffer) is maintained. The structure contains a number of block buffers where the most-used index blocks are placed. • For data blocks, MySQL uses no special cache. Instead it relies on the native operating system file system cache.
  • Page 719 They still compete for control structures that manage access to the key cache buffers. To reduce key cache access contention further, MySQL also provides multiple key caches. This feature enables you to assign different table indexes to different key caches.
  • Page 720 Key Cache MyISAM [458] is the cache component. See Section 5.1.5.1, “Structured System key_buffer_size Variables”, for a description of the syntax used for referring to structured key cache system variables. By default, table indexes are assigned to the main (default) key cache created at the server startup. When a key cache is destroyed, all indexes assigned to it are reassigned to the default key cache.
  • Page 721 To preload an index into a cache, use the statement. For example, the LOAD INDEX INTO CACHE following statement preloads nodes (index blocks) of indexes of the tables and t2: mysql> LOAD INDEX INTO CACHE t1, t2 IGNORE LEAVES; +---------+--------------+----------+----------+ | Table | Op...
  • Page 722: The Innodb Buffer Pool

    [415] option at server startup. size 8.6.1.6. Restructuring a Key Cache A key cache can be restructured at any time by updating its parameter values. For example: mysql> SET GLOBAL cold_cache.key_buffer_size=4*1024*1024; If you assign to either the [458] [460] key cache...
  • Page 723: The Mysql Query Cache

    To disable the query cache at server startup, set the [485] system variable to 0. query_cache_size By disabling the query cache code, there is no noticeable overhead. If you build MySQL from source, query cache capabilities can be excluded from the server entirely by invoking with the configure option.
  • Page 724 “Query Cache Options”.) SELECT To verify that enabling the query cache is beneficial, test the operation of your MySQL server with the cache enabled and disabled. Then retest periodically because query cache efficiency may change as server workload changes. 8.6.3.1. How the Query Cache Operates This section describes how the query cache works when it is operational.
  • Page 725 The MySQL Query Cache The query cache works for queries and stores a value that SELECT SQL_CALC_FOUND_ROWS ... is returned by a following query. [960] returns the correct SELECT FOUND_ROWS() FOUND_ROWS() value even if the preceding query was fetched from the cache because the number of found rows is also stored in the cache.
  • Page 726 | have_query_cache | YES +------------------+-------+ When using a standard MySQL binary, this value is always YES, even if query caching is disabled. Several other system variables control query cache operation. These can be set in an option file or on the command line when starting mysqld. The query cache system variables all have names that begin with query_cache_.
  • Page 727 The MySQL Query Cache new query cache size is 0 mysql> SET GLOBAL query_cache_size = 41984; Query OK, 0 rows affected (0.00 sec) mysql> SHOW VARIABLES LIKE 'query_cache_size'; +------------------+-------+ | Variable_name | Value | +------------------+-------+ | query_cache_size | 41984 |...
  • Page 728 [484]. However, be careful to not make it too large (see the query_cache_min_res_unit previous item). 8.6.3.4. Query Cache Status and Maintenance To check whether the query cache is present in your MySQL server, use the following statement: mysql> SHOW VARIABLES LIKE 'have_query_cache'; +------------------+-------+...
  • Page 729: Locking Issues

    MySQL manages contention for table contents using locking: • Internal locking is performed within the MySQL server itself to manage contention for table contents by multiple threads. This type of locking is internal because it is performed entirely by the server and involves no other programs.
  • Page 730 [533] status variables, which indicate Table_locks_immediate Table_locks_waited the number of times that requests for table locks could be granted immediately and the number that had to wait, respectively: mysql> SHOW STATUS LIKE 'Table%'; +-----------------------+---------+ | Variable_name | Value +-----------------------+---------+ | Table_locks_immediate | 1151552 |...
  • Page 731: Table Locking Issues

    Options other than row-level or page-level locking: • Versioning (such as that used in MySQL for concurrent inserts) where it is possible to have one writer at the same time as many readers. This means that the database or table supports different views for the data depending on when access begins.
  • Page 732: Concurrent Inserts

    LOCK TABLES faster than updating without locks. Splitting table contents into separate tables may also help. • If you encounter speed problems with table locks in MySQL, you may be able to improve performance by converting some of your tables to tables.
  • Page 733: External Locking

    External locking is the use of file system locking to manage contention for database tables by MyISAM multiple processes. External locking is used in situations where a single process such as the MySQL server cannot be assumed to be the only process that requires access to tables. Here are some examples: •...
  • Page 734: Optimizing Database Structure

    You can get better performance for a table and minimize storage space by using the techniques listed here: • Use the most efficient (smallest) data types possible. MySQL has many specialized types that save disk space and memory. For example, use the smaller integer types if possible to get smaller tables.
  • Page 735: Using Procedure Analyse

    • If it is very likely that a string column has a unique prefix on the first number of characters, it is better to index only this prefix, using MySQL's support for creating an index on the leftmost part of the column (see Section 13.1.8,...
  • Page 736: How Mysql Opens And Closes Tables

    MySQL closes an unused table and removes it from the table cache under the following circumstances: • When the cache is full and a thread tries to open a table that is not in the cache.
  • Page 737: Disadvantages Of Creating Many Tables In The Same Database

    DISTINCT ORDER BY • If you use the option, MySQL uses an in-memory temporary table, unless the SQL_SMALL_RESULT query also contains elements (described later) that require on-disk storage. To determine whether a query requires a temporary table, use...
  • Page 738: Optimizing The Mysql Server

    (not repair) a table without telling myisamchk the server to flush and lock the tables first. Note that using multiple MySQL servers to access the same data concurrently is generally not recommended, except when using MySQL Cluster. statements use internal locking, so you can use them...
  • Page 739 The output mysqld includes the default variable values and looks something like this: help TRUE abort-slave-event-count allow-suspicious-udfs FALSE auto-increment-increment auto-increment-offset automatic-sp-privileges TRUE basedir /home/jon/bin/mysql-5.0/ FALSE bind-address (No default value) character-set-client-handshake TRUE character-set-filesystem binary character-set-server latin1 character-sets-dir /home/jon/bin/mysql-5.0/share/mysql/charsets/ chroot...
  • Page 740 FALSE merge TRUE myisam-recover ndbcluster FALSE FALSE old-passwords FALSE old-style-user-limits FALSE pid-file /home/jon/bin/mysql-5.0/var/tonfisk.pid port 3306 port-open-timeout relay-log (No default value) relay-log-index (No default value) relay-log-info-file relay-log.info replicate-same-server-id FALSE report-host (No default value) report-password (No default value)
  • Page 741 Tuning Server Parameters ft_query_expansion_limit ft_stopword_file (No default value) group_concat_max_len 1024 innodb_additional_mem_pool_size 1048576 innodb_autoextend_increment innodb_buffer_pool_awe_mem_mb innodb_buffer_pool_size 8388608 innodb_commit_concurrency innodb_concurrency_tickets innodb_file_io_threads innodb_force_recovery innodb_lock_wait_timeout innodb_log_buffer_size 1048576 innodb_log_file_size 5242880 innodb_log_files_in_group innodb_mirrored_log_groups innodb_open_files innodb_sync_spin_loops innodb_thread_concurrency innodb_thread_sleep_delay 10000 interactive_timeout 28800 join_buffer_size 131072 keep_files_on_create FALSE key_buffer_size 8384512 key_cache_age_threshold key_cache_block_size 1024...
  • Page 742 Section 5.1.6, “Server Status Variables”. MySQL uses algorithms that are very scalable, so you can usually run with very little memory. However, normally you get better performance by giving MySQL more memory. When tuning a MySQL server, the two most important variables to configure are [458] [498].
  • Page 743: How Mysql Uses Threads For Client Connections

    You can make use of the example option files included with your MySQL distribution; see Section 5.1.2, “Server Configuration Defaults”. If you specify an option on the command line for...
  • Page 744: How Mysql Uses Memory

    (calculated as the sum of all column lengths) or that contain columns are stored on disk. BLOB If an internal in-memory temporary table becomes too large, MySQL handles this automatically by changing the table from in-memory to on-disk format, to be handled by the storage engine.
  • Page 745: Disk Issues

    [498] system variable. If a table has been table_cache used by two running threads at the same time, the cache contains two entries for the table. See Section 8.8.3, “How MySQL Opens and Closes Tables”. • A statement or command closes all tables that...
  • Page 746: Using Symbolic Links

    8.9.6.1. Using Symbolic Links for Databases on Unix On Unix, the way to symlink a database is first to create a directory on some disk where you have free space and then to create a soft link to it from the MySQL data directory. shell>...
  • Page 747 (.MYI) file. The data file and index file can be moved elsewhere and replaced in the data directory by symlinks. The format file cannot. • You can symlink the data file and the index file independently to different directories. • To instruct a running MySQL server to perform the symlinking, use the DATA DIRECTORY options to TABLE.
  • Page 748 Suppose that you want to place the database directory for a database named at D:\data\mydb. mydb To do this, create a symbolic link in the MySQL data directory that points to D:\data\mydb. However, before creating the symbolic link, make sure that the directory exists by creating it if D:\data\mydb necessary.
  • Page 749: Enabling Large

    The following limitations apply to the use of files for database symbolic linking on Windows: .sym • The symbolic link is not used if a directory with the same name as the database exists in the MySQL data directory. • The [1241] option cannot be used.
  • Page 750: Dns Lookup Optimization And The Host Cache

    Large page support in MySQL is disabled by default. To enable it, start the server with the --large- [410] option. For example, you can use the following lines in your server's file: pages my.cnf...
  • Page 751: Examining Thread Information

    8.10. Examining Thread Information When you are attempting to ascertain what your MySQL server is doing, it can be helpful to examine the process list, which is the set of threads currently executing within the server. Process list information is available from these sources: •...
  • Page 752: Thread Command Values

    Thread Command Values • indicate what the thread is doing. Command State Most states correspond to very quick operations. If a thread stays in a given state for many seconds, there might be a problem that needs to be investigated. •...
  • Page 753 Thread Command Values The thread is executing a prepared statement. • Fetch The thread is fetching the results from executing a prepared statement. • Field List The thread is retrieving information for table columns. • Init DB The thread is selecting a default database. •...
  • Page 754: General Thread States

    General Thread States The thread is waiting for the client to send a new statement to it. • Statistics The thread is producing server-status information. • Table Dump The thread is sending table contents to a slave server. • Time Unused.
  • Page 755 The server is copying to a temporary table on disk. The temporary result set has become too large (see Section 8.8.5, “How MySQL Uses Internal Temporary Tables”). Consequently, the thread is changing the temporary table from in-memory to disk-based format to save memory.
  • Page 756 KILL The flag is checked in each major loop in MySQL, but in some cases it might still take a short time for the thread to die. If the thread is locked by some other thread, the kill takes effect as soon as the other thread releases its lock.
  • Page 757 MySQL could not optimize away the SELECT DISTINCT distinct operation at an early stage. Because of this, MySQL requires an extra stage to remove all duplicated rows before sending the result to the client. •...
  • Page 758 General Thread States The thread is beginning an operation. ALTER TABLE • Sorting for group The thread is doing a sort to satisfy a GROUP • Sorting for order The thread is doing a sort to satisfy a ORDER • Sorting index The thread is sorting index pages for more efficient access during a table optimization...
  • Page 759: Delayed-Insert Thread States

    Delayed-Insert Thread States The thread is waiting for a global read lock obtained by another thread (with FLUSH TABLES WITH LOCK) to be released. READ • Waiting for tables, Waiting for table The thread got a notification that the underlying structure for a table has changed and it needs to reopen the table to get the new structure.
  • Page 760: Query Cache Thread States

    8.10.4. Query Cache Thread States These thread states are associated with the query cache (see Section 8.6.3, “The MySQL Query Cache”). • checking privileges on cached query The server is checking whether the user has privileges to access a cached query result.
  • Page 761: Replication Slave I/O Thread States

    Replication Slave I/O Thread States The following list shows the most common states you may see in the column for the master's State thread. If you see no threads on a master server, this means that Binlog Dump Binlog Dump replication is not running—that is, that no slaves are currently connected.
  • Page 762: Replication Slave Sql Thread States

    Replication Slave SQL Thread States The thread has connected to the master and is waiting for binary log events to arrive. This can last for a long time if the master is idle. If the wait lasts for [1466] seconds, slave_net_timeout a timeout occurs.
  • Page 763: Mysql Cluster Thread States

    This is used to have a correct binary log of schema operations for NDB. • Waiting for event from ndbcluster The server is acting as an SQL node in a MySQL Cluster, and is connected to a cluster management node. •...
  • Page 764 MySQL Cluster Thread States • Waiting for schema epoch The thread is waiting for a schema epoch (that is, a global checkpoint).
  • Page 765: Language Structure

    • Comments 9.1. Literal Values This section describes how to write literal values in MySQL. These include strings, numbers, hexadecimal values, boolean values, and NULL. The section also covers the various nuances and “gotchas” that you may run into when dealing with these basic types in MySQL.
  • Page 766 NO_BACKSLASH_ESCAPES SQL mode is enabled. Each of these sequences begins with a backslash (“\”), known as the escape character. MySQL recognizes the escape sequences shown in Table 9.1, “Special Character Escape Sequences”. For all other escape sequences, backslash is ignored. That is, the escaped character is interpreted as if it was not escaped.
  • Page 767: Number Literals

    API”. Other language interfaces may provide a similar capability. • As an alternative to explicitly escaping special characters, many MySQL APIs provide a placeholder capability that enables you to insert special markers into a statement string, and then bind data values to them when you issue the statement.
  • Page 768: Date And Time Literals

    Date and time values can be represented in several formats, such as quoted strings or as numbers, depending on the exact type of the value and other factors. For example, in contexts where MySQL expects a date, it interprets any of '2015-07-21', '20150721', and as a date.
  • Page 769 6 characters. For example, if you specify '9903', thinking that represents March, 1999, MySQL converts it to the “zero” date value. This occurs because the year and month values are and 03, but the day part is completely missing.
  • Page 770: Hexadecimal Literals

    SELECT TRUE, true, FALSE, false; -> 1, 1, 0, 0 9.1.6. Bit-Field Literals Beginning with MySQL 5.0.3, bit-field values can be written using notation. b'value' 0bvalue is a binary value written using zeros and ones. value...
  • Page 771: Null Values

    Values”. NULL 9.2. Schema Object Names Certain objects within MySQL, including database, table, index, column, alias, view, stored procedure, partition, and other object names are known as identifiers. This section describes the permissible syntax for identifiers in MySQL. Section 9.2.2, “Identifier Case Sensitivity”, describes which types of...
  • Page 772 • Database, table, and column names cannot end with space characters. • Database and table names cannot contain “/”, “\”, “.”, or characters that are not permitted in file names. The identifier quote character is the backtick (“`”): mysql> SELECT * FROM `select` WHERE `select`.id > 100; If the [535]...
  • Page 773: Identifier Qualifiers

    Basic Multilingual Plane (BMP). Supplementary characters are not permitted. 9.2.1. Identifier Qualifiers MySQL permits names that consist of a single identifier or multiple identifiers. The components of a multiple-part name must be separated by period (“.”) characters. The initial parts of a multiple-part name act as qualifiers that affect the context within which the final identifier is interpreted.
  • Page 774: Identifier Case Sensitivity

    TABLE CREATE DATABASE should not set this variable to 0 if you are running MySQL on a system that has case- insensitive file names (such as Windows or Mac OS X). If you force this variable to 0 with [466]...
  • Page 775: Function Name Parsing And Resolution

    InnoDB lower_case_table_names=1. If you are using MySQL on only one platform, you do not normally have to change the [466] variable from its default value. However, you may encounter lower_case_table_names difficulties if you want to transfer tables between platforms that differ in file system case sensitivity.
  • Page 776 5.1, they are rather numerous (about 200), so you may find it easiest to treat the no-whitespace requirement as applying to all function calls. In MySQL 5.1, parser improvements reduce to about 30 the number of affected function names.
  • Page 777 Function Name Parsing and Resolution CREATE TABLE `count`(i INT); CREATE TABLE `count` (i INT); • With [536] enabled, the parser loosens the requirement that there be no whitespace IGNORE_SPACE between the function name and the following parenthesis. This provides more flexibility in writing function calls.
  • Page 778: Reserved Words

    UDF with a different nonconflicting name. • If a new version of MySQL implements a built-in function with the same name as an existing stored function, you have two choices: Rename the stored function to use a nonconflicting name, or change calls to the function so that they use a schema qualifier (that is, use schema_name.func_name()
  • Page 779 Reserved Words Table 9.2. Reserved Words in MySQL 5.0.96 ALTER ANALYZE ASENSITIVE BEFORE BETWEEN BIGINT BINARY BLOB BOTH CALL CASCADE CASE CHANGE CHAR CHARACTER CHECK COLLATE COLUMN CONDITION CONSTRAINT CONTINUE CONVERT CREATE CROSS CURRENT_DATE CURRENT_TIME CURRENT_TIMESTAMP CURRENT_USER CURSOR DATABASE DATABASES...
  • Page 780 USING UTC_DATE UTC_TIME UTC_TIMESTAMP VALUES VARBINARY VARCHAR VARCHARACTER VARYING WHEN WHERE WHILE WITH WRITE YEAR_MONTH ZEROFILL Table 9.3. New Reserved Words in MySQL 5.0 ASENSITIVE CALL CONDITION CONNECTION CONTINUE CURSOR DECLARE DETERMINISTIC EACH ELSEIF EXIT FETCH GOTO INOUT INSENSITIVE ITERATE...
  • Page 781: User-Defined Variables

    “.”, “_”, and “$”. A user variable name can contain other characters if you quote it as a string or identifier (for example, @'my-var', @"my-var", or @`my-var`). User variable names are not case sensitive in MySQL 5.0 and up, but are case sensitive before MySQL 5.0.
  • Page 782 If a user variable is assigned a nonbinary (character) string value, it has the same character set and collation as the string. The coercibility of user variables is implicit as of MySQL 5.0.3. (This is the same coercibility as for table column values.) Bit values assigned to user variables are treated as binary strings.
  • Page 783 +------+ 1 row in set (0.00 sec) mysql> SELECT `@col` FROM t; ERROR 1054 (42S22): Unknown column '@col' in 'field list' mysql> SET @col = "`c1`"; Query OK, 0 rows affected (0.00 sec) mysql> SELECT @col FROM t; +------+ | @col |...
  • Page 784: Expression Syntax

    Assembling an SQL statement in this fashion is sometimes known as “Dynamic SQL”. 9.5. Expression Syntax The following rules define expression syntax in MySQL. The grammar shown here is based on that given in the file of MySQL source distributions. See the notes after the grammar sql/sql_yacc.yy...
  • Page 785 Expression Syntax bit_expr bit_expr bit_expr bit_expr bit_expr bit_expr bit_expr interval_expr bit_expr interval_expr simple_expr simple_expr: literal identifier function_call simple_expr COLLATE collation_name param_marker variable simple_expr simple_expr simple_expr simple_expr simple_expr simple_expr | BINARY simple_expr (expr [, expr] ...) | ROW (expr, expr [, expr] ...) | (subquery) | EXISTS (subquery) {identifier...
  • Page 786: Comment Syntax

    MySQL extensions, but is still portable, by using comments of the following form: MySQL-specific code In this case, MySQL Server parses and executes the code within the comment as it would any other SQL statement, but other SQL servers will ignore the extensions. For example, MySQL Server...
  • Page 787: Globalization

    • Selecting the locale for day and month names. 10.1. Character Set Support MySQL includes character set support that enables you to store data using a variety of character sets and perform comparisons according to a variety of collations. You can specify character sets at the server, database, table, and column level.
  • Page 788: Character Sets And Collations In General

    Character set issues affect not only data storage, but also communication between client programs and the MySQL server. If you want the client program to communicate with the server using a character set different from the default, you'll need to indicate which one. For example, to use the...
  • Page 789: Character Sets And Collations In Mysql

    Character Sets and Collations in MySQL 10.1.2. Character Sets and Collations in MySQL The MySQL server can support multiple character sets. To list the available character sets, use the statement. A partial listing follows. For more complete information, see SHOW CHARACTER SET Section 10.1.13, “Character Sets and Collations That MySQL...
  • Page 790: Specifying Character Sets And Collations

    Collations”. 10.1.3.1. Server Character Set and Collation MySQL Server has a server character set and a server collation. These can be set at server startup on the command line or in an option file and changed at runtime. Initially, the server character set and collation depend on the options that you use when you start mysqld.
  • Page 791 MySQL server. Example: CREATE DATABASE db_name CHARACTER SET latin1 COLLATE latin1_swedish_ci; MySQL chooses the database character set and database collation in the following manner: • If both are specified, character set and collation are used.
  • Page 792 The table character set and collation are used as default values for column definitions if the column character set and collation are not specified in individual column definitions. The table character set and collation are MySQL extensions; there are no such things in standard SQL. 10.1.3.4. Column Character Set and Collation Every “character”...
  • Page 793 CHARACTER SET COLLATE If you use to convert a column from one character set to another, MySQL attempts to ALTER TABLE map the data values, but if the character sets are incompatible, there may be data loss. 10.1.3.5. Character String Literal Character Set and Collation Every character string literal has a character set and a collation.
  • Page 794 Specifying Character Sets and Collations Examples: SELECT _latin1 x'AABBCC'; SELECT _latin1 0xAABBCC; SELECT _latin1 b'1100011'; SELECT _latin1 0b1100011; MySQL determines a literal's character set and collation in the following manner: • If both are specified, character set and collation are used. COLLATE Y •...
  • Page 795 SELECT N'some text'; SELECT n'some text'; SELECT _utf8'some text'; For information on upgrading character sets to MySQL 5.0 from versions prior to 4.1, see the MySQL 3.23, 4.0, 4.1 Reference Manual. 10.1.3.7. Examples of Character Set and Collation Assignment The following examples show how MySQL determines default character set and collation values.
  • Page 796: Connection Character Sets And Collations

    CHAR(10) ) DEFAULT CHARACTER SET latin1 COLLATE latin1_danish_ci; We have a column with a default character set and a default collation. In this circumstance, MySQL checks the table level to determine the column character set and collation. Consequently, the character set for column and its collation is latin1_danish_ci.
  • Page 797 Connection Character Sets and Collations • What character set should the server translate a statement to after receiving it? For this, the server uses the [442] character_set_connection [443] system variables. It converts statements sent by the client from collation_connection [441] [442] (except for string character_set_client...
  • Page 798: Configuring The Character Set And Collation For Applications

    Messages”. 10.1.5. Configuring the Character Set and Collation for Applications For applications that store data using the default MySQL character set and collation (latin1, latin1_swedish_ci), no special configuration should be needed. If applications require data storage using a different character set or collation, you can configure character set information several ways:...
  • Page 799 • Specify character settings at configuration time, if you build MySQL from source. This causes the server to use the given settings for all applications, without having to specify them at server startup.
  • Page 800: Character Set For Error Messages

    SET NAMES server. Regardless of how you configure the MySQL character set for application use, you must also consider the environment within which those applications execute. If you will send statements using UTF-8 text taken from a file that you create in an editor, you should edit the file with the locale of your environment set to UTF-8 so that the file encoding is correct and so that the operating system handles it correctly.
  • Page 801 Therefore, the following statement causes an error message because the latin2_bin collation is not legal with the character set: latin1 mysql> SELECT _latin1 'x' COLLATE latin2_bin; ERROR 1253 (42000): COLLATION 'latin2_bin' is not valid for CHARACTER SET 'latin1'...
  • Page 802 Collation Issues 10.1.7.5. Collation of Expressions In the great majority of statements, it is obvious what collation MySQL uses to resolve a comparison operation. For example, in the following cases, it should be clear that the collation is the collation of column charset_name: SELECT x FROM T ORDER BY x;...
  • Page 803 'A' COLLATE x Error column1 COLLATE x = 'A' COLLATE y [958] function can be used to determine the coercibility of a string COERCIBILITY() expression: mysql> SELECT COERCIBILITY('A' COLLATE latin1_swedish_ci); -> 0 mysql> SELECT COERCIBILITY(VERSION()); -> 3 mysql> SELECT COERCIBILITY('A');...
  • Page 804 Lettercase conversion. Collations provide information about lettercase of characters, so characters in a nonbinary string can be converted from one lettercase to another, even for collations that _bin ignore lettercase for ordering: mysql> SET NAMES latin1 COLLATE latin1_bin; Query OK, 0 rows affected (0.02 sec) mysql> SELECT LOWER('aA'), UPPER('zZ');...
  • Page 805 CHAR(10) BINARY CHAR(10) CHARACTER SET latin1 COLLATE latin1_bin The effect of as a column attribute differs from its effect prior to MySQL 4.1. Formerly, BINARY BINARY resulted in a column that was treated as a binary string. A binary string is a string of bytes that has no character set or collation, which differs from a nonbinary character string that has a binary collation.
  • Page 806 Muffler Müller MX Systems MySQL Suppose also that the column values are retrieved using the following statement: SELECT X FROM T ORDER BY X COLLATE collation_name; The following table shows the resulting order of the values if we use with different collations.
  • Page 807: String Repertoire

    The repertoire of a character set is the collection of characters in the set. As of MySQL 5.0.48, string expressions have a repertoire attribute, which can have two values: • ASCII: The expression can contain only characters in the Unicode range to U+007F.
  • Page 808: Operations Affected By Character Set Support

    This section describes operations that take character set information into account. 10.1.9.1. Result Strings MySQL has many operators and functions that return a string. This section answers the question: What is the character set and collation of such a string? For simple functions that take string input and return a string result as output, the output's character set and collation are the same as those of the principal input value.
  • Page 809 The syntax is: CONVERT() CONVERT(expr USING transcoding_name) In MySQL, transcoding names are the same as the corresponding character set names. Examples: SELECT CONVERT(_latin1'Müller' USING utf8); INSERT INTO utf8table (utf8column) SELECT CONVERT(latin1field USING utf8) FROM latin1table;...
  • Page 810 It takes an optional SHOW CHARACTER SET [896] clause that indicates which character set names to match. For example: LIKE mysql> SHOW CHARACTER SET LIKE 'latin%'; +---------+-----------------------------+-------------------+--------+ | Charset | Description | Default collation | Maxlen |...
  • Page 811: Unicode Support

    The character set is not part of the display but is implied by the collation name. 10.1.10. Unicode Support MySQL 5.0 supports two character sets for storing Unicode data: • ucs2, the UCS-2 encoding of the Unicode character set using 16 bits per character •...
  • Page 812: For Metadata

    UTF-8 for Metadata The MySQL implementation of UCS-2 stores characters in big-endian byte order and does not use a byte order mark (BOM) at the beginning of values. Other database systems might use little-endian byte order or a BOM. In such cases, conversion of values will need to be performed when transferring data between those systems and MySQL.
  • Page 813: Column Character Set Conversion

    To satisfy both requirements, MySQL stores metadata in a Unicode character set, namely UTF-8. This does not cause any disruption if you never use accented or non-Latin characters. But if you do, you should be aware that metadata is in UTF-8.
  • Page 814: Character Sets And Collations That Mysql Supports

    (the character set you're converting the column to). If you use a binary column to store information in multiple character sets, MySQL has no way to know which values use which character set and cannot convert the data properly.
  • Page 815 Character Sets and Collations That MySQL Supports You can always list the available character sets and their default collations with the SHOW CHARACTER statement: mysql> SHOW CHARACTER SET; +----------+-----------------------------+---------------------+ | Charset | Description | Default collation +----------+-----------------------------+---------------------+ | big5 | Big5 Traditional Chinese...
  • Page 816 Also, combining marks are not fully supported. This affects primarily Vietnamese, Yoruba, and some smaller languages such as Navajo. MySQL implements language-specific Unicode collations only if the ordering with xxx_unicode_ci does not work well for a language. Language-specific collations are UCA-based. They are derived from with additional language tailoring rules.
  • Page 817 For additional information about Unicode collations in MySQL, see Collation-Charts.Org (utf8). 10.1.13.2. West European Character Sets Western European character sets cover most West European languages, such as French, Spanish, Catalan, Basque, Portuguese, Italian, Albanian, Dutch, German, Danish, Swedish, Norwegian, Finnish, Faroese, Icelandic, Irish, Scottish, and English.
  • Page 818 0x90 0x9d to 0x009d. collation is the default that probably is used by the majority of MySQL latin1_swedish_ci customers. Although it is frequently said that it is based on the Swedish/Finnish collation rules, there are Swedes and Finns who disagree with this statement.
  • Page 819 For additional information about Western European collations in MySQL, see Collation-Charts.Org (ascii, cp850, dec8, hp8, latin1, macroman, swe7). 10.1.13.3. Central European Character Sets MySQL provides some support for character sets used in the Czech Republic, Slovakia, Hungary, Romania, Slovenia, Croatia, Poland, and Serbia (Latin). •...
  • Page 820 • latin5_bin • (default) latin5_turkish_ci For additional information about South European and Middle Eastern collations in MySQL, see Collation-Charts.Org (armscii8, cp1256, geostd8, greek, hebrew, latin5). 10.1.13.5. Baltic Character Sets The Baltic character sets cover Estonian, Latvian, and Lithuanian languages. •...
  • Page 821 • (default) koi8u_general_ci For additional information about Cyrillic collations in MySQL, see Collation-Charts.Org (cp1251, cp866, koi8r, koi8u). ). 10.1.13.7. Asian Character Sets The Asian character sets that we support include Chinese, Japanese, Korean, and Thai. These can be complicated. For example, the Chinese sets must allow for thousands of different characters. See Section 10.1.13.7.1, “The...
  • Page 822 • ujis_bin • (default) ujis_japanese_ci collation sorts on number of strokes. big5_chinese_ci For additional information about Asian collations in MySQL, see Collation-Charts.Org (big5, cp932, eucjpms, euckr, gb2312, gbk, sjis, tis620, ujis). 10.1.13.7.1. The Character Set cp932 Why is needed? cp932...
  • Page 823 • There are several conversion rules from so-called “SHIFT JIS” to Unicode, and some characters are converted to Unicode differently depending on the conversion rule. MySQL supports only one of these rules (described later). The MySQL character set is designed to solve these problems.
  • Page 824: Setting The Error Message Language

    Setting the Error Message Language For some characters, conversion to and from is different for and cp932. The following ucs2 sjis tables illustrate these differences. Conversion to ucs2: Value -> Conversion -> Conversion sjis/cp932 sjis ucs2 cp932 ucs2 005C 005C 007E 007E 815C...
  • Page 825: Adding A Character Set

    MySQL. 10.3. Adding a Character Set This section discusses the procedure for adding a character set to MySQL. The proper procedure depends on whether the character set is simple or complex: • If the character set does not need special string collating routines for sorting and does not need multi-byte character support, it is simple.
  • Page 826 Adding a Character Set a suffix of (general, case insensitive). It is possible for the binary collation to be the general_ci default collation, but usually they are different. The default collation should have a flag. primary The binary collation should have a flag.
  • Page 827: Character Definition Arrays

    Character Definition Arrays add_compiled_collation(&my_charset_MYSET_bin); #endif b. If the character set uses ctype-MYSET.c, edit and add strings/Makefile.am to each definition of the variable, and to the variable. ctype-MYSET.c CSRCS EXTRA_DIST c. If the character set uses ctype-MYSET.c, edit and add libmysql/Makefile.shared to the definition.
  • Page 828: String Collating Support For Complex Character Sets

    A collation is a set of rules that defines how to compare and sort character strings. Each collation in MySQL belongs to a single character set. Every character set has at least one collation, and most have two or more collations.
  • Page 829: Collation Implementation Types

    3. Restart the server 4. Verify that the collation is present The instructions here cover only collations that can be added without recompiling MySQL. To add a collation that does require recompiling (as implemented by means of functions in a C source file), use the instructions in Section 10.3, “Adding a Character...
  • Page 830 Collations for Unicode multi-byte character sets Some of these collations are based on the Unicode Collation Algorithm (UCA), others are not. Non-UCA collations have a one-to-one mapping from character code to weight. In MySQL, such collations are case insensitive and accent insensitive.
  • Page 831: Choosing A Collation Id

    IDs between 53 and 57, and between 99 and 128. Or you could choose an ID higher than 210. Warning If you upgrade MySQL, you may find that the collation ID you choose has been assigned to a collation included in the new MySQL distribution. In this case, you...
  • Page 832: Adding A Simple Collation To An 8-Bit Character Set

    This section describes how to add a simple collation for an 8-bit character set by writing the elements associated with a character set description in the MySQL <collation> <charset> file. The procedure described here does not require recompiling MySQL. The example Index.xml adds a collation named to the character set.
  • Page 833: Adding A Uca Collation To A Unicode Character Set

    Data Markup Language (LDML) specification, which is available at http://www.unicode.org/reports/tr35/. In 5.0, this method of adding collations is supported as of MySQL 5.0.46. With this method, you need not define the entire collation. Instead, you begin with an existing “base” collation and describe the new collation in terms of how it differs from the base collation.
  • Page 834 <charset element. Remember that each collation must have its own unique ID. name="ucs2"> 5. Restart the server and use this statement to verify that the collation is present: mysql> SHOW COLLATION LIKE 'utf8_phone_ci'; +---------------+---------+-----+---------+----------+---------+ | Collation | Charset | Id...
  • Page 835 1 row in set (0.00 sec) 10.4.4.2. LDML Syntax Supported in MySQL This section describes the LDML syntax that MySQL recognizes. This is a subset of the syntax described in the LDML specification available at http://www.unicode.org/reports/tr35/, which should be consulted for further information. The rules described here are all supported except that character sorting occurs only at the primary level.
  • Page 836: Character Set Configuration

    (as database object identifiers, column values, or both), these may be displayed incorrectly in output from the client or the output itself may be formatted incorrectly. In such cases, starting the mysql client with [266]—that is, setting the client --default-character-set=system_character_set character set to match the system character set—should fix the problem.
  • Page 837 The MySQL installation procedure creates the time zone tables in the database, but does not mysql load them. You must do so manually using the following instructions. (If you are upgrading to MySQL 4.1.3 or later from an earlier version, you can create the tables by upgrading your database.
  • Page 838 If your system is one that has no zoneinfo database (for example, Windows or HP-UX), you can use the package of pre-built time zone tables that is available for download at the MySQL Developer Zone: http://dev.mysql.com/downloads/timezones.html This time zone package contains .frm, .MYD, and...
  • Page 839: Staying Current With Time Zone Changes

    For MySQL, there are two factors to consider in staying current: • The operating system time affects the value that the MySQL server uses for times if its time zone is set to SYSTEM. Make sure that your operating system is using the latest time zone information.
  • Page 840: Time Zone Leap Second Support

    10.6.2. Time Zone Leap Second Support Before MySQL 5.0.74, if the operating system is configured to return leap seconds from OS time calls or if the MySQL server uses a time zone definition that has leap seconds, functions such as [926] could return a value having a time part that ends with or :59:61.
  • Page 841: Mysql Server Locale Support

    2 | 2008-12-31 23:59:59 | +------+---------------------+ 1 row in set (0.00 sec) 10.7. MySQL Server Locale Support Beginning with MySQL 5.0.25, the locale indicated by the [462] system variable lc_time_names controls the language used to display day and month names and abbreviations. This variable affects...
  • Page 842 [462] may be set to any of the following locale values. The set of locales supported lc_time_names by MySQL may differ from those supported by your operating system. ar_AE: Arabic - United Arab Emirates ar_BH: Arabic - Bahrain ar_DZ: Arabic - Algeria...
  • Page 843 MySQL Server Locale Support en_AU: English - Australia en_CA: English - Canada en_GB: English - United Kingdom en_IN: English - India en_NZ: English - New Zealand en_PH: English - Philippines en_US: English - United States en_ZA: English - South Africa...
  • Page 845: Data Types

    11.4. Using Data Types from Other Database Engines ............... 861 MySQL supports a number of data types in several categories: numeric types, date and time types, and string (character and byte) types. This chapter provides an overview of these data types, a more detailed description of the properties of the types in each category, and a summary of the data type storage requirements.
  • Page 846 1 to 64. The default is 1 if is omitted. This data type was added in MySQL 5.0.3 for MyISAM, and extended in 5.0.5 to MEMORY, InnoDB, BDB, and NDBCLUSTER. Before 5.0.3, is a synonym for TINYINT(1).
  • Page 847 • You can always store an exact integer value in a column by storing it using a string. In BIGINT this case, MySQL performs a string-to-number conversion that involves no intermediate double- precision representation. • The [906], [906], and...
  • Page 848 MySQL DECIMAL used to create the table. If your server is from MySQL 5.0.3 or higher, but you have DECIMAL columns in tables that were created before 5.0.3, the old behavior still applies to those columns. To...
  • Page 849: Date And Time Type Overview

    REAL FLOAT • FLOAT(p) [UNSIGNED] [ZEROFILL] A floating-point number. represents the precision in bits, but MySQL uses this value only to determine whether to use for the resulting data type. If is from 0 to 24, the data FLOAT DOUBLE...
  • Page 850: String Type Overview

    Section 11.1.6, “String Types”, and Section 11.2, “Data Type Storage Requirements”. In some cases, MySQL may change a string column to a type different from that given in a CREATE statement. See Section 13.1.10.3, “Silent Column Specification Changes”. TABLE ALTER TABLE In MySQL 4.1 and up, string data types include some features that you may not have encountered in...
  • Page 851 • Character column sorting and comparison are based on the character set assigned to the column. (Before MySQL 4.1, sorting and comparison were based on the collation of the server character set.) For the CHAR, VARCHAR, TEXT, ENUM, and...
  • Page 852 CHAR BYTE BINARY MySQL permits you to create a column of type CHAR(0). This is useful primarily when you have to be compliant with old applications that depend on the existence of a column but that do not actually use its value.
  • Page 853 BLOB 2-byte length prefix that indicates the number of bytes in the value. An optional length can be given for this type. If this is done, MySQL creates the column as the smallest type large enough to hold values bytes long.
  • Page 854: Numeric Types

    Structure”. .frm 11.1.4. Numeric Types MySQL supports all standard SQL numeric data types. These types include the exact numeric data types (INTEGER, SMALLINT, DECIMAL, and NUMERIC), as well as the approximate numeric data types (FLOAT, REAL, and PRECISION). The keyword...
  • Page 855 -999.99 enforces this limit as of MySQL 5.0.3. Before 5.0.3, on the positive end of the range, the column could actually store numbers up to 9999.99. (For positive numbers, MySQL 5.0.2 and earlier used the byte reserved for the sign to extend the upper end of the range.) In standard SQL, the syntax is equivalent to DECIMAL(M,0).
  • Page 856 BIT(6) assigning b'000101'. 11.1.4.5. Numeric Type Attributes MySQL supports an extension for optionally specifying the display width of integer data types in parentheses following the base keyword for the type. For example, specifies an with a INT(4) display width of four digits.
  • Page 857 AUTO_INCREMENT 11.1.4.6. Out-of-Range and Overflow Handling When MySQL stores a value in a numeric column that is outside the permissible range of the column data type, the result depends on the SQL mode in effect at the time: • If strict SQL mode is enabled, MySQL rejects the out-of-range value with an error, and the insert fails, in accordance with the SQL standard.
  • Page 858: Date And Time Types

    Keep in mind these general considerations when working with date and time types: • MySQL retrieves values for a given date or time type in a standard output format, but it attempts to interpret a variety of formats for input values that you supply (for example, when you specify a value to be assigned to or compared to a date or time type).
  • Page 859 • By default, when 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-...
  • Page 860 Modes”, for more information. Before MySQL 5.0.2, the MySQL server performs only basic checking on the validity of a date: The ranges for year, month, and day are 1000 to 9999, 00 to 12, and 00 to 31, respectively. Any date containing parts not within these ranges is subject to conversion to '0000-00-00'.
  • Page 861 '11:12:00', not '00:11:12'. '11:12' MySQL interprets abbreviated values without colons using the assumption that the two rightmost digits represent seconds (that is, as elapsed time rather than as time of day). For example, you might think of as meaning...
  • Page 862 YEAR(4). Note that migration will become necessary at some point because support for data YEAR types with display values other than 4, most notably YEAR(2), is reduced as of MySQL 5.6.6 and will be removed entirely in a future release. Limitations...
  • Page 863 11.1.5.5. Automatic Initialization and Updating for TIMESTAMP Note In older versions of MySQL (prior to 4.1), the properties of the TIMESTAMP data type differed significantly in several ways from what is described in this section (see the MySQL 3.23, 4.0, 4.1 Reference Manual for details); these include syntax extensions which are deprecated in MySQL 5.1, and no longer...
  • Page 864 Date and Time Types if all other columns are set to their current values. To prevent the column from updating when other columns change, explicitly set it to its current value. To update the column even when other columns do not change, explicitly set it to the value it should have (for example, set it to [918]).
  • Page 865 Date and Time Types CREATE TABLE t1 ( ts TIMESTAMP DEFAULT 0 ON UPDATE CURRENT_TIMESTAMP • With an clause but no clause, the column is ON UPDATE CURRENT_TIMESTAMP DEFAULT automatically updated to the current timestamp. The default is 0 unless the column is defined with attribute, in which case the default is NULL.
  • Page 866 +-------------------------------------------+ 19473 | +-------------------------------------------+ However, when MySQL stores a value into a column of any temporal data type, it discards any fractional part and does not store it. 11.1.5.7. Conversion Between Date and Time Types To some extent, you can convert a value from one temporal type to another. However, there may be some alteration of the value or loss of information.
  • Page 867 Conversion of values: TIME MySQL converts a time value to a date or date-and-time value by parsing the string value of the time as a date or date-and-time. This is unlikely to be useful. For example, interpreted as a '23:12:31' date becomes '2032-12-31'.
  • Page 868: String Types

    The length can be specified as a value from 0 VARCHAR to 255 before MySQL 5.0.3, and 0 to 65,535 in 5.0.3 and later versions. The effective maximum length of a in MySQL 5.0.3 and later is subject to the maximum row size (65,535 bytes, which is VARCHAR shared among all columns) and the character set used.
  • Page 869 'abcd' The values shown as stored in the last row of the table apply only when not using strict mode; if MySQL is running in strict mode, values that exceed the column length are not stored, and an error results.
  • Page 870 Both inserted values remain unchanged when selected. \0\0' • Before MySQL 5.0.15, the pad value is space. Values are right-padded with space on insert, and trailing spaces are removed on select. Trailing spaces are ignored in comparisons, including ORDER operations.
  • Page 871 SQL mode. See Section 5.1.7, “Server SQL Modes”. Beginning with MySQL 5.0.60, truncation of excess trailing spaces from values to be inserted into TEXT columns always generates a warning, regardless of the SQL mode.
  • Page 872 In some cases, it may be desirable to store binary data such as media files in columns. BLOB TEXT You may find MySQL's string handling functions useful for working with such data. See Section 12.5, “String Functions”. For security and other reasons, it is usually preferable to do so using application...
  • Page 873 • The index value of the empty string error value is 0. This means that you can use the following statement to find rows into which invalid values were assigned: SELECT ENUM mysql> SELECT * FROM tbl_name WHERE enum_col=0; • The index of the value is NULL. NULL •...
  • Page 874 For example, ENUM you can retrieve numeric values from an column like this: ENUM mysql> SELECT enum_col+0 FROM tbl_name; If you store a number into an column, the number is treated as the index into the possible values, ENUM and the value stored is the enumeration member with that index.
  • Page 875 For binary or case-sensitive collations, lettercase is taken into account when assigning values to the column. MySQL stores values numerically, with the low-order bit of the stored value corresponding to the first set member. If you retrieve a value in a numeric context, the value retrieved has bits set corresponding to the set members that make up the column value.
  • Page 876: Data Type Default Values

    5 rows in set (0.04 sec) If you set a column to an unsupported value, the value is ignored and a warning is issued: mysql> INSERT INTO myset (col) VALUES ('a,d,d,s'); Query OK, 1 row affected, 1 warning (0.03 sec) mysql>...
  • Page 877 For nontransactional tables, an error occurs, but if this happens for the second or subsequent row of a multiple-row statement, the preceding rows will have been inserted. • If strict mode is not enabled, MySQL sets the column to the implicit default value for the column data type.
  • Page 878: Data Type Storage Requirements

    This sections includes some guideliness and information for the storage requirements for each data type supported by MySQL, including details for the internal format and the sizes used by storage engines that used a fixed size representation for different types. Information is listed by category or storage engine.
  • Page 879 This ndb_size.pl Perl script connects to a current MySQL (non-Cluster) database and creates a report on how much space that database would require if it used the storage engine. See Section 17.4.18, NDBCLUSTER “ndb_size.pl...
  • Page 880 Data Type Storage Required 1 byte YEAR For details about internal representation of temporal values, see MySQL Internals: Important Algorithms and Structures. Storage Requirements for String Types In the following table, represents the declared column length in characters for nonbinary string types and bytes for binary string types.
  • Page 881: Choosing The Right Type For A Column

    MEDIUMINT UNSIGNED type. Of the types that represent all the required values, this type uses the least amount of storage. Tables created in MySQL 5.0.3 and above use a new storage format for columns. All basic DECIMAL...
  • Page 882 Using Data Types from Other Database Engines To facilitate the use of code written for SQL implementations from other vendors, MySQL maps data types as shown in the following table. These mappings make it easier to import table definitions from other database systems into MySQL.
  • Page 883: Functions And Operators

    12.6.1. Arithmetic Operators ....................905 12.6.2. Mathematical Functions ..................907 12.7. Date and Time Functions ....................915 12.8. What Calendar Is Used By MySQL? ................. 934 12.9. Full-Text Search Functions ....................934 12.9.1. Natural Language Full-Text Searches ..............935 12.9.2. Boolean Full-Text Searches ................... 938 12.9.3.
  • Page 884: Function And Operator Reference

    However, spaces around function arguments are permitted. You can tell the MySQL server to accept spaces after function names by starting it with the [422] option.
  • Page 885 Function and Operator Reference Name Description [957] Repeatedly execute an expression BENCHMARK() [877] Check whether a value is within a range of values BETWEEN ... AND ... [886] Return a string containing binary representation of a number BIN() [948] Cast a string to a binary string BINARY [969] Return bitwise and...
  • Page 886 Function and Operator Reference Name Description Synonyms for NOW() CURRENT_TIMESTAMP(), [918] CURRENT_TIMESTAMP The authenticated user name and host name CURRENT_USER(), [959] CURRENT_USER [918] Return the current time CURTIME() [960] Return the default (current) database name DATABASE() [919] Add time values (intervals) to a date value DATE_ADD() [921] Format date as specified...
  • Page 887 Function and Operator Reference Name Description [923] Convert a day number to a date FROM_DAYS() [923] Format UNIX timestamp as a date FROM_UNIXTIME() [924] Return a date format string GET_FORMAT() [965] Get a named lock GET_LOCK() [876] Greater than or equal operator >= [876] Greater than operator...
  • Page 888 Function and Operator Reference Name Description Synonym for NOW() LOCALTIMESTAMP, [925] LOCALTIMESTAMP() [890] Return the position of the first occurrence of substring LOCATE() [911] Return the base-10 logarithm of the argument LOG10() [911] Return the base-2 logarithm of the argument LOG2() [910] Return the natural logarithm of the first argument...
  • Page 889 Function and Operator Reference Name Description [891] Return character code for leftmost character of the argument ORD() [956] Calculate and return a password string PASSWORD() [926] Add a period to a year-month PERIOD_ADD() [926] Return the number of months between periods PERIOD_DIFF() [911] Return the value of pi...
  • Page 890 Function and Operator Reference Name Description [972] Return the population standard deviation STDDEV() [927] Convert a string to a date STR_TO_DATE() [898] Compare two strings STRCMP() [928] A synonym for DATE_SUB() when invoked with three SUBDATE() arguments [894] Return the substring as specified SUBSTR() [894] Return a substring from a string before the specified number...
  • Page 891: Type Conversion In Expression Evaluation

    12.2. Type Conversion in Expression Evaluation When an operator is used with operands of different types, type conversion occurs to make the operands compatible. Some conversions occur implicitly. For example, MySQL automatically converts numbers to strings as necessary, and vice versa.
  • Page 892: Operators

    SELECT 0 = 'x6'; -> 1 For comparisons of a string column with a number, MySQL cannot use an index on the column to look up the value quickly. If is an indexed string column, the index cannot be used when...
  • Page 893: Operator Precedence

    Operator Precedence Name Description [882] Assign a value (as part of a statement, or as part of the clause in an statement) UPDATE [881] Assign a value [877] Check whether a value is within a range of values BETWEEN ... AND ... [948] Cast a string to a binary string BINARY...
  • Page 894: Comparison Functions And Operators

    [881]. Section 13.7.4, “SET Syntax”, and Section 9.4, “User-Defined Variables”, explain how MySQL determines which interpretation of should apply. The meaning of some operators depends on the SQL mode: • By default, [881] is a logical [881] operator. With...
  • Page 895 By default, string comparisons are not case sensitive and use the current character set. The default is (cp1252 West European), which also works well for English. latin1 • [875] Equal: mysql> SELECT 1 = 0; -> 0 mysql> SELECT '0' = 0; -> 1 mysql>...
  • Page 896 TRUE, FALSE, or UNKNOWN. boolean_value mysql> SELECT 1 IS TRUE, 0 IS FALSE, NULL IS UNKNOWN; -> 1, 1, 1 [876] syntax was added in MySQL 5.0.2. IS boolean_value • [876] IS NOT boolean_value Tests a value against a boolean value, where can be TRUE, FALSE, or UNKNOWN.
  • Page 897 Tests whether a value is NULL. mysql> SELECT 1 IS NULL, 0 IS NULL, NULL IS NULL; -> 0, 0, 1 To work well with ODBC programs, MySQL supports the following extra features when using [877]: NULL • If [493]...
  • Page 898 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' Before MySQL 5.0.13, [878] returns only if all arguments are NULL. As of GREATEST() NULL 5.0.13, it returns if any argument is NULL. NULL •...
  • Page 899 • If any argument is a nonbinary (character) string, the arguments are compared as nonbinary strings. • In all other cases, the arguments are compared as binary strings. Before MySQL 5.0.13, [879] returns only if all arguments are NULL. As of 5.0.13, it...
  • Page 900: Logical Operators

    SELECT ! 1+1; -> 1 The last example produces because the expression evaluates the same way as (!1)+1. Note that the precedence of the [880] operator changed in MySQL 5.0.2. See Section 12.3.1, “Operator Precedence”. • [880], [880] &&...
  • Page 901: Assignment Operators

    With a operand, the result is if the other operand is nonzero, and otherwise. NULL NULL If both operands are NULL, the result is NULL. mysql> SELECT 1 || 1; -> 1 mysql> SELECT 1 || 0; -> 1 mysql>...
  • Page 902: Control Flow Functions

    Control Flow Functions mysql> SELECT @var1:=COUNT(*) FROM t1; -> 4 mysql> SELECT @var1; -> 4 You can make value assignments using [881] in other statements besides SELECT, such as UPDATE, as shown here: mysql> SELECT @var1; -> 4 mysql> SELECT * FROM t1;...
  • Page 903 If there was no matching result value, the result after is returned, or if there is no part. ELSE NULL ELSE mysql> SELECT CASE 1 WHEN 1 THEN 'one' -> WHEN 2 THEN 'two' ELSE 'more' END; -> 'one' mysql> SELECT CASE WHEN 1>0 THEN 'true' ELSE 'false' END;...
  • Page 904: String Functions

    [884] is the more “general” of the two IFNULL(expr1,expr2) expressions, in the order STRING, REAL, or INTEGER. Consider the case of a table based on expressions or where MySQL must internally store a value returned by [884] in a IFNULL() temporary table: mysql>...
  • Page 905 String Functions Name Description [888] Return string at index number ELT() [888] Return a string such that for every bit set in the value bits, EXPORT_SET() you get an on string and for every unset bit, you get an off string [888] Return the index (position) of the first argument in the...
  • Page 906 [886] CHAR(N,... [USING charset_name]) [886] interprets each argument as an integer and returns a string consisting of the CHAR() characters given by the code values of those integers. values are skipped. NULL mysql> SELECT CHAR(77,121,83,81,'76'); -> 'MySQL' mysql> SELECT CHAR(77,77.3,'77.3');...
  • Page 907 String Functions -> 'MMM' As of MySQL 5.0.15, [886] arguments larger than 255 are converted into multiple CHAR() result bytes. For example, [886] is equivalent to [886], and CHAR(256) CHAR(1,0) [886] is equivalent to [886]: CHAR(256*256) CHAR(1,0,0) mysql> SELECT HEX(CHAR(1,0)), HEX(CHAR(256));...
  • Page 908 String Functions mysql> SELECT 'My' 'S' 'QL'; -> 'MySQL' • [888] CONCAT_WS(separator,str1,str2,...) [888] stands for Concatenate With Separator and is a special form of CONCAT_WS() [887]. The first argument is the separator for the rest of the arguments. The separator is CONCAT() added between the strings to be concatenated.
  • Page 909 Returns if either argument is NULL. This function does not work properly if the NULL first argument contains a comma (“,”) character. mysql> SELECT FIND_IN_SET('b','a,b,c,d'); -> 2 • [889] FORMAT(X,D) Formats the number to a format like '#,###,###.##', rounded to decimal places, and returns the result as a string.
  • Page 910 If the file does not exist or cannot be read because one of the preceding conditions is not satisfied, the function returns NULL. As of MySQL 5.0.19, the [442] system variable controls character_set_filesystem interpretation of file names that are given as literal strings.
  • Page 911 String Functions mysql> SET @str = BINARY 'New York'; mysql> SELECT LOWER(@str), LOWER(CONVERT(@str USING latin1)); +-------------+-----------------------------------+ | LOWER(@str) | LOWER(CONVERT(@str USING latin1)) | +-------------+-----------------------------------+ | New York | new york +-------------+-----------------------------------+ This function is multi-byte safe. • [891] LPAD(str,len,padstr) Returns the string str, left-padded with the string to a length of characters.
  • Page 912 [892] performs a case-sensitive match when searching for from_str. REPLACE() mysql> SELECT REPLACE('www.mysql.com', 'w', 'Ww'); -> 'WwWwWw.mysql.com' This function is multi-byte safe. • [892] REVERSE(str) Returns the string with the order of the characters reversed.
  • Page 913 Returns the string str, right-padded with the string to a length of characters. If padstr longer than len, the return value is shortened to characters. mysql> SELECT RPAD('hi',5,'?'); -> 'hi???' mysql> SELECT RPAD('hi',1,'?'); -> 'h' This function is multi-byte safe.
  • Page 914 (counting from the right) is returned. [894] performs a case-sensitive match when searching for delim. SUBSTRING_INDEX() mysql> SELECT SUBSTRING_INDEX('www.mysql.com', '.', 2); -> 'www.mysql' mysql> SELECT SUBSTRING_INDEX('www.mysql.com', '.', -2); -> 'mysql.com' This function is multi-byte safe.
  • Page 915: String Comparison Functions

    [889]. That is, it interprets each pair of characters in the argument as a hexadecimal HEX(str) number and converts it to the character represented by the number. The return value is a binary string. mysql> SELECT UNHEX('4D7953514C'); -> 'MySQL' mysql> SELECT 0x4D7953514C; -> 'MySQL' mysql> SELECT UNHEX(HEX('string'));...
  • Page 916 Per the SQL standard, [896] performs matching on a per-character basis, thus it can produce LIKE results different from the [875] comparison operator: mysql> SELECT 'ä' LIKE 'ae' COLLATE latin1_german2_ci; +-----------------------------------------+ | 'ä' LIKE 'ae' COLLATE latin1_german2_ci | +-----------------------------------------+ +-----------------------------------------+ mysql>...
  • Page 917 SELECT 10 LIKE '1%'; -> 1 Note Because MySQL uses C escape syntax in strings (for example, “\n” to represent a newline character), you must double any “\” that you use in [896] strings. For example, to search for “\n”, specify it as “\\n”.
  • Page 918 String Comparison Functions mysql> SELECT filename, filename LIKE '%\\\\' FROM t1; +--------------+-----------------------+ | filename | filename LIKE '%\\\\' | +--------------+-----------------------+ | C: | C:\ | C:\Programs | C:\Programs\ | +--------------+-----------------------+ • [898] expr NOT LIKE pat [ESCAPE 'escape_char'] This is the same as NOT (expr LIKE pat [ESCAPE 'escape_char']).
  • Page 919: Regular Expressions

    A regular expression is a powerful way of specifying a pattern for a complex search. MySQL uses Henry Spencer's implementation of regular expressions, which is aimed at conformance with POSIX 1003.2. MySQL uses the extended version to support pattern-matching operations...
  • Page 920 A regular expression for the [899] operator may use any of the following special characters REGEXP and constructs: • Match the beginning of a string. mysql> SELECT 'fo\nfo' REGEXP '^fo$'; -> 0 mysql> SELECT 'fofo' REGEXP '^fo'; -> 1 •...
  • Page 921 Regular Expressions • de|abc Match either of the sequences or abc. 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>...
  • Page 922 Regular Expressions Within a bracket expression (written using and ]), matches the sequence of characters of that collating element. is either a single character or a character name like newline. The characters following table lists the permissible character names. The following table shows the permissible character names and the characters that they match. For characters given as numeric values, the values are represented in octal.
  • Page 923 '^' underscore low-line grave-accent left-brace left-curly- bracket vertical-line right-brace right-curly- tilde bracket mysql> SELECT '~' REGEXP '[[.~.]]'; -> 1 mysql> SELECT '~' REGEXP '[[.tilde.]]'; -> 1 • [=character_class=] Within a bracket expression (written using and ]), represents an [=character_class=] equivalence class.
  • Page 924: Numeric Functions And Operators

    To use a literal instance of a special character in a regular expression, precede it by two backslash (\) characters. The MySQL parser interprets one of the backslashes, and the regular expression library interprets the other. For example, to match the string...
  • Page 925: Arithmetic Operators

    Arithmetic Operators Name Description [910] Return the natural logarithm of the first argument LOG() [906] Minus operator [911] Return the remainder MOD() [907] Modulo operator % or MOD [911] Return the value of pi PI() [906] Addition operator [912] Return the argument raised to the specified power POW() [912] Return the argument raised to the specified power...
  • Page 926 Arithmetic operators apply to numbers. For other types of values, alternative operations may be available. For example, to add date values, use [919]; see Section 12.7, “Date and DATE_ADD() Time Functions”. • [906] Addition: mysql> SELECT 3+5; -> 8 • [906] Subtraction: mysql> SELECT 3-5; -> -2 •...
  • Page 927: Mathematical Functions

    Integer division. Similar to [910], but is safe with values. Incorrect results may FLOOR() BIGINT occur for noninteger operands that exceed range. BIGINT mysql> SELECT 5 DIV 2; -> 2 • [907], [907] N % M N MOD M Modulo operation. Returns the remainder of divided by M.
  • Page 928 TRUNCATE() All mathematical functions return in the event of an error. NULL • [908] ABS(X) Returns the absolute value of X. mysql> SELECT ABS(2); -> 2 mysql> SELECT ABS(-32); -> 32 This function is safe to use with values. BIGINT •...
  • Page 929 Computes a cyclic redundancy check value and returns a 32-bit unsigned value. The result is NULL the argument is NULL. The argument is expected to be a string and (if possible) is treated as one if it is not. mysql> SELECT CRC32('MySQL'); -> 3259397556 mysql> SELECT CRC32('mysql'); -> 2501908538 •...
  • Page 930 Mathematical Functions -> 180 mysql> SELECT DEGREES(PI() / 2); -> 90 • [910] EXP(X) Returns the value of e (the base of natural logarithms) raised to the power of X. The inverse of this function is [910] (using a single argument only) or [910].
  • Page 931 -> 1.5 [911] returns NULL. MOD(N,0) • [911] PI() Returns the value of π (pi). The default number of decimal places displayed is seven, but MySQL uses the full double-precision value internally. mysql> SELECT PI(); -> 3.141593 mysql> SELECT PI()+0.000000000000000000;...
  • Page 932 Mathematical Functions • [912] POW(X,Y) Returns the value of raised to the power of Y. mysql> SELECT POW(2,2); -> 4 mysql> SELECT POW(2,-2); -> 0.25 • [912] POWER(X,Y) This is a synonym for [912]. POW() • [912] RADIANS(X) Returns the argument X, converted from degrees to radians. (Note that π radians equals 180 degrees.)
  • Page 933 2 | 0.37307905813035 | 3 | 0.14808605345719 | +------+------------------+ 3 rows in set (0.01 sec) The effect of using a nonconstant argument is undefined. As of MySQL 5.0.13, nonconstant arguments are not permitted. To obtain a random integer in the range <=...
  • Page 934 Mathematical Functions As of MySQL 5.0.3, [913] uses the following rules depending on the type of the first ROUND() argument: • For exact-value numbers, [913] uses the “round half away from zero” or “round toward ROUND() nearest” rule: A value with a fractional part of .5 or greater is rounded up to the next integer if positive or down to the next integer if negative.
  • Page 935: Date And Time Functions

    If is 0, the result has no decimal point or fractional part. can be negative to cause digits left of the decimal point of the value to become zero. mysql> SELECT TRUNCATE(1.223,1); -> 1.2 mysql> SELECT TRUNCATE(1.999,1); -> 1.9 mysql>...
  • Page 936 Date and Time Functions Name Description [924] Return a date format string GET_FORMAT() [924] Extract the hour HOUR() [925] Return the last day of the month for the argument LAST_DAY [925] Synonym for NOW() LOCALTIME(), LOCALTIME Synonym for NOW() LOCALTIMESTAMP, [925] LOCALTIMESTAMP() [925]...
  • Page 937 -> '2008-02-02' mysql> SELECT ADDDATE('2008-01-02', INTERVAL 31 DAY); -> '2008-02-02' When invoked with the form of the second argument, MySQL treats it as an integer number of days days to be added to expr. mysql> SELECT ADDDATE('2008-01-02', 31); -> '2008-02-02' •...
  • Page 938 CONVERT_TZ() from_tz time zone given by and returns the resulting value. Time zones are specified as described in to_tz Section 10.6, “MySQL Server Time Zone Support”. This function returns if the arguments are NULL invalid. If the value falls out of the supported range of the...
  • Page 939 'DAYS HOURS:MINUTES' DAY_HOUR 'DAYS HOURS' YEAR_MONTH 'YEARS-MONTHS' The values are available beginning with MySQL 5.0.0. QUARTER WEEK The return value depends on the arguments: • if the first argument is a (or TIMESTAMP) value, or if the first argument is a...
  • Page 940 If you specify a value like '1:10', MySQL assumes that the days and hours parts are missing and the value represents minutes and seconds. In other words, is interpreted in such a way that it is equivalent to '1:10' DAY_SECOND MINUTE_SECOND.
  • Page 941 CAST() used. To treat as 1 hour, 5 minutes, cast it to a value with a single fractional digit: DECIMAL mysql> SELECT CAST(6/4 AS DECIMAL(3,1)); -> 1.5 mysql> SELECT DATE_ADD('1970-01-01 12:00:00', -> INTERVAL CAST(6/4 AS DECIMAL(3,1)) HOUR_MINUTE);...
  • Page 942 A literal “%” character x, for any “x” not listed above Ranges for the month and day specifiers begin with zero due to the fact that MySQL permits the storing of incomplete dates such as '2014-00-00'. As of MySQL 5.0.25, the language used for day and month names and abbreviations is controlled...
  • Page 943 Date and Time Functions • [923] DAYNAME(date) Returns the name of the weekday for date. As of MySQL 5.0.25, the language used for the name is controlled by the value of the [462] system variable (Section 10.7, “MySQL Server lc_time_names Locale Support”).
  • Page 944 [921] function. DATE_FORMAT() mysql> SELECT FROM_UNIXTIME(1196440219); -> '2007-11-30 10:30:19' mysql> SELECT FROM_UNIXTIME(1196440219) + 0; -> 20071130103019.000000 mysql> SELECT FROM_UNIXTIME(UNIX_TIMESTAMP(), ->...
  • Page 945 Date and Time Functions mysql> SELECT HOUR('10:05:03'); -> 10 mysql> SELECT HOUR('272:59:59'); -> 272 • [925] LAST_DAY(date) Takes a date or datetime value and returns the corresponding value for the last day of the month. Returns if the argument is invalid.
  • Page 946 SELECT MONTH('2008-02-03'); -> 2 • [926] MONTHNAME(date) Returns the full name of the month for date. As of MySQL 5.0.25, the language used for the name is controlled by the value of the [462] system variable (Section 10.7, “MySQL Server...
  • Page 947 [927] returns and, as STR_TO_DATE() NULL of MySQL 5.0.3, produces a warning. The server scans attempting to match to it. The format string can contain literal format characters and format specifiers beginning with %. Literal characters in must match literally format in str.
  • Page 948 Returns the current date and time as a value in 'YYYY-MM-DD HH:MM:SS' format, depending on whether the function is used in a string or numeric YYYYMMDDHHMMSS.uuuuuu context. As of MySQL 5.0.12, [928] returns the time at which it executes. This differs from SYSDATE() the behavior for...
  • Page 949 (microseconds), SECOND, MINUTE, HOUR, DAY, WEEK, MONTH, QUARTER, or YEAR. FRAC_SECOND Beginning with MySQL 5.0.60, it is possible to use in place of with this MICROSECOND FRAC_SECOND function, and is deprecated.
  • Page 950 Date and Time Functions mysql> SELECT TIMESTAMPADD(MINUTE,1,'2003-01-02'); -> '2003-01-02 00:01:00' mysql> SELECT TIMESTAMPADD(WEEK,1,'2003-01-02'); -> '2003-01-09' [929] is available as of MySQL 5.0.0. TIMESTAMPADD() • [930] TIMESTAMPDIFF(unit,datetime_expr1,datetime_expr2) Returns – datetime_expr1, where datetime_expr2 datetime_expr1 datetime_expr2 are date or datetime expressions. One expression may be a date and the other a datetime; a date value is treated as a datetime having the time part where necessary.
  • Page 951 See Section 12.8, “What Calendar Is Used By MySQL?”, for details. Remember that MySQL converts two-digit year values in dates to four-digit form using the rules in Section 11.1.5, “Date and Time Types”. For example, are seen...
  • Page 952 [923] will map that value back to only one of the original FROM_UNIXTIME() values. Here is an example, using values in the time zone: TIMESTAMP TIMESTAMP mysql> SELECT UNIX_TIMESTAMP('2005-03-27 03:00:00'); +---------------------------------------+ | UNIX_TIMESTAMP('2005-03-27 03:00:00') | +---------------------------------------+ 1111885200 | +---------------------------------------+ mysql>...
  • Page 953 SELECT WEEK('2008-02-20',1); -> 8 mysql> SELECT WEEK('2008-12-31',1); -> 53 Note that if a date falls in the last week of the previous year, MySQL returns if you do not use 2, 3, 6, or as the optional argument: mode mysql>...
  • Page 954: What Calendar Is Used By Mysql

    A calendar applied to dates when it was not actually in use is called proleptic. Thus, if we assume there was never a cutover and Gregorian rules always rule, we have a proleptic Gregorian calendar. This is what is used by MySQL, as is required by standard SQL. For this reason, dates prior to the cutover stored as MySQL values must be adjusted to compensate for the difference.
  • Page 955: Natural Language Full-Text Searches

    WHERE MATCH (title,body) AGAINST ('database'); +----+-------------------+------------------------------------------+ | id | title | body +----+-------------------+------------------------------------------+ 5 | MySQL vs. YourSQL | In the following database comparison ... | 1 | MySQL Tutorial | DBMS stands for DataBase ... +----+-------------------+------------------------------------------+ 2 rows in set (0.00 sec)
  • Page 956 (rows) that contain a particular word. To simply count matches, you could use a query like this: mysql> SELECT COUNT(*) FROM articles ->...
  • Page 957 For example, although the word “MySQL” is present in every row of table shown earlier, a search for the word produces no results: articles mysql>...
  • Page 958: Boolean Full-Text Searches

    Boolean Full-Text Searches The search result is empty because the word “MySQL” is present in at least 50% of the rows. As such, it is effectively treated as a stopword. For large data sets, this is the most desirable behavior: A natural language query should not return every second row from a 1GB table.
  • Page 959 As of MySQL 5.0.3, nonword characters need not be matched exactly: Phrase searching requires only that matches contain exactly the same words as the phrase and in...
  • Page 960: Full-Text Searches With Query Expansion

    Thus, if one of these documents contains the word “databases” and the word “MySQL”, the second search finds the documents that contain the word “MySQL” even if they do not contain the word “database”. The following example shows this difference: mysql>...
  • Page 961: Full-Text Stopwords

    The following table shows the default list of full-text stopwords. In a MySQL source distribution, you can find this list in the file.
  • Page 962 Full-Text Stopwords below beside besides best better between beyond both brief c'mon came can't cannot cant cause causes certain certainly changes clearly come comes concerning consequently consider considering contain containing contains corresponding could couldn't course currently definitely described despite didn't different does doesn't...
  • Page 963 Full-Text Stopwords near nearly necessary need needs neither never nevertheless next nine nobody none noone normally nothing novel nowhere obviously often okay once ones only onto other others otherwise ought ours ourselves outside over overall particular particularly perhaps placed please plus possible presumably...
  • Page 964: Full-Text Restrictions

    Source”. Note that full-text search is carefully tuned for the most effectiveness. Modifying the default behavior in most cases can actually decrease effectiveness. Do not alter the MySQL sources unless you know what you are doing. Most full-text variables described in this section must be set at server startup time. A server restart is required to change them;...
  • Page 965 #define GWS_IN_USE GWS_PROB Change that line to this: #define GWS_IN_USE GWS_FREQ Then recompile MySQL. There is no need to rebuild the indexes in this case. Note By making this change, you severely decrease MySQL's ability to provide adequate relevance values for the [934] function.
  • Page 966: Adding A Collation For Full-Text Indexing

    To rebuild FULLTEXT the indexes in this case, it is sufficient to do a repair operation: QUICK mysql> REPAIR TABLE tbl_name QUICK; Alternatively, use with the options to drop and re-create...
  • Page 967 </map> </ctype> 4. Restart the server. 5. To employ the new collation, include it in the definition of columns that are to use it: mysql> DROP TABLE IF EXISTS t1; Query OK, 0 rows affected (0.13 sec) mysql> CREATE TABLE t1 ( ->...
  • Page 968: Cast Functions And Operators

    [948] is shorthand for [948]. BINARY str CAST(str AS BINARY) Note that in some contexts, if you cast an indexed column to BINARY, MySQL is not able to use the index efficiently. • [948] CAST(expr AS type) [948]...
  • Page 969 [948] is ODBC syntax. CONVERT() [948] with is used to convert data between different character sets. In MySQL, CONVERT() USING transcoding names are the same as the corresponding character set names. For example, this statement converts the string in the default character set to the corresponding string in the...
  • Page 970: Bit Functions

    For information about implicit conversion of numbers to strings, see Section 12.2, “Type Conversion in Expression Evaluation”. MySQL supports arithmetic with both signed and unsigned 64-bit values. If you are using numeric operators (such as [906] [906]) and one of the operands is an unsigned integer, the result is unsigned by default (see Section 12.6.1, “Arithmetic...
  • Page 971 Bitwise OR [951] Bitwise XOR [951] Left shift << [951] Right shift >> MySQL uses (64-bit) arithmetic for bit operations, so these operators have a maximum range BIGINT of 64 bits. • [951] Bitwise OR: mysql> SELECT 29 | 15;...
  • Page 972: Encryption And Compression Functions

    Encryption and Compression Functions mysql> SELECT 5 & ~1; -> 4 The result is an unsigned 64-bit integer. • [952] BIT_COUNT(N) Returns the number of bits that are set in the argument N. mysql> SELECT BIT_COUNT(29), BIT_COUNT(b'101010'); -> 4, 3 12.12.
  • Page 973 Passwords or other sensitive values supplied as arguments to encryption functions are sent in plaintext to the MySQL server unless an SSL connection is used. Also, such values will appear in any MySQL logs to which they are written. To avoid these types of exposure, applications can encrypt sensitive values on the client side before sending them to the server.
  • Page 974 [954] COMPRESS(string_to_compress) Compresses a string and returns the result as a binary string. This function requires MySQL to have been compiled with a compression library such as zlib. Otherwise, the return value is always NULL. The compressed string can be uncompressed with [957].
  • Page 975 The first key is the default key that is used if you do not specify any key argument to [954]. DES_ENCRYPT() You can tell MySQL to read new key values from the key file with the FLUSH DES_KEY_FILE statement. This requires the [577] privilege.
  • Page 976 [956] as a binary string, and is intended to permit you PASSWORD() to reset passwords for any pre-4.1 clients that need to connect to your version 5.0 MySQL server without locking them out. See Section 6.1.2.4, “Password Hashing in MySQL”.
  • Page 977: Information Functions

    [954] function. If the argument is not a COMPRESS() compressed value, the result is NULL. This function requires MySQL to have been compiled with a compression library such as zlib. Otherwise, the return value is always NULL. mysql> SELECT UNCOMPRESS(COMPRESS('any string'));...
  • Page 978 It may BENCHMARK() expr count be used to time how quickly MySQL processes the expression. The result value is always 0. The intended use is from within the client, which reports query execution times: mysql mysql> SELECT BENCHMARK(1000000,ENCODE('hello','goodbye'));...
  • Page 979 [959] CURRENT_USER CURRENT_USER() Returns the user name and host name combination for the MySQL account that the server used to authenticate the current client. This account determines your access privileges. The return value is a string in the character set.
  • Page 980 In the latter case, [959] returns the object's invoker. INVOKER CURRENT_USER() This applies to stored programs as of MySQL 5.0.10 and to views as of MySQL 5.0.24. (For older versions, [959] returns the account for the object's invoker.) CURRENT_USER()
  • Page 981 • For stored functions and triggers that change the value, the value is restored when the function or trigger ends, so following statements do not see a changed value. (Before MySQL 5.0.12, the value is not restored and following statements do see a changed value.)
  • Page 982 -> (NULL, 'Mary'), (NULL, 'Jane'), (NULL, 'Lisa'); Query OK, 3 rows affected (0.00 sec) Records: 3 Duplicates: 0 Warnings: 0 mysql> SELECT * FROM t; +----+------+ | id | name | +----+------+ 1 | Bob 2 | Mary | 3 | Jane |...
  • Page 983 [961]. This can be used to simulate sequences: LAST_INSERT_ID() 1. Create a table to hold the sequence counter and initialize it: mysql> CREATE TABLE sequence (id INT NOT NULL); mysql> INSERT INTO sequence VALUES (0);...
  • Page 984: Miscellaneous Functions

    [964]. SYSTEM_USER() USER() • [964] USER() Returns the current MySQL user name and host name as a string in the character set. utf8 mysql> SELECT USER(); -> 'davida@localhost' The value indicates the user name you specified when connecting to the server, and the client host from which you connected.
  • Page 985 Defines the values to be used during an INSERT VALUES() • [965] DEFAULT(col_name) Returns the default value for a table column. Starting with MySQL 5.0.2, an error results if the column has no default value. mysql> UPDATE t SET i = DEFAULT(i)+1 WHERE id < 100; •...
  • Page 986 If the blocked client terminates, timeout its thread does not die until the lock request times out. This is a known bug (fixed in MySQL 5.5). • [966] INET_ATON(expr) Given the dotted-quad representation of an IPv4 network address as a string, returns an integer that represents the numeric value of the address in network byte order (big endian).
  • Page 987 14 | +--------+ This function was added in MySQL 5.0.12. It is for internal use only. The server uses it when writing statements from stored programs that contain references to local program variables, as described Section 18.6, “Binary Logging of Stored Programs”, You might see this function in the output from...
  • Page 988: Functions And Modifiers For Use With Group By Clauses

    In this case, spatial uniqueness cannot be guaranteed. Nevertheless, a collision should have very low probability. Currently, the MAC address of an interface is taken into account only on FreeBSD and Linux. On other operating systems, MySQL uses a randomly generated 48-bit number. mysql> SELECT UUID();...
  • Page 989 • [969] AVG([DISTINCT] expr) Returns the average value of expr. The option can be used as of MySQL 5.0.3 to return DISTINCT the average of the distinct values of expr. [969] returns if there were no matching rows.
  • Page 990 SELECT COUNT(DISTINCT results) FROM student; In MySQL, you can obtain the number of distinct expression combinations that do not contain by giving a list of expressions. In standard SQL, you would have to do a concatenation of all NULL expressions inside [970].
  • Page 991 MAX() ENUM than by the string's relative position in the set. This differs from how compares them. This ORDER BY is expected to be rectified in a future MySQL release. • [971] MIN([DISTINCT] expr) Returns the minimum value of expr.
  • Page 992: Group By Modifiers

    Returns the population standard variance of expr. It considers rows as the whole population, not as a sample, so it has the number of rows as the denominator. This function was added in MySQL 5.0.3. Before 5.0.3, you can use [972], which is equivalent but is not standard SQL.
  • Page 993 VARCHAR(20) NOT NULL, product VARCHAR(32) NOT NULL, profit The table's contents can be summarized per year with a simple like this: GROUP BY mysql> SELECT year, SUM(profit) FROM sales GROUP BY year; +------+-------------+ | year | SUM(profit) | +------+-------------+ | 2000 |...
  • Page 994 NULL. Other Considerations When using ROLLUP The following items list some behaviors specific to the MySQL implementation of ROLLUP: When you use ROLLUP, you cannot also use an clause to sort the results. In other words, ORDER BY are mutually exclusive. However, you still have some control over sort order.
  • Page 995: Mysql Extensions To Group By

    GROUP BY named in the clause. This means that the preceding query is legal in MySQL. You can use GROUP BY this feature to get better performance by avoiding unnecessary column sorting and grouping. However,...
  • Page 996: Spatial Extensions

    This specification is available from the OGC Web site at http://www.opengis.org/ docs/99-049.pdf. • If you have questions or concerns about the use of the spatial extensions to MySQL, you can discuss them in the GIS forum: http://forums.mysql.com/list.php?23. 12.16.1. Introduction to MySQL Spatial Support MySQL implements spatial extensions following the specification of the Open Geospatial Consortium (OGC).
  • Page 997: The Opengis Geometry Model

    It contains additional information relevant to this chapter. MySQL implements a subset of the SQL with Geometry Types environment proposed by OGC. This term refers to an SQL environment that has been extended with a set of geometry types. A geometry- valued SQL column is implemented as a column that has a geometry type.
  • Page 998 • Its SRID, or Spatial Reference Identifier. This value identifies the geometry's associated Spatial Reference System that describes the coordinate space in which the geometry object is defined. In MySQL, the SRID value is just an integer associated with the geometry value. All calculations are done assuming Euclidean (planar) geometry.
  • Page 999 The OpenGIS Geometry Model • Its coordinates in its Spatial Reference System, represented as double-precision (8-byte) numbers. All nonempty geometries include at least one pair of (X,Y) coordinates. Empty geometries contain no coordinates. Coordinates are related to the SRID. For example, in different coordinate systems, the distance between two objects may differ even when objects have the same coordinates, because the distance on the planar coordinate system and the distance on the geocentric system (coordinates on the Earth's surface) are different things.
  • Page 1000 The OpenGIS Geometry Model • The boundary of a is the empty set. Point 12.16.2.4. Class Curve is a one-dimensional geometry, usually represented by a sequence of points. Particular Curve subclasses of define the type of interpolation between points. is a noninstantiable class. Curve Curve Properties...
  • Page 1001 The OpenGIS Geometry Model Examples Polygon • On a region map, objects could represent forests, districts, and so on. Polygon Assertions Polygon • The boundary of a consists of a set of objects (that is, objects Polygon LinearRing LineString that are both simple and closed) that make up its exterior and interior boundaries. •...
  • Page 1002 The OpenGIS Geometry Model • A is simple if and only if all of its elements are simple; the only intersections between MultiCurve any two elements occur at points that are on the boundaries of both elements. • A boundary is obtained by applying the “mod 2 union rule” (also known as the “odd- MultiCurve even rule”): A point is in the boundary of a if it is in the boundaries of an odd number of...
  • Page 1003: Supported Spatial Data Formats

    • Well-Known Text (WKT) format • Well-Known Binary (WKB) format Internally, MySQL stores geometry values in a format that is not identical to either WKT or WKB format. 12.16.3.1. Well-Known Text (WKT) Format The Well-Known Text (WKT) representation of Geometry is designed to exchange geometry data in ASCII form.
  • Page 1004: Creating A Spatially Enabled Mysql Database

    OpenGIS specification. 12.16.4. Creating a Spatially Enabled MySQL Database This section describes the data types you can use for representing spatial data in MySQL, and the functions available for creating and retrieving spatial values. 12.16.4.1. MySQL Spatial Data Types MySQL has data types that correspond to OpenGIS classes.
  • Page 1005 OpenGIS standard, and using MySQL-specific functions. 12.16.4.2.1. Creating Geometry Values Using WKT Functions MySQL provides a number of functions that take as arguments a Well-Known Text representation and, optionally, a spatial reference system identifier (SRID). They return the corresponding geometry.

This manual is also suitable for:

Mysql 5.0

Table of Contents