Home > Articles

  • Print
  • + Share This
This chapter is from the book

This chapter is from the book

3.2 The mysql Client Program

The mysql client program enables you to send queries to the MySQL server and receive their results. It can be used interactively or it can read query input from a file in batch mode:

  • Interactive mode is useful for day-to-day usage, for quick one-time queries, and for testing how queries work.

  • Batch mode is useful for running queries that have been prewritten. It's especially valuable for issuing a complex series of queries that's difficult to enter manually, or queries that need to be run automatically by a job scheduler without user intervention.

3.2.1 Using mysql Interactively

To invoke mysql interactively from the command line, specify any necessary connection parameters after the command name:

shell> mysql -u user_name -p -h host_name

You can also provide a database name to select that database as the default database:

shell> mysql -u user_name -p -h host_name database_name

After mysql has connected to the MySQL server, it prints a mysql> prompt to indicate that it's ready to accept queries. To issue a query, enter it at the prompt. Complete the query with a statement terminator (typically a semicolon). The terminator tells mysql that the statement has been entered completely and should be executed. When mysql sees the terminator, it sends the query to the server and then retrieves and displays the result. For example:

mysql> SELECT DATABASE();
+------------+
| DATABASE() |
+------------+
| world   |
+------------+

A terminator is necessary after each statement because mysql allows several queries to be entered on a single input line. mysql uses the terminators to distinguish where each query ends, and then sends each one to the server in turn and displays its results:

mysql> SELECT DATABASE(); SELECT VERSION();
+------------+
| DATABASE() |
+------------+
| world   |
+------------+
+------------+
| VERSION() |
+------------+
| 4.0.18-log |
+------------+

Statement terminators are necessary for another reason as well: mysql allows a single query to be entered using multiple input lines. This makes it easier to issue a long query because you can enter it over the course of several lines. mysql will wait until it sees the statement terminator before sending the query to the server to be executed. For example:

mysql> SELECT Name, Population FROM City
  -> WHERE Country = 'IND'
  -> AND Population > 3000000;
+--------------------+------------+
| Name        | Population |
+--------------------+------------+
| Mumbai (Bombay)  |  10500000 |
| Delhi       |  7206704 |
| Calcutta [Kolkata] |  4399819 |
| Chennai (Madras)  |  3841396 |
+--------------------+------------+

More information about statement terminators can be found in section 3.2.3, "Statement Terminators."

In the preceding example, notice what happens when you don't complete the query on a single input line: mysql changes the prompt from mysql> to -> to indicate that it's still waiting to see the end of the statement. The full set of mysql prompts is discussed in section 3.2.4, "The mysql Prompts."

If a statement results in an error, mysql displays the error message returned by the server:

mysql> This is an invalid statement;
ERROR 1064: You have an error in your SQL syntax.

If you change your mind about a statement that you're composing, enter \c and mysql will return you to a new prompt:

mysql> SELECT Name, Population FROM City
  -> WHERE \c
mysql>

To quit mysql, use \q, QUIT, or EXIT:

mysql> \q

3.2.2 Using Editing Keys in mysql

mysql supports input-line editing, which enables you to recall and edit input lines. For example, you can use the up-arrow and down-arrow keys to move up and down through previous input lines, and the left-arrow and right-arrow keys to move back and forth within a line. Other keys, such as Backspace and Delete, erase characters from the line, and you can type in new characters at the cursor position. To submit an edited line, press Enter.

On Windows, you might find that input-line editing does not work for Windows 95, 98, or Me.

mysql also supports tab-completion to make it easier to enter queries. With tab-completion, you can enter part of a keyword or identifier and complete it using the Tab key. This feature is supported on Unix only.

3.2.3 Statement Terminators

You may use any of several statement terminators to end a query. Two statement terminators are the semicolon character (;) and the \g sequence. They're equivalent and may be used interchangeably:

mysql> SELECT VERSION(), DATABASE();
+------------+------------+
| VERSION() | DATABASE() |
+------------+------------+
| 4.0.18-log | world   |
+------------+------------+
mysql> SELECT VERSION(), DATABASE()\g
+------------+------------+
| VERSION() | DATABASE() |
+------------+------------+
| 4.0.18-log | world   |
+------------+------------+

The \G sequence also terminates queries, but causes mysql to display query results in a different style. The new style shows each output row with each column value on a separate line:

mysql> SELECT VERSION(), DATABASE()\G
*************************** 1. row ***************************
 VERSION(): 4.0.18-log
DATABASE(): world

The \G terminator is especially useful if a query produces very wide output lines. It can make the result much easier to read.

3.2.4 The mysql Prompts

The mysql> prompt displayed by mysql is just one of several different prompts that you might see when entering queries. Each type of prompt has a functional significance because mysql varies the prompt to provide information about the status of the statement you're entering. The following table shows each of these prompts:

Prompt

Meaning of Prompt

mysql>

Ready for new statement

->

Waiting for next line of statement

'>

Waiting for end of single-quoted string

">

Waiting for end of double-quoted string or identifier

´>

Waiting for end of backtick-quoted identifier

The mysql> prompt is the main (or primary) prompt. It signifies that mysql is ready for you to begin entering a new statement.

The other prompts are continuation (or secondary) prompts. mysql displays them to indicate that it's waiting for you to finish entering the current statement. The -> prompt is the most generic continuation prompt. It indicates that you have not yet completed the current statement, for example, by entering ; or \G. The '>, ">, and ´> prompts are more specific. They indicate not only that you're in the middle of entering a statement, but that you're in the middle of entering a single-quoted string, a double-quoted string, or a backtick-quoted identifier, respectively. When you see one of these prompts, you'll often find that you have entered an opening quote on the previous line without also entering the proper closing quote.

If in fact you did mistype the current query by forgetting to close a quote, you can cancel the query by entering the closing quote followed by the \c clear-query command.

3.2.5 Using Script Files with mysql

When used interactively, mysql reads queries entered at the keyboard. mysql can also accept input from a file. An input file containing SQL statements to be executed is known as a "script file" or a "batch file." A script file should be a plain text file containing statements in the same format that you would use to enter the statements interactively. In particular, each statement must end with a terminator.

One way to process a script file is to execute it with a SOURCE command from within mysql:

mysql> SOURCE input_file;

Notice that there are no quotes around the name of the file.

mysql executes the queries in the file and displays any output produced.

The file must be located on the client host where you're running mysql. The filename must either be an absolute pathname listing the full name of the file, or a pathname that's specified relative to the directory in which you invoked mysql. For example, if you started mysql on a Windows machine in the C:\mysql\ directory and your script file is my_commands in the C:\scripts directory, either of the following SOURCE commands would tell mysql to run the file:

mysql> SOURCE C:\scripts\my_commands;
mysql> SOURCE ..\scripts\my_commands;

The other way to execute a script file is by naming it on the mysql command line. Invoke mysql and use the < input redirection operator to specify the file from which to read query input:

shell> mysql db_name < input_file

If a statement in a script file fails with an error, mysql ignores the rest of the file. To execute the entire file regardless of whether errors occur, invoke mysql with the --force or -f option.

A script file can itself contain SOURCE commands to execute other files. But be careful not to create a SOURCE loop. For example, if file1 contains a SOURCE file2 command, file2 should not contain a SOURCE file1 command.

3.2.6 mysql Output Formats

By default, mysql produces output in one of two formats, depending on whether you use it in interactive or batch mode:

  • When invoked interactively, mysql displays query output in a tabular format that uses bars and dashes to display values lined up in boxed columns.

  • When you invoke mysql with a file as its input source on the command line, mysql runs in batch mode with query output displayed using tab characters between data values.

To override the default output format, use these options:

  • --batch or -B
  • Produce batch mode (tab-delimited) output, even when running interactively.

  • --table or -t
  • Produce tabular output format, even when running in batch mode.

In batch mode, you can use the --raw or -r option to suppress conversion of characters such as newline and carriage return to escape-sequences like \n or \r. In raw mode, the characters are printed literally.

To select a different output format than either of the default formats, use these options:

  • --html or -H
  • Produce output in HTML format.

  • --xml or -X
  • Produce output in XML format.

3.2.7 mysql Client Commands and SQL Statements

When you issue an SQL statement while running mysql, the program sends the statement to the MySQL server to be executed. SELECT, INSERT, UPDATE, and DELETE are examples of this type of input. mysql also understands a number of its own commands that aren't SQL statements. The QUIT and SOURCE commands that have already been discussed are examples of mysql commands. Another example is STATUS, which displays information about the current connection to the server, as well as status information about the server itself. Here is what a status display might look like:

mysql> STATUS;
--------------
mysql Ver 12.22 Distrib 4.0.18, for apple-darwin7.2.0 (powerpc)


Connection id:     14498
Current database:    world
Current user:      myname@localhost
SSL:          Not in use
Current pager:     stdout
Using outfile:     ''
Server version:     4.0.18-log
Protocol version:    10
Connection:       Localhost via UNIX socket
Client characterset:  latin1
Server characterset:  latin1
UNIX socket:      /tmp/mysql.sock
Uptime:         15 days 1 hour 9 min 27 sec

Threads: 4 Questions: 78712 Slow queries: 0 Opens: 786 Flush tables: 1
Open tables: 64 Queries per second avg: 0.061
--------------

A full list of mysql commands can be obtained using the HELP command.

mysql commands have both a long form and a short form. The long form is a full word (such as SOURCE, STATUS, or HELP). The short form consists of a backslash followed by a single character (such as \., \s, or \h). The long forms may be given in any lettercase. The short forms are case sensitive.

Unlike SQL statements, mysql commands cannot be entered over multiple lines. For example, if you issue a SOURCE file_name command to execute statements stored in a file, file_name must be given on the same line as SOURCE. It may not be entered on the next line.

By default, the short command forms are recognized on any input line, except within quoted strings. The long command forms aren't recognized except at the mysql> primary prompt. For example, CLEAR and \c both clear (cancel) the current command, which is useful if you change your mind about issuing the statement that you're currently entering. But CLEAR isn't recognized after the first line of a multiple-line statement, so you should use \c instead. To have mysql recognize the long command names on any input line, invoke it with the --named-commands option.

3.2.8 Using the --safe-updates Option

It's possible to inadvertently issue statements that modify many rows in a table or that return extremely large result sets. The --safe-updates option helps prevent these problems. The option is particularly useful for people who are just learning to use MySQL. --safe-updates has the following effects:

  • UPDATE and DELETE statements are allowed only if they include a WHERE clause that specifically identifies which records to update or delete by means of a key value, or if they include a LIMIT clause.

  • Output from single-table SELECT statements is restricted to no more than 1,000 rows unless the statement includes a LIMIT clause.

  • Multiple-table SELECT statements are allowed only if MySQL will examine no more than 1,000,000 rows to process the query.

The --i-am-a-dummy option is a synonym for --safe-updates.

  • + Share This
  • 🔖 Save To Your Account

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020