Linux mysql command

Updated: 09/12/2023 by Computer Hope
mysql command

The mysql command is a simple shell for SQL (Structured Query Language) commands. With user interaction, it can enter commands at a special prompt, or run a batch script containing your SQL commands.

Description

When mysql is used interactively, query results are presented in a table format. When used non-interactively, the result is presented in tab-separated format. The output format can be changed using command options.

The simplest way to invoke mysql is to specify your MySQL username with the -u option, and to tell mysql to prompt you for your password with -p:

mysql -u username -p

You are shown a brief introduction message and then placed at the mysql> prompt.

At the mysql> prompt, enter MySQL commands, such as:

mysql> SHOW DATABASES;

To list the databases which exist, or:

mysql> USE dbname;

...to begin using the database named dbname, or:

mysql> SELECT 21 * 2 AS meaning_of_life;

...to display the mathematical product of 2 and 21.

To end your mysql session and return to the shell prompt, use the command:

mysql> QUIT

Running MySQL commands from a batch script

Instead of using mysql interactively, you can execute MySQL statements from a script file. For instance, if you have a text file named mysqlscript.txt containing MySQL commands, one per line, you could use this command:

mysql -u username -p db_name < mysqlscript.txt > output.txt

...and after prompting you for your password, mysql would execute the commands in mysqlscript.txt on the database db_name, writing the output to the file output.txt.

For an in-depth description of how to install MySQL on your system, and an overview of the basic interactive usage of mysql, see an introduction to MySQL.

Syntax

mysql [options] db_name

Options

mysql supports the following options, which can be specified on the command line or in the [mysql] and [client] groups of an option file.

--help, -? Display a help message and exit.
--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, press Tab again to see the possible names beginning with what you typed so far. Completion does not occur if there is no default database.
--auto-vertical-output Cause result sets to display vertically if they are too wide for the current window, and use normal tabular format otherwise. (This applies to statements terminated by ; or \G.) This option was added in MySQL 5.5.3.
--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 using raw mode; see the description for the --raw option.
--bind-address=ip_address On a computer having multiple network interfaces, this option can 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. It is not available in standard MySQL Server 5.5 releases.
--character-sets-dir=path The directory where character sets are installed.
--column-names Write column names in results.
--column-type-info, -m Display result set metadata.
--comments, -c Whether to preserve comments in statements sent to the server. The default is --skip-comments (discard comments), enable with --comments (preserve comments).
--compress, -C Compress all information sent between the client and the server if both support compression.
--database=db_name,
-D db_name
The database to use. This switch is useful primarily in an option file.
--debug[=debug_options],
-# [debug_options]
Write a debugging log. A typical debug_options string is 'd:t:o,file_name'. The default is 'd:t:o,/tmp/mysql.trace'.
--debug-check Print some debugging information when the program exits.
--debug-info, -T Print debugging information, and memory and CPU (central processing unit) usage statistics when the program exits.
--default-auth=plugin The client-side authentication plugin to use.

This option was added in MySQL 5.5.7.
--default-character-set=charset_name Use charset_name as the default character set for the client and connection.

A common issue that occurs when the operating system uses utf8 or another multi-byte character set is that output from the mysql client is formatted incorrectly, because that MySQL client uses the latin1 character set by default. You can usually fix such issues using this option to force the client to use the system character set instead.
--delimiter=str Set the statement delimiter. The default is the semicolon character (";").
--disable-named-commands Disable named commands. Use the \* form only, or use named commands only at the beginning of a line ending with a semicolon (";"). The mysql command starts with this option enabled by default. However, even with this option, long-format commands still work from the first line.
--enable-cleartext-plugin Enable the mysql_clear_password cleartext authentication plugin. This option was added in MySQL 5.5.27.
--execute=statement,
-e statement
Execute the statement and quit. The default output format is like that produced with --batch. With this option, mysql does not use the history file.
--force, -f Continue even if an SQL error occurs.
--host=host_name,
-h host_name
Connect to the MySQL server on the given host.
--html, -H Produce HTML (hypertext markup language) output.
--ignore-spaces, -i Ignore spaces after function names. The effect of this switch is described in the discussion for the IGNORE_SPACE SQL mode.
--init-command=str SQL statement to execute after connecting to the server. If auto-reconnect is enabled, the statement is executed again after reconnection occurs.
--line-numbers Write line numbers for errors. Disable this with --skip-line-numbers.
--local-infile[={0|1}] Enable or disable 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 Enable named mysql commands. Long-format commands are permitted, in addition to short-format commands. For example, quit and \q both are recognized. Use --skip-named-commands to disable named commands.
--no-auto-rehash, -A This has the same effect as -skip-auto-rehash. See the description for --auto-rehash.
--no-beep, -b Do not beep when errors occur.
--no-named-commands, -g Deprecated, use --disable-named-commands instead. --no-named-commands was removed in MySQL 5.5.3.
--no-pager Deprecated form of --skip-pager. See the --pager option. --no-pager was removed in MySQL 5.5.3.
--no-tee Deprecated form of --skip-tee. See the --tee option. --no-tee is removed in MySQL 5.5.3.
--one-database, -o Ignore statements except those that occur while the default database is the one named on the command line. This option is rudimentary and should be used with care. Statement filtering is based only on USE statements.

Initially, mysql executes statements in the input because specifying a database db_name on the command line is equivalent to inserting USE db_name at the beginning of the input. Then, for each USE statement encountered, mysql accepts or rejects following statements depending on whether the database named is the one on the command line. The content of the statements is immaterial.

Suppose that mysql is invoked to process this set of statements:

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);
If the command line is mysql --force --one-database db1, mysql handles the input as follows:

The DELETE statement is executed because the default database is db1, even though the statement names a table in a different database.

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

The 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] Use the given command for paging query output. If the command is omitted, the default pager is the value of your PAGER environment variable. Valid pagers are less, more, cat [> file name], and so forth. This option only works on Unix and only in interactive mode. To disable paging, use --skip-pager. See MySQL commands for more information about output paging.
--password[=password],
-p[password]
The password to use when connecting to the server. If you use the short option form (-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.

Specifying a password on the command line should be considered insecure. You can use an option file to avoid giving the password on the command line.
--pipe, -W On Windows, connect to the server using a named pipe. This option applies only if the server supports named-pipe connections.
--plugin-dir=path The directory where to look for plugins. It may be necessary to specify this option if the --default-auth option is used to specify an authentication plugin but mysql does not find it.

This option was added in MySQL 5.5.7.
--port=port_num,
-P port_num
The TCP/IP port number to use for the connection.
--prompt=format_str Set the prompt to the specified format. The default is mysql>. The special sequences that the prompt contains are described in the MySQL commands section.
--protocol={TCP|SOCKET|PIPE|MEMORY} 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.
--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.
--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.

The following example demonstrates tabular versus nontabular output and the use of raw mode to disable 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 If the connection to the server is lost, automatically try to reconnect. A single reconnect attempt is made each time the connection is lost. To suppress reconnection behavior, use --skip-reconnect.
--safe-updates,
--i-am-a-dummy,
-U
Permit only those UPDATE and DELETE statements that specify which rows to modify using key values. If you have set this option in an option file, you can override it using --safe-updates on the command line.
--secure-auth Do not send passwords to the server in old (pre-4.1.1) format. This prevents connections except for servers that use the newer password format.
--show-warnings Cause warnings to show after each statement, if there are any. This option applies to interactive and batch mode.
--sigint-ignore Ignore SIGINT signals (typically the result of typing Control+C).
--silent, -s Silent mode. Produce less output. This option can be given multiple times to produce less and less output.

This option results in nontabular output format and escaping of special characters. Escaping may be disabled using raw mode; see the description for the --raw option.
--skip-column-names, -N Do not write column names in results.
--skip-line-numbers, -L Do not write line numbers for errors. Useful when you want to compare result files that include error messages.
--socket=path, -S path For connections to localhost, the Unix socket file to use, or on Windows, the name of the named pipe to use.
--ssl* Options that begin with --ssl specify whether to connect to the server using SSL (secure sockets layer) and indicate where to find SSL keys and certificates.
--table, -t Display output in table format. This switch is the default for interactive use, but can produce table output in batch mode.
--tee=file_name Append a copy of output to the given file. This option works only in interactive mode. The section called "MYSQL COMMANDS", discusses tee files further.
--unbuffered, -n Flush the buffer after each query.
--user=user_name,
-u user_name
The MySQL username to use when connecting to the server.
--verbose, -v Verbose mode. Produce more output about what the program does. This option can be given multiple times to produce more and more output. (For example, -v -v -v produces table output format even in batch mode.)
--version, -V Display version information and exit.
--vertical, -E Print query output rows vertically (one line per column value). Without this option, you can specify vertical output for individual statements by terminating them with \G.
--wait, -w If the connection cannot be established, wait and retry instead of aborting.
--xml, -X Produce XML (extensible markup language) output. See mysql manual for more information.

MySQL commands

mysql sends each SQL statement you issue to the server to be executed. Note that all text commands must first be online and end with ';' .

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:

? (\?) 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.

Examples

For an in-depth description of installing MySQL, and an overview of basic commands, see An introduction to MySQL.

The following are a few other notable commands:

mysqldump -u hope -p -h localhost hope_SMF > smf.sql

Backup the database "hope_SMF" to the smf.sql file after the username and password were verified.

mysql> status

Running status while at the mysql> prompt would give you MySQL status results similar to what is shown below.

--------------
mysql  Ver 14.14 Distrib 5.5.35, for debian-linux-gnu (i686) using readline 6.2
Connection id:		42
Current database:	
Current user:		hope@localhost
SSL:			Not in use
Current pager:		stdout
Using outfile:		''
Using delimiter:	;
Server version:		5.5.35-0ubuntu0.13.10.2 (Ubuntu)
Protocol version:	10
Connection:		Localhost via UNIX socket
Server characterset:	latin1
Db     characterset:	latin1
Client characterset:	utf8
Conn.  characterset:	utf8
UNIX socket:		/var/run/mysqld/mysqld.sock
Uptime:			2 hours 3 min 4 sec
Threads: 1  Questions: 577  Slow queries: 0  Opens: 421  Flush tables: 1  Open tables: 41  Queries per second avg: 0.078
--------------

myisamchk — Check, repair, optimize, or fetch information about a MySQL database.
mysqldump — A tool for backing up or transferring MySQL databases.