MySQL Run SQL Queries From A Shell Prompt / Command Line

by Vivek Gite on May 4, 2008 · 10 comments

Q. How do I specify MySQL SQL queries on the UNIX / Linux command line?

A. mysql command line has option to execute the SQL statement and quit. This is also useful for running sql queries from a shell script. Following is the syntax:

mysql -u user -p -e 'SQL Query' database

Where,
-u : Specify mysql database user name
-p : Prompt for password
-e : Execute sql query
database : Specify database name
To list all database, enter:
$ mysql -u vivek -p -e 'show databases;'
To list count all rows, enter:
$ mysql -u vivek -p -e 'SELECT COUNT(*) FROM quotes' cbzquotes
Sample output:

Enter password:
+----------+
| count(*) |
+----------+
|      471 |
+----------+

Tell mysql to display output a page at a time, by using more or less pager:
$ mysql --pager=/usr/bin/less -u vivek -p -e 'SELECT COUNT(*) FROM quotes' cbzquotes
Redirect out to a file:
$ mysql -u vivek -p 'PassWord' -e 'SELECT COUNT(*) FROM quotes' cbzquotes > sql.output.txt
To avoid password prompt just create ~/my.cnf file:

[client]
# for local server
#host=localhost
host=10.0.1.100
user=vivek
password=myPassword
[mysql]
pager=/usr/bin/less

Featured Articles:

Share this with other sys admins!
Facebook it - Tweet it - Print it -

{ 10 comments… read them below or add one }

1 Leopoldo Maestro May 5, 2008

Very useful.

Thank you

Reply

2 Andrew McGregor July 27, 2009

One correction is that in Linux then options file must be called:
~/.my.cnf

Reply

3 Barry July 6, 2010

Very helpful, but any idea how to get a statement line:

select * from users where fname=’Dave’

to work? I just cannot find a way to eacape the quote characters and it’s driving me nuts!!

Reply

4 damdaray August 19, 2010

thanks for helpful working. ı looked for a long time this soul’s answer.thanks again…

Reply

5 Gerald Mutisya October 22, 2010

Try using double quotes for the SQL statement – worked for me.
i.e. mysql -e “select * from users where fname=’Dave’” dbname

Reply

6 Shravan November 10, 2010

Helpful article. Thanks to Vivek Gite

Reply

7 Greg November 17, 2010

I wish I had read these comments earlier, that double quote requirement wasted about 30 minutes of my time today..lol

Oh well… and thanks for the article… I’m using it in a perl script via a system call :)

Reply

8 guru January 18, 2011

Its very usefull thak you very much….

Reply

9 Shiva May 30, 2011

getting error 1045

Reply

10 vinod pardhi August 29, 2011

Thank you very much, it saved lot of time of mine………..

Reply

Leave a Comment

You can use these HTML tags and attributes for your code and commands: <strong> <em> <ol> <li> <u> <ul> <blockquote> <pre> <a href="" title="">
What is 15 + 6 ?
Please leave these two fields as-is:
Solve the simple math so we know that you are a human and not a bot.




Previous post:

Next post: