Entering an SQL One-Liner

Problem

You want to specify a statement to be executed directly on the mysql command line.

Solution

mysql can read a statement from its argument list.

Discussion

To execute a statement directly from the command line, specify it using the -e (or --execute) option. For example, to find out how many rows are in the limbs table, run this command:

%mysql -e "SELECT COUNT(*) FROM limbs" cookbook
+----------+
| COUNT(*) |
+----------+
|       12 |
+----------+

To execute multiple statements this way, separate them with semicolons:

%mysql -e "SELECT COUNT(*) FROM limbs;SELECT NOW()" cookbook
+----------+
| COUNT(*) |
+----------+
|       12 |
+----------+
+---------------------+
| NOW()               |
+---------------------+
| 2006-07-04 10:42:22 |
+---------------------+

By default, results generated by statements that are specified with -e are displayed in tabular format if output goes to the terminal, and in tab-delimited format otherwise. To learn what these different formats are, see Sending Query Output to a File or to a Program. To choose a particular format, see Selecting Tabular or Tab-Delimited Query Output Format.

Get MySQL Cookbook, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.