To run a SQL file from the Linux command line, you use the command-line interface (CLI) tool associated with your specific database engine (such as mysql, psql, or sqlite3) and pipe the file into the tool or use a source command. For example, in MySQL, the standard command is mysql -u username -p database_name < file.sql. This process allows you to automate database migrations, restore backups, and execute complex schema changes without manually copying and pasting code into an interactive shell.

What You'll Need

  • A Linux terminal (Bash, Zsh, etc.) with access to the server hosting the database.
  • The database client tool installed (e.g., mysql-client, postgresql-client, or sqlite3).
  • A valid .sql file containing the queries you wish to execute.
  • Administrative or user credentials (username and password) with sufficient permissions to modify the target database.
  • The name of the target database where the script should be applied.

Step-by-Step

  1. Locate your SQL file: Open your terminal and navigate to the directory where your .sql file is stored using the cd command. For example, if your file is in the Downloads folder, type cd ~/Downloads. You can verify the file exists by typing ls -l to see a list of files in the current directory.
  2. Identify your Database Engine: Different databases use different command-line tools. You must use the tool that matches your installation. Common tools include mysql for MySQL/MariaDB, psql for PostgreSQL, and sqlite3 for SQLite.
  3. Execute the command based on your engine:
    • For MySQL / MariaDB: Use the redirection operator (<) to feed the file into the mysql client. Run: mysql -u [username] -p [database_name] < [filename].sql. After pressing Enter, the system will prompt you for your password. Replace [username] with your DB user and [database_name] with the target schema.
    • For PostgreSQL: Use the psql tool. The syntax is: psql -U [username] -d [database_name] -f [filename].sql. The -f flag specifically tells PostgreSQL to read commands from a file. Depending on your configuration, you may be prompted for a password or required to use a .pgpass file.
    • For SQLite: Since SQLite uses a local file as the database, the command is: sqlite3 [database_file].db < [filename].sql. This will execute the script against the specified database file.
  4. Verify Execution: Once the command finishes and returns you to the prompt, log into the database interactively to ensure the changes were applied. For example, in MySQL, type mysql -u username -p, then USE database_name; followed by SHOW TABLES; or a SELECT statement to verify the data.
  5. Check for Errors: If the command line returns an error immediately, review the output. If the script was very long, you can redirect the output to a log file to find the exact line where it failed: mysql -u username -p database_name < file.sql 2> error_log.txt.

Common Mistakes

One of the most frequent errors is attempting to run the command without specifying the database name. In MySQL and PostgreSQL, the client needs to know which schema to apply the changes to. If you omit the database name, the server will return an "No database selected" error. Always ensure the database exists before running the script; if it doesn't, you must create it first using CREATE DATABASE name;.

Another common mistake is using the wrong redirection operator. Using > instead of < will not execute the file; instead, it will take the output of the command and overwrite your SQL file with that output, potentially deleting your entire script. Always double-check that the arrow points toward the database client (<).

Permission issues are also common. Users often try to run a script as a standard Linux user when the database requires root or administrative privileges. If you receive an "Access Denied" error, ensure you are using the correct database user (e.g., -u root) and that the Linux user has read permissions for the .sql file itself.

Finally, many users forget that the command line does not automatically "commit" changes in some environments. While most .sql files include a COMMIT; statement at the end, if your script uses transactions and fails halfway through, you may end up with a partially updated database if you haven't handled transaction blocks correctly.

Tips

To improve security, avoid putting the password directly in the command string (e.g., -ppassword123). This is dangerous because the password will be visible in the shell history (the .bash_history file) to any other user on the system. Always use the -p flag alone and enter the password when prompted, or use a configuration file like .my.cnf for MySQL or .pgpass for PostgreSQL to store credentials securely.

For very large SQL files (several gigabytes), the standard redirection method can sometimes be slow or time out. In these cases, logging into the database first and using the internal source command is often more stable. For MySQL, log in and then run SOURCE /path/to/file.sql;. This tells the server to pull the file directly, which can be more efficient for massive datasets.

If you are automating these scripts via a Cron job or a shell script, use the full path to the SQL file (e.g., /home/user/db/backup.sql) rather than a relative path. This prevents the script from failing if the Cron environment starts in a different working directory than you expect.

When testing a new script, always run it against a staging or development database first. A single DROP TABLE command in a script executed via the command line happens instantly and irreversibly if you do not have a recent backup. Always run a mysqldump or pg_dump before executing an unknown script on production data.

Troubleshooting

If the command fails, first check the connection. Try to log in to the database interactively using mysql -u username -p or psql -U username. If you cannot log in manually, the issue is with your credentials or the database server status, not the SQL file. Check if the database service is running using systemctl status mysql or systemctl status postgresql.

If you encounter a "File not found" error, verify your current directory with pwd. Ensure that the filename is spelled exactly as it appears in the file system, including case sensitivity, as Linux is case-sensitive (Backup.sql is different from backup.sql).

If the script runs but the data doesn't change, check for transaction errors. If the SQL file contains BEGIN TRANSACTION but lacks a COMMIT at the end, the changes will be rolled back automatically when the session closes. Open the file in a text editor like nano or vim and ensure it ends with a commit statement.

For encoding errors (such as strange characters in your data), specify the character set in your command. For MySQL, you can add --default-character-set=utf8mb4 to the command to ensure that special characters and emojis are handled correctly during the import process.

Frequently Asked Questions

Can I run a SQL file without knowing the password?

No. For security reasons, you must provide valid credentials. However, if you are the root user on a Linux system using MySQL, you might be able to connect via a socket without a password using sudo mysql, depending on the server's authentication plugin configuration.

How do I run a SQL file on a remote server?

You can add the host flag to your command. For MySQL, use -h [hostname_or_ip]. For example: mysql -h 192.168.1.10 -u username -p database_name < file.sql. Ensure the remote server is configured to allow external connections and that the firewall port (usually 3306 for MySQL or 5432 for Postgres) is open.

What is the difference between < and SOURCE?

The < operator is a shell feature that redirects a file into the program's standard input. The SOURCE command is an internal database command used after you have already logged into the database shell. SOURCE is generally preferred for very large files as it provides better feedback within the CLI.

Can I run only a specific part of a SQL file?

Not directly from the command line. You would need to split the file into smaller files using the split command or a text editor, or use a tool like sed to extract specific line ranges into a temporary file before executing that temporary file.

Why is my command hanging and not finishing?

This usually happens with very large files or complex queries (like creating indexes on millions of rows). The terminal doesn't show a progress bar by default. You can use the pv (pipe viewer) utility to see progress: pv file.sql | mysql -u username -p database_name. This will show you a progress bar and the data transfer rate.