mysql
The MySQL command-line tool
These notes are interpretations and comments and examples by me and the Genuine documentation is at
Dev.MySQL.com/doc.
mysql [options] db_name
a SQL shell (with GNU readline capabilities).
Output format can be changed using command options.Default:
- interactively, results are in ASCII-table format.
> mysql db_name
Or:
> mysql --user=user_name [--password=password] db_name
- non-interactively (for example, as a filter), results are in tab-separated format.
> mysql db_name script.sql output.tab
--host=host_name -h host_name
| --database=db_name -D db_name
| --user=user_name -u user_name MySQL username
| ‑‑password[=password] -p[password]
For the short form (-p), do not use a space before the password.
If Password is omitted following --password or -p it is prompted for .
| --safe-updates -U UPDATEs and DELETEs must specify a key.
If set in an option file, override it by using --safe-updates on the command line.
select_limit (Default 1,000.)
max_join_size (Default 1,000,000.)
See "MYSQL TIPS"
| --batch -B Use [tab] ␉as the column separator, with each row on a new line.
Supresses prompt , nnn rows in set summary message with timing and the history file of commmands entered.
> mysql --batch
select name,entry, class from PCCraceApp;
name␉entry␉class␉
Rosemary␉Murphy␉209␉OC1
Mike␉Parkinson␉200␉SK1
David␉Impens␉237␉RC1
Amber␉Tomas␉236␉ICFK1
Charlie␉Johnson␉235␉Tr1
Slava␉Sadkhin␉212␉SK1 Also Current pager: stdout
--raw -r Write column values without escape conversion.
Useful with --batch .
+---------------------+---------------+----------------+
| day | bfname | blname |
+---------------------+---------------+----------------+
| 2017-01-02 15:17:35 | EDWARD | GIANNOTTI |
| 2017-01-02 19:26:50 | RAMON | BARRETT |
| 2017-01-02 19:50:42 | yehudi | shkedi |
| 2017-01-02 20:25:53 | FREDERICK | PELIA |
| 2017-01-13 12:07:15 | FRANCIS | KELLY-IASPARRI |
+---------------------+---------------+----------------+
5 rows in set (0.01 sec)
AlsoCurrent pager: less
--vertical -E Output rows vertically (one value per line).
mysql> select name,entry, class from PCCraceApp;
*************************** 1. row ***************************
name: Rosemary Murphy
entry: 209
class: OC1
*************************** 2. row ***************************
name: Mike Parkinson
entry: 200
class: SK1
*************************** 3. row ***************************
name: David Impens
entry: 237
class: RC1
36 rows in set (0.00 sec)
Without this option, you can specify vertical output for individual
statements by terminating them with \G.
--html -H Produce HTML output.
<TABLE BORDER=1>
<TR><TH>name</TH><TH>entry</TH><TH>class</TH></TR>
<TR><TD>Rosemary Murphy</TD><TD>209</TD><TD>OC1</TD></TR>
<TR><TD>Mike Parkinson</TD><TD>200</TD><TD>SK1</TD></TR>
<TR><TD>David Impens</TD><TD>237</TD><TD>RC1</TD></TR>
<TR><TD>Amber Tomas</TD><TD>236</TD><TD>ICFK1</TD></TR>
<TR><TD>Charlie Johnson</TD><TD>235</TD><TD>Tr1</TD></TR>
<TR><TD>Gary Ballina</TD><TD>218</TD><TD>K2</TD></TR>
<TR><TD>Emilia Rastick</TD><TD>225</TD><TD>OC1</TD></TR>
<TR><TD>Meegan Coll</TD><TD>226</TD><TD>OC1</TD></TR>
<TR><TD>Glen Green</TD><TD>219</TD><TD>K1</TD></TR></TABLE>
36 rows in set (0.03 sec)
| name | entry | class |
| Rosemary Murphy | 209 | OC1 |
| Mike Parkinson | 200 | SK1 |
| David Impens | 237 | RC1 |
| Amber Tomas | 236 | ICFK1 |
| Charlie Johnson | 235 | Tr1 |
| Gary Ballina | 218 | K2 |
| Emilia Rastick | 225 | OC1 |
| Meegan Coll | 226 | OC1 |
| Glen Green | 219 | K1 |
Also Current pager: less
--xml -X Produce XML output.
<?xml version="1.0"?>
<resultset statement="select name,entry, class from PCCraceApp;"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<row>
<field name="name">Rosemary Murphy</field>
<field name="entry">209</field>
<field name="class">OC1</field>
</row>
<row>
<field name="name">Mike Parkinson</field>
<field name="entry">200</field>
<field name="class">SK1</field>
</row>
</resultset>
36 rows in set (0.00 sec)
Also Current pager: less
--table -t Default for interactive.
+---------------------+---------------+----------------+
| day | bfname | blname |
+---------------------+---------------+----------------+
| 2017-01-02 15:17:35 | EDWARD | GIANNOTTI |
| 2017-01-02 19:26:50 | RAMON | BARRETT |
| 2017-01-02 19:50:42 | yehudi | shkedi |
| 2017-01-02 20:25:53 | FREDERICK | PELIA |
| 2017-01-13 12:07:15 | FRANCIS | KELLY-IASPARRI |
+---------------------+---------------+----------------+
5 rows in set (0.01 sec)
| --column-names | Write column names in results.
| --skip-column-names -N in results.
| --verbose -v multiple times produce more and more output.
in batch mode:
-v echos the supplied SQL statment and
-v -v produces nnn rows in set summary message with time.
-v -v -v produces table output format
--silent -s given multiple times to produce less and less output.
Without --silent welcome greeting is displayed at startup:
Welcome to the MariaDB monitor. Commands end with ; or \g.
Your MariaDB connection id is 67855984
Server version: 10.6.18-MariaDB-log MariaDB Server
Copyright (c) 2000, 2018, Oracle, MariaDB Corporation Ab and others.
Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
| --line-numbers | Write line numbers for errors.
| --skip-line-numbers -L for errors.
Useful when you want to compare result files that include error messages.
| --tee=file
--no-tee Append / (don't append) a copy of output to file.
Not in batch mode. see MYSQL commands
--no-beep -b Do not beep when errors occur.
| |
| --debug-info -T output debugging information when the program exits. (May be disabled)
| --debug[=debug_options] -# [debug_options]
Write a debugging log. The debug_options string often is d:t:o,file_name The default is d:t:o,/tmp/mysql.trace
| --delimiter=C Set the statement delimiter. Default semicolon ;.
| --execute=statement -e statement Execute the statement and quit.
The default output format is like that produced with --batch.
See Section 3.1, "Using Options on the Command Line".
| --force -f Continue if an SQL error occurs.
| --ignore-spaces -i Ignore spaces after function names.
See "SQL MODES" IGNORE_SPACE .
| --local-infile[=0|1] Disable | Enable LOCAL capability for LOAD DATA INFILE.
--local-infile enables LOCAL.
Enabling LOCAL has no effect if the server does not also support it.
| --named-commands -G Enable named mysql commands. Long-format commands are allowed, not
just short-format commands. For example, quit and \q both are recognized.
--skip-named-commands to disable named commands.
See "MYSQL COMMANDS".
| --no-named-commands -g Disable named commands. Use the \* form only, or use named commands
only at the beginning of a line ending with a semicolon (';'). As of
MySQL 3.23.22, mysql starts with this option enabled by default.
However, even with this option, long-format commands still work from
the first line. See the section called "MYSQL COMMANDS".
| --default-character-set=charset_name Use charset_name as the default character set.
See Section 9.1, "The Character Set Used for Data and Sorting".
| --one-database -o Ignore statements except those for the default database named on the command line.
Useful for skipping updates to other databases in the binary log.
| --pager[=command]
--skip-pager Valid commands are less, more, cat [> filename],
and so forth. Only on Unix.
Default is PAGER environment variable.
Not in batch mode.
See MYSQL COMMANDS discusses output paging further.
| --no-pager | Deprecated form of --skip-pager. See the --pager option.
| --prompt=format_str Default mysql>.
see MYSQL COMMANDS
| --port=port_num -P port_num The TCP/IP port number to use for the connection.
| --protocol={TCP|SOCKET|PIPE|MEMORY} |
| --compress -C Compress all information sent between client and server
| --quick -q Do not cache each query result, output each row as it is received.
This may slow down the server if the output is suspended.
With this option, mysql does not use the history file.
| --reconnect
--skip-reconnectautomatically reconnect. A single reconnect attempt is made each time .
| --wait -w Wait & retry if connection cannot be established.
| --secure-auth | Do not send passwords to the server in old (pre-4.1.1) format.
| --sigint-ignore | Control-C
| --socket=path -S path Connections to localhost, Unix socket file , Windows named pipe
| --ssl* connect to the server via SSL and indicate where to find SSL keys and certificates.
See Section 7.7.3, "SSL Command Options".
| --unbuffered -n Flush the buffer after each query.
| --character-sets-dir=path The directory where character sets are installed.
See Section 9.1, "The Character Set Used for Data and Sorting".
| --auto-rehash
--skip-auto-rehash
| Enable/Skip rehashing. Default enables table and column name completion. ( same as rehash )
Disables rehashing.
| --no-auto-rehash -A Deprecated form of -skip-auto-rehash. See the description for --auto-rehash.
|
using --var_name=value (variables)
| select_limit | when using --safe-updates. (Default 1,000.)
| max_join_size Limit rows in a join when using --safe-updates. (Default 1,000,000.)
| connect_timeout | (Default 0 seconds .)
| max_allowed_packet length | Sent to or receive from the server. (Default 16MB.)
| net_buffer_length | TCP/IP and socket communication. (Default 16KB.)
| --version -V 5.0.92-community-log as of 4/27/11 at slmp-550-13.slc.westdc.net
| | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | |
History file
On Unix, mysql writes statements to .mysql_history.
To specify a different file, set MYSQL_HISTFILE environment variable.
To disable this first remove .mysql_history and either
Set MYSQL_HISTFILE /dev/null or
Create .mysql_history as a symbolic link to /dev/null:
> ln -s /dev/null $HOME/.mysql_history
MySQL COMMANDS
SQLs statement are sent the server
These are commands that mysql itself processes.
warnings \W| Show warnings after every statement.
| nowarning \w| Don't show warnings after every statement.
| clear \c| Clear command.
| connect \r| Reconnect to the server. Optional arguments are db and host.
| delimiter \d| Set statement delimiter. NOTE: Takes the rest of the line as
new 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 0 | Disable pager, output to stdout.
| notee \t| Don't write into outfile.
| pager \P| Set PAGER [to_pager]. output the query results via PAGER.
| output \p| output 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.
| ? \?| Synonym for `help'.
| --help, -?
| | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | |
For server side help, type help contents
Commands have 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.
If you provide an argument to the help command, mysql uses it as a
search string to access server-side help from the contents of the MySQL
Reference Manual. For more information, see the section called "MYSQL SERVER-SIDE HELP".
Avoid delimiter backslash ('\') because that is the escape character .
edit, nopager, pager, and system work only in *nix.
status outputs information about the connection, server, if in --safe-updates mode
status and the values for variables that affect queries.
To log queries and output use tee command. Data
displayed on the screen is appended to a file.
Useful for debugging. This can be enabled on the
command line with --tee , or with tee
The tee file can be disabled with notee
. Executing tee again re-enables logging defaulting to
the previous file. tee flushes results
after each statement.
Use --pager to browse or search query
results with filters such as less, more or
a similar filter.
Without a value $PAGER is used.
Output paging is enabled with pager and disabled with nopager.
The optional argument . With no
Paging works only in *nix.
For Windows, tee can be used to save query output, although this is not as convenient
as pager for browsing output.
Tips
- write to only a file
mysql> pager cat > /tmp/log.txt
pass options for pager:
mysql> pager less -n -i -S
- the -S
useful for browsing wide 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
- 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
In this example, the command would send query results to two files in
two different directories on two different filesystems mounted on /dr1
and /dr2, yet still display the results onscreen via less.
You can also combine the tee and pager functions. Have a tee file
enabled and pager set to less, and you are able to browse the results
using the less program and still have everything appended into a file
the same time. The difference between the Unix tee used with the pager
command and the mysql built-in tee command is that the built-in tee
works even if you do not have the Unix tee available. The built-in tee
also logs everything that is output on the screen, whereas the Unix
tee used with pager does not log quite that much. Additionally, tee
file logging can be turned on and off interactively from within mysql.
This is useful when you want to log some queries to a file, but not
others.
string for defining the prompt can contain the following special sequences:
\R | hours, 0-23
| \r | 1-12
| \m | Minutes
| \s | Seconds
| \P | am/pm
| \D | full date Tue May 22 20:19:04 2012
| \w | day of the week in three-letter format (Mon, Tue, ...)
| \o | month numeric format
| \O | three-letter format (Jan, Feb, ...)
| \y | year, 2 digits
| \Y | 4 digits
| \c | A counter that increments for each statement
| \d | default database
| \h | server host
| \v | server version
| \p | TCP/IP port or socket file
| \u | username
| \U | full user_name@host_name | account
| \T | '\' backslash
| \S | Semicolon
| \' | apostrophe
| \" | Double quote
| | A newline character
| \t tab character T}:T{ A space (a space follows the backslash)
| \_ | space
| | | | | | | | | | | | | | | | | | | | | | | | | |
'\' followed by any other letter just becomes that letter.
If you specify the prompt command with no argument, mysql resets the prompt to the default of mysql>.
Set the prompt using :
MYSQL_PS1 environment variable.
shell> export MYSQL_PS1="(\u@\h) [\d]> "
-
--prompt=xxx command-line option.
shell> mysql --prompt="\u@\h [\d]> "
user@host [database]>
- Use an option file. the
prompt option in the [mysql] group of any MySQL option file, such as
/etc/my.cnf or the .my.cnf file in your home directory. For example:
[mysql]
prompt=(\\u@\\h) [\\d]>\\_
In this example, note that the backslashes are doubled (escaped). If you set the
prompt using the prompt option in an option file, it is advisable to
double the backslashes when using the special prompt options. There is
some overlap in the set of allowable prompt options and the set of
special escape sequences that are recognized in option files. (These
sequences are listed in Section 3.2, "Using Option Files".) The overlap
may cause you problems if you use single backslashes. For example, \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> "
Set the prompt interactively. using the 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 SERVER-SIDE HELP
mysql> help search_string
if you provide an argument to the help command, mysql
uses it as a search string to access server-side help from the contents
of the MySQL Reference Manual. This requires that the help tables in the mysql database be initialized with
help topic information (see the section called "SERVER-SIDE HELP").
To see a list of the help categories:
mysql> help contents
You asked for help about help category: "Contents"
For more information, type 'help - ', where
- is one of the following categories:
Account Management, Administration, Data Definition, Data Manipulation, Data Types, Functions,
Functions and Modifiers for Use with GROUP BY, Geographic Features, Language Structure, Storage Engines, Table Maintenance,
Transactions,
If the search string matches multiple items, mysql shows a list of matching topics:
mysql> help logs
Many help items for your request exist.
To make a more specific request, please type 'help - ',
where
- is one of the following topics:
SHOW
SHOW BINARY LOGS
SHOW ENGINE
SHOW LOGS
Use a topic as the search string to see the help entry for that topic:
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-master-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
+---------------+-----------+
Executing SQL statements from a file
> mysql db_name < text_file
A USE db_name in the file precludes specifing the database name on the command line:
mysql < text_file
from within mysql, execute an script file using source or \.
mysql> source file_name
mysql> \. file_name
To display progress information:
SELECT 'info_to_display' AS ' ';
The statement shown outputs info_to_display.
MYSQL TIPS
Displaying Query Results Vertically
terminate the query with \G instead of ; semicolon.
Longer text values that include newlines are much easier to read with vertical
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"
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)
Using the --safe-updates Option
For example issuing a DELETE FROM tbl_name; ommitting the WHERE clause.
Without safe-updates statement deletes all rows from the table.
With --safe-updates, delete rows requires key values.
mysql issues the following statement when it connects to the MySQL server:
SET SQL_SAFE_UPDATES=1,SQL_SELECT_LIMIT=1000, SQL_MAX_JOIN_SIZE=1000000;
See Section 5.3
-
UPDATEs and DELETEs require a key constraint in a WHERE or provide a LIMIT . For example:
UPDATE tbl_name SET not_key_column=val WHERE key_column=val;
UPDATE tbl_name SET not_key_column=val LIMIT 1;
SELECT results are limited to 1,000 rows unless a LIMIT clause is included.
- 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, use
--select_limit and --max_join_size
> mysql --safe-updates --select_limit=500 --max_join_size=10000
Disabling mysql Auto-Reconnect
If mysql loses connection to the server while sending a query,
session objects, settings, autocommit mode, temporary tables, user-defined and session variables are lost.
Current transaction rolls back.
This behavior may be dangerous as in the following example
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 | Expected 1
+------+
1 row in set (0.05 sec)
The @a user variable has been lost with the connection, and after the reconnection it is undefined.
To have mysql terminate with an error if the connection has been lost, use --skip-reconnect .
With auto-reconnect mySQL immediately tries once to reconnect to the server and send the query again.
SEE isamchk, isamlog, msql2mysql, myisam_ftdump, myisamchk,
myisamlog, myisampack, mysql.server, mysql_config,
mysql_explain_log, mysql_fix_privilege_tables, mysql_zap,
mysqlaccess, mysqladmin, mysqlbinlog, mysqlcheck,
mysqld, mysqld(8), mysqld_multi, mysqld_safe, mysqldump,
mysqlhotcopy, mysqlimport, mysqlshow, pack_isam, perror,
replace, safe_mysqld
The current documention is at dev.mysql.com/doc/refman/5.7/en/index.html