mysql - the MySQL command-line toolhtml
mysql [options] db_namemysql
mysql is a simple SQL shell with input line editing capabilities. It supports interactive and noninteractive use. When used interactively, query results are presented in an ASCII-table format. When used noninteractively (for example, as a filter), the result is presented in tab-separated format. The output format can be changed using command options.linux
If you have problems due to insufficient memory for large result sets, use the --quick
option. This forces mysql to retrieve results from the server a row at a time rather than retrieving the entire result set and buffering it in memory before displaying it. This is done by returning the result set using the mysql_use_result()
C API function in the client/server library rather than mysql_store_result()
.sql
Using mysql is very easy. Invoke it from the prompt of your command interpreter as follows:shell
shell> mysql db_name
Or:api
shell> mysql --user=user_name --password=your_password db_name
Then type an SQL statement, end it with ";
", \g
, or \G
and press Enter
.
As of MySQL 5.1.10, typing Control+C
causes mysql to attempt to kill the current statement. If this cannot be done, or Control+C is typed again before the statement is killed, mysql exits. Previously, Control+C caused mysql to exit in all cases.session
You can execute SQL statements in a script file (batch file) like this:app
shell> mysql db_name < script.sql > output.tab
On Unix, the mysql client writes a record of executed statements to a history file. See the section called "MYSQL HISTORY FILE".less
mysql supports the following options, which can be specified on the command line or in the [mysql] and [client] groups of an option file. mysql also supports the options for processing option files described at Section 4.2.3.4, "Command-Line Options that Affect Option-File Handling".socket
--help, -?
--auto-rehash
Enable automatic rehashing. This option is on by default, which enables database, table, and column name completion. Use --disable-auto-rehash
to disable rehashing. That causes mysql to start faster, but you must issue the rehash command if you want to use name completion.
To complete a name, enter the first part and press Tab. If the name is unambiguous, mysql completes it. Otherwise, you can press Tab again to see the possible names that begin with what you have typed so far. Completion does not occur if there is no default database.
--batch, -B
Print results using tab as the column separator, with each row on a new line. With this option, mysql does not use the history file.
Batch mode results in nontabular output format and escaping of special characters. Escaping may be disabled by using raw mode; see the description for the --raw
option.
--bind-address=ip_address
On a computer having multiple network interfaces, this option can be used to select which interface is employed when connecting to the MySQL server.
This option is supported only in the version of the mysql client that is supplied with MySQL Cluster, beginning with MySQL Cluster NDB 6.3.4. It is not available in standard MySQL 5.1 releases.
--character-sets-dir=path
--column-names
--column-type-info, -m
--debug-info
.) The -m
short option was added in MySQL 5.1.21.--comments, -c
Whether to preserve comments in statements sent to the server. The default is --skip-comments
(discard comments), enable with --comments
(preserve comments). This option was added in MySQL 5.1.23.
--compress, -C
--database=db_name, -D db_name
--debug[=debug_options], -# [debug_options]
d:t:o,file_name
'. The default is 'd:t:o,/tmp/mysql.trace
'.--debug-check
--debug-info, -T
Before MySQL 5.1.14, this option prints debugging information and memory and CPU usage statistics when the program exits, and also causes display of result set metadata during execution. As of MySQL 5.1.14, use --column-type-info
to display result set metadata.
--default-character-set=charset_name
Use charset_name as the default character set for the client and connection.
A common issue that can occur when the operating system uses utf8
or another multi-byte character
set is that output from the mysql client is formatted incorrectly, due to the fact that the MySQL client uses the latin1
character set by default. You can usually fix such issues by using this option to force the client to use the system character set instead.
See Section 10.5, "Character Set Configuration", for more information.
--delimiter=str
--disable-named-commands
MYSQL COMMANDS
".--execute=statement, -e statement
--batch
. See Section 4.2.3.1, "Using Options on the Command Line", for some examples. With this option, mysql does not use the history file.--force, -f
--host=host_name, -h host_name
--html, -H
--ignore-spaces, -i
IGNORE_SPACE SQL
mode (see Section 5.1.7, "Server SQL Modes").--line-numbers
--skip-line-numbers
.--local-infile[={0|1}]
LOCAL
capability for LOAD DATA INFILE
. With no value, the option enables LOCAL
. The option may be given as --local-infile=0
or --local-infile=1
to explicitly disable or enable LOCAL
. Enabling LOCAL
has no effect if the server does not also support it.--named-commands, -G
quit
and \q
both are recognized. Use --skip-named-commands
to disable named commands. See the section called "MYSQL COMMANDS".--no-auto-rehash, -A
-skip-auto-rehash
. See the description for --auto-rehash
.--no-beep, -b
--no-named-commands, -g
--disable-named-commands
instead. --no-named-commands
is removed in MySQL 5.5.--no-pager
--skip-pager
. See the --pager
option. --no-pager
is removed in MySQL 5.5.--no-tee
Deprecated form of --skip-tee
. See the --tee
option. --no-tee
is removed in MySQL 5.5.
--one-database, -o
DELETE FROM db2.t2; USE db2; DROP TABLE db1.t1; CREATE TABLE db1.t1 (i INT); USE db1; INSERT INTO t1 (i) VALUES(1); CREATE TABLE db2.t1 (j INT);
--force
--one-database
db1, mysql handles the input as follows:
DELETE
statement is executed because the default database is db1, even though the statement names a table in a different database.DROP TABLE
and CREATE TABLE
statements are not executed because the default database is not db1, even though the statements name a table in db1.INSERT
and CREATE TABLE
statements are executed because the default database is db1, even though the CREATE TABLE statement names a table in a different database.--pager[=command]
PAGER
environment variable. Valid pagers are less, more, cat [> filename]
, and so forth. This option works only on Unix and only in interactive mode. To disable paging, use --skip-pager
. the section called "MYSQL COMMANDS", discusses output paging further.--password[=password], -p[password]
-p
), you cannot have a space between the option and the password. If you omit the password value following the --password
or -p
option on the command line, mysql prompts for one.--pipe, -W
named-pipe
connections.--port=port_num, -P port_num
--prompt=format_str
mysql>
. The special sequences that the prompt can contain are described in the section called "MYSQL COMMANDS".--protocol={TCP|SOCKET|PIPE|MEMORY}
--quick, -q
--raw, -r
For tabular output, the "boxing" around columns enables one column value to be distinguished from another. For nontabular output (such as is produced in batch mode or when the --batch
or --silent
option is given), special characters are escaped in the output so they can be identified easily. Newline
, tab
, NUL
, and backslash
are written as \n
, \t
, \0
, and \\
. The --raw
option disables this character escaping.
% mysql mysql> SELECT CHAR(92); +----------+ | CHAR(92) | +----------+ | \ | +----------+ % mysql -s mysql> SELECT CHAR(92); CHAR(92) \\ % mysql -s -r mysql> SELECT CHAR(92); CHAR(92) \
--reconnect
--safe-updates, --i-am-a-dummy, -U
UPDATE
and DELETE
statements that specify which rows to modify by using key values. If you have set this option in an option file, you can override it by using --safe-updates
on the command line. See the section called "MYSQL TIPS", for more information about this option.--secure-auth
--show-warnings
--sigint-ignore
SIGINT
signals (typically the result of typing Control+C
).--silent, -s
--raw
option.--skip-column-names, -N
--skip-line-numbers, -L
--socket=path, -S path
--ssl*
--table, -t
Display output in table format. This is the default for interactive use, but can be used to produce table output in batch mode.
--tee=file_name
--unbuffered, -n
--user=user_name, -u user_name
--verbose, -v
-v
-v
-v
produces table output format even in batch mode.)--version, -V
--vertical, -E
\G
.--wait, -w
If the connection cannot be established, wait and retry instead of aborting.
--xml, -X
<field name="column_name">NULL</field>
--xml
is used with mysql matches that of mysqldump --xml
. See mysqldump(1) for details.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-instance"> <row> <field name="Variable_name">version</field> <field name="Value">5.0.40-debug</field> </row> <row> <field name="Variable_name">version_comment</field> <field name="Value">Source distribution</field> </row> <row> <field name="Variable_name">version_compile_machine</field> <field name="Value">i686</field> </row> <row> <field name="Variable_name">version_compile_os</field> <field name="Value">suse-linux-gnu</field> </row> </resultset>
(See Bug #25946.)
You can also set the following variables by using --var_name=value
. The --set-variable
format is deprecated and is removed in MySQL 5.5.
connect_timeout
max_allowed_packet
max_join_size
--safe-updates
. (Default value is 1,000,000.)net_buffer_length
select_limit
SELECT
statements when using --safe-updates
. (Default value is 1,000.)Mysql Commands
mysql sends each SQL statement that you issue to the server to be executed. There is also a set of commands that mysql itself interprets. For a list of these commands, type help
or \h
at the mysql> prompt:
mysql> help List of all MySQL commands: Note that all text commands must be first on line and end with ';' ? (\?) Synonym for 'help'. clear (\c) Clear command. connect (\r) Reconnect to the server. Optional arguments are db and host. delimiter (\d) Set statement delimiter. edit (\e) Edit command with $EDITOR. ego (\G) Send command to mysql server, display result vertically. exit (\q) Exit mysql. Same as quit. go (\g) Send command to mysql server. help (\h) Display this help. nopager (\n) Disable pager, print to stdout. notee (\t) Don't write into outfile. pager (\P) Set PAGER [to_pager]. Print the query results via PAGER. print (\p) Print current command. prompt (\R) Change your mysql prompt. quit (\q) Quit mysql. rehash (\#) Rebuild completion hash. source (\.) Execute an SQL script file. Takes a file name as an argument. status (\s) Get status information from the server. system (\!) Execute a system shell command. tee (\T) Set outfile [to_outfile]. Append everything into given outfile. use (\u) Use another database. Takes database name as argument. charset (\C) Switch to another charset. Might be needed for processing binlog with multi-byte charsets. warnings (\W) Show warnings after every statement. nowarning (\w) Don't show warnings after every statement.
For server side help, type 'help contents'
Each command has both a long and short form. The long form is not case sensitive; the short form is. The long form can be followed by an optional semicolon terminator, but the short form should not.
The use of short-form commands within multi-line /* ... */ comments is not supported.
help [arg], \h [arg], \? [arg], ? [arg]
charset charset_name, \C charset_name
SET NAMES
statement. This enables the character set to remain synchronized on the client and server if mysql is run with auto-reconnect enabled (which is not recommended), because the specified character set is used for reconnects. This command was added in MySQL 5.1.7.clear, \c
connect [db_name host_name]], \r [db_name host_name]]
delimiter str, \d str
edit, \e
ego, \G
exit, \q
go, \g
nopager, \n
notee, \t
nowarning, \w
pager [command], \P [command]
--pager
option when you invoke mysql, it is possible to browse or search query results in interactive mode with Unix programs such as less, more, or any other similar program. If you specify no value for the option, mysql checks the value of the PAGER
environment variable and sets the pager to that. Pager functionality works only in interactive mode.print, \p
prompt [str], \R [str]
quit, \q
rehash, \#
--auto-rehash
option.)source file_name, \. file_name
status, \s
--safe-updates
mode, status also prints the values for the mysql variables that affect your queries.system command, \! command
tee [file_name], \T [file_name]
--tee
option when you invoke mysql, you can log statements and their output. All the data displayed on the screen is appended into a given file. This can be very useful for debugging purposes also. mysql flushes results to the file after each statement, just before it prints its next prompt. Tee functionality works only in interactive mode.use db_name, \u db_name
warnings, \W
mysql> pager cat > /tmp/log.txt You can also pass any options for the program that you want to use as your pager: mysql> pager less -n -i -S
In the preceding example, note the -S
option. You may find it very useful for browsing wide query results. Sometimes a very wide result set is difficult to read on the screen. The -S
option to less can make the result set much more readable because you can scroll it horizontally using the left-arrow and right-arrow keys. You can also use -S interactively within less to switch the horizontal-browse mode on and off. For more information, read the less manual page:
shell> man less
The -F and -X options may be used with less to cause it to exit if output fits on one screen, which is convenient when no scrolling is necessary:
mysql> pager less -n -i -S -F -X
You can specify very complex pager commands for handling query output:
mysql> pager cat | tee /dr1/tmp/res.txt \ | tee /dr2/tmp/res2.txt | less -n -i -S
/dr1
and /dr2
, yet still display the results onscreen using less.shell> export MYSQL_PS1="(\u@\h) [\d]> "
shell> mysql --prompt="(\u@\h) [\d]> " (user@host) [database]>
[mysql] prompt=(\\u@\\h) [\\d]>\\_
\s
is interpreted as a space rather than as the current seconds value. The following example shows how to define a prompt within an option file to include the current time in HH:MM:SS>
format:[mysql] prompt="\\r:\\m:\\s> "
prompt
(or \R
) command. 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> Mysql History File
.mysql_history
and is created in your home directory. To specify a different file, set the value of the MYSQL_HISTFILE environment variable..mysql_history
should be protected with a restrictive access mode because sensitive information might be written to it, such as the text of SQL statements that contain passwords. See Section 6.1.2.1, "End-User Guidelines for Password Security".--batch
or --execute
option..mysql_history
as a symbolic link to /dev/null
:shell> ln -s /dev/null $HOME/.mysql_history You need do this only once. Mysql Server-side Help mysql> help search_string
mysql> help me Nothing found
mysql> help contents
help <item>
', where <item
> is one of theAccount Management Administration Data Definition Data Manipulation Data Types Functions Functions and Modifiers for Use with GROUP BY Geographic Features Language Structure Plugins Storage Engines Stored Routines Table Maintenance Transactions Triggers
If the search string matches multiple items, mysql shows a list of matching topics:
mysql> help logs
SHOW SHOW BINARY LOGS SHOW ENGINE SHOW LOGS
mysql> help show binary logs Name: 'SHOW BINARY LOGS' Description: Syntax: SHOW BINARY LOGS SHOW MASTER LOGS Lists the binary log files on the server. This statement is used as part of the procedure described in [purge-binary-logs], that shows how to determine which logs can be purged. mysql> SHOW BINARY LOGS; +---------------+-----------+ | Log_name | File_size | +---------------+-----------+ | binlog.000015 | 724935 | | binlog.000016 | 733481 | +---------------+-----------+
shell> mysql db_name
shell> mysql db_name < text_file If you place a USE db_name statement as the first statement in the file, it is unnecessary to specify the 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 source command or \. command: mysql> source file_name mysql> \. file_name Sometimes you may want your script to display progress information to the user. For this you can insert statements like this: SELECT '<info_to_display>' AS ' '; The statement shown outputs <info_to_display>.
--default-character-set=utf8
.mysql> SELECT * FROM mails WHERE LENGTH(txt) < 300 LIMIT 300,1\G *************************** 1. row *************************** msg_nro: 3068 date: 2000-03-01 23:29:50 time_zone: +0200 mail_from: Monty reply: monty@no.spam.com mail_to: "Thimble Smith" <tim@no.spam.com> sbj: UTF-8 txt: >>>>> "Thimble" == Thimble Smith writes: Thimble> Hi. I think this is a good idea. Is anyone familiar Thimble> with UTF-8 or Unicode? Otherwise, I'll put this on my Thimble> TODO list and see what happens. Yes, please do that. Regards, Monty file: inbox-jani-1 hash: 190402944 1 row in set (0.09 sec)
--safe-updates
(or --i-am-a-dummy
, which has the same effect). It is helpful for cases when you might have issued a DELETE FROM
tbl_name statement but forgotten the WHERE
clause. Normally, such a statement deletes all rows from the table. With --safe-updates
, you can delete rows only by specifying the key values that identify them. This helps prevent accidents.SET sql_safe_updates=1, sql_select_limit=1000, sql_max_join_size=1000000;
See Section 5.1.4, "Server System Variables".
The SET statement has the following effects:
UPDATE tbl_name SET not_key_column=val WHERE key_column=val; UPDATE tbl_name SET not_key_column=val LIMIT 1;
- The server limits all large SELECT results to 1,000 rows unless the statement includes a LIMIT clause.
- The server aborts multiple-table SELECT statements that probably need to examine more than 1,000,000 row combinations.
To specify limits different from 1,000 and 1,000,000, you can override the defaults by using the --select_limit and --max_join_size options:
shell> mysql --safe-updates --select_limit=500 --max_join_size=10000
mysql> 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: 1 Current database: test Query OK, 1 row affected (1.30 sec) mysql> SELECT * FROM t; +------+ | a | +------+ | NULL | +------+ 1 row in set (0.05 sec)
The @a user variable has been lost with the connection, and after the reconnection it is undefined. If it is important to have mysql terminate with an error if the connection has been lost, you can start the mysql client with the --skip-reconnect option.
For more information about auto-reconnect and its effect on state information when a reconnection occurs, see Section 21.9.11, "Controlling Automatic Reconnection Behavior".