Knowledgebase

How to Run MySQL/MariaDB Queries Directly from the Linux Command Line?

If you are in charge of managing a database server, from time to time you may need to run a query and inspect it carefully. While you can do that from the MySQL / MariaDB shell, but this tip will allow you to execute the MySQL/MariaDB Queries directly using the Linux command line AND save the output to a file for later inspection (this is particularly useful if the query return lots of records).

 

Let us look at some simple examples of running queries directly from the command line before we can move to a more advanced query.

 

To view all the databases on your server, you can issue the following command:

# mysql -u root -p -e "show databases;"

 

Next, to create a database table named tutorials in the database rootadminzdb, run the command below:

$ mysql -u root -p -e "USE rootadminzdb; CREATE TABLE tutorials(tut_id INT NOT NULL AUTO_INCREMENT, tut_title VARCHAR(100) NOT NULL, tut_author VARCHAR(40) NOT NULL, submissoin_date DATE, PRIMARY KEY (tut_id));"

 

We will use the following command and pipe the output to the tee command followed by the filename where we want to store the output.

 

For illustration, we will use a database named employees and a simple join between the employees and salaries tables. In your own case, just type the SQL query between the quotes and hit Enter.

 

Note that you will be prompted to enter the password for the database user:

# mysql -u root -p -e "USE employees; SELECT DISTINCT A.first_name, A.last_name FROM employees A JOIN salaries B ON A.emp_no = B.emp_no WHERE hire_date < '1985-01-31';" | tee queryresults.txt

 

View the query results with the help of cat command.

# cat queryresults.txt

 

With the query results in a plain text file, you can process the records more easily using other command-line utilities.

  • Run MySQL/MariaDB Queries through command line
  • 0 Users Found This Useful
Was this answer helpful?

Related Articles

How to upload a file using File Manager in cPanel

Sometimes it's necessary to upload files to your cPanel account. This can be easily accomplished...

How to configure custom name servers

If you have a reseller, you can set up and use custom name servers. For example, if your domain...

How to Create WHM Accounts/Master/Alpha in Zamfoo ??

1. Login to your WHM 2. Click on Add Package 3. Create a Package for Reseller/MasterReseller...

How to add a package in WHM?

How do I add, edit and delete packages in WHM? The following article explains how to add, edit...

How to Configure PayPal in WHMCS

Part 1: Initial Setup in WHMCS    Begin by going to Setup > Payment Gateways in WHMCS....