MySQL MariaDB

How to Run a SQL Script in MySQL From the Terminal

“Scripts are an incredible feature for a database administrator. They allow you to specify and execute a set of instructions in sequential order on a given server. This makes the process of automating repetitive tasks much more accessible and approachable.

However, when creating and executing SQL scripts, you will often carry out the operations in a development editor such as MySQL Workbench, Jetbrains DataGrip, etc. Therefore, it can be challenging to determine how to run SQL scripts in an environment where you can access a terminal session.”

In this short post, we will show you how you can execute SQL scripts stored in a file straight from the terminal.

Let’s jump in.

Method 1 – Run a SQL Script From an Active Session

Suppose we have a script that changes the database to sakila, sets the session timezone, and finally fetches the first ten records from the customer table.

Start by creating the file ending in .sql extension

$ touch script.sql

We can then add the instructions of the script as shown:

use sakila;
set @@session.time_zone = 'America/Los_Angeles';
select * from sakila.customer limit 10;

Save the file and close the editor.

We can use the source or backlash command to run the script in an already active session. For example, start by connecting to the server:

mysql -u root -p

Then run the script as shown:

mysql> source script.sql

You can also specify the path to the file using absolute or relative filepaths.

Running the command above will invoke the script and run all the instructions provided in the script.

Each instruction in the script is executed sequentially.

You can also use the backslash character to invoke the script as:

mysql > \.script.sql

Similarly, if the file exists in a different location on your computer, you can specify the path in the command.

Method 2 – Run a SQL Script When Connecting to the Server

If you are not already connected to the server, you can run the script when connecting to the server by using the less-than-operator.

The command syntax is as shown:

mysql -u username -p < /path/to/filename.sql

For example, to run the script.sql file, we can run the command:

mysql -u root -p < script.sql

MySQL will take the instructions from the script and perform each instruction sequentially.

Conclusion

In this post, you discovered two main methods of executing SQL scripts from the terminal using the source and less than operators.

Thanks for reading!!

About the author

John Otieno

My name is John and am a fellow geek like you. I am passionate about all things computers from Hardware, Operating systems to Programming. My dream is to share my knowledge with the world and help out fellow geeks. Follow my content by subscribing to LinuxHint mailing list