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:

  1. interactively, results are in ASCII-table format.

    > mysql db_name

    Or:

    > mysql --user=user_name [--password=password] db_name

  2. 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
--i-am-a-dummy
-U
only UPDATEs and DELETEs that specify key values are permitted.
If set in an option file, override it by using --safe-updates on the command line.
See "MYSQL TIPS"
--table
-t
Display output in table format. default for interactive.
--batch
-B
Display results using [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
select name,entry, class from PCCraceApp;
nameentryclass
RosemaryMurphy209OC1
MikeParkinson200SK1
DavidImpens237RC1
AmberTomas236ICFK1
CharlieJohnson235Tr1
SlavaSadkhin212SK1
--raw
-r
Write column values without escape conversion.
Useful with --batch .
--vertical
-E
Print query output rows vertically (one line per column value).
 Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 20417564
Server version: 5.1.62-cll MySQL Community Server (GPL)
…

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)
nameentryclass
Rosemary Murphy209OC1
Mike Parkinson200SK1
David Impens237RC1
Amber Tomas236ICFK1
Charlie Johnson235Tr1
Gary Ballina218K2
Emilia Rastick225OC1
Meegan Coll226OC1
Glen Green219K1

--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) 
--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.
    --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
    Print 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, print 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 automatically reconnect. A single reconnect attempt is made each time .
    To suppress reconnection behavior, use --skip-reconnect.
    --wait
    -w
    If the connection cannot be established, wait and retry instead of aborting.
    --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".
    --version
    -V
    5.0.92-community-log as of 4/27/11 at slmp-550-13.slc.westdc.net
    --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 automatic rehashing. default enables table and column name completion.
    disables rehashing. mysql starts faster, to use table and column name completion issue rehash.
    --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.)
    connect_timeout (Default value is 0 seconds .)
    max_allowed_packet length to send to or receive from the server. (Default value is 16MB.)
    max_join_size The automatic limit for rows in a join when using --safe-updates. (Default value is 1,000,000.)
    net_buffer_length TCP/IP and socket communication. (Default 16KB.)

    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, 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.
    ? \? 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 the use delimiter of the backslash ('\') character because that is the escape character for MySQL.

    The edit, nopager, pager, and system commands work only in Unix.

    The status command provides some information about the connection and the server you are using. If you are running in --safe-updates mode, status also prints the values for the mysql variables that affect your queries.

    To log queries and their output, use the tee command. All the data displayed on the screen is appended into a given file. This can be very useful for debugging purposes also. You can enable this feature on the command line with the --tee option, or interactively with the tee command. The tee file can be disabled interactively with the notee command. Executing tee again re-enables logging. Without a parameter, the previous file is used. Note that tee flushes query results to the file after each statement, just before mysql prints its next prompt.

    By using the --pager option, 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. Output paging can be enabled interactively with the pager command and disabled with nopager. The command takes an optional argument; if given, the paging program is set to that. With no argument, the pager is set to the pager that was set on the command line, or stdout if no pager was specified.

    Output paging works only in Unix because it uses the popen() function, which does not exist on Windows. For Windows, the tee option can be used instead to save query output, although this is not as convenient as pager for browsing output in some situations.

    Here are a few tips about the pager command:

    1. You can use it to write to a file and the results go only to the file:
       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 

    2. 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

    3. 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 printed 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 :
    1. MYSQL_PS1 environment variable. shell> export MYSQL_PS1="(\u@\h) [\d]> "
    2. --prompt=xxx command-line option. shell> mysql --prompt="\u@\h [\d]> " user@host [database]>
    3. 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

    1. 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;
      
    2. SELECT results are limited to 1,000 rows unless a LIMIT clause is included.
    3. aborts multiple-table SELECT statements that probably need to examine more than 1,000,000 row combinations.
    4. 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