How do you run a single query through mysql from the command line?
Execute an SQL query in MySQL with:
Just replace user
with your username, QUERY
with your SQL code, and db_name
with your database name. After you execute, you'll be prompted to input your password. For a SELECT
statement, for example:
Don't forget, use single quotes around your query if it contains shell-sensitive characters. Here's how:
Essential tips and pro-level tricks
Running queries on remote databases
If the MySQL database is hosted remotely, include -h <hostname>
in your command:
Switch out the host
with the IP address or hostname of your MySQL server.
Viewing outputs in table format
To receive the MySQL output in tabular format - because who doesn't like organized data - incorporate the -t
flag:
You'll instantly fall in love with the carefully crafted ASCII tables!
Security is a priority
NEVER include passwords directly in the command line for the world to see. Let the MySQL client prompt for it - it's more secure and less error-prone.
Scripting for productivity
Save frequently used queries in a script file for greater efficiency:
Best practices for SQL rockstars
No more shell expansion
Mentioning -e
in single quotes keeps unwanted shell expansions at bay, making your operation more secure.
Trial before you sail
Run a safety check with a simple query before deploying larger scripts:
No interaction? No problem!
Execute your command without an interactive shell by piping the input to the MySQL client:
Always check the docs
The MySQL official documentation is your navigation guide for exploring command options and best practices. It's constantly updated and packed with details, much like this post!
Was this article helpful?