Running an SQL file from the command line lets you execute database scripts—like creating tables, inserting data, or running queries—without opening a GUI tool. This works with most relational databases (e.g., MySQL, PostgreSQL, SQLite), and requires the database client tools installed and accessible from your terminal.

What You'll Need

  • A database server running (e.g., MySQL, PostgreSQL, SQLite) or a local database file (for SQLite)
  • The corresponding command-line client installed (e.g., mysql, psql, sqlite3)
  • Valid connection details: host, port, username, password (or use environment variables)
  • The SQL file (e.g., script.sql) saved locally with correct syntax for your database

Step-by-Step

  1. Verify your database client is installed and accessible: Open a terminal (Command Prompt on Windows, Terminal on macOS/Linux). Type mysql --version, psql --version, or sqlite3 --version (depending on your database). If you see a version number, you’re ready. If not, install the client via your OS package manager (e.g., apt install mysql-client on Ubuntu) or official installer.
  2. Navigate to your SQL file directory: Use cd /path/to/your/sql/file to reach the folder containing your .sql file. Confirm with ls (macOS/Linux) or dir (Windows) to ensure the file appears.
  3. Open the connection to your database: Use the appropriate command with your credentials. For example:
    • MySQL: mysql -h localhost -P 3306 -u your_username -p your_database_name
      Replace your_username, your_database_name, and optionally host/port. After pressing Enter, enter your password when prompted (it won’t show as you type).
    • PostgreSQL: psql -h localhost -p 5432 -U your_username -d your_database_name
      Same as above—replace placeholders. You’ll be prompted for a password unless you set up .pgpass.
    • SQLite: sqlite3 path/to/your_database.db
      SQLite doesn’t need a server. Replace path/to/your_database.db with the actual database file path; if it doesn’t exist, it will be created automatically.
  4. Execute the SQL file from inside the client: Once connected, use the database’s built-in command to run the file:
    • MySQL: At the mysql> prompt, type source /full/path/to/script.sql; or \. /full/path/to/script.sql (on Windows, use forward slashes or escape backslashes). Example: source /home/user/scripts/create_tables.sql;
    • PostgreSQL: At the =# prompt, type \i '/full/path/to/script.sql' (note the single quotes around the path). Example: \i '/Users/you/scripts/insert_data.sql'.
    • SQLite: At the sqlite> prompt, type .read '/full/path/to/script.sql'. Example: .read '/tmp/update_schema.sql'.
  5. Or, run the file directly from your shell (bypassing interactive mode): For automation or one-off runs, pipe the file through the client:
    • MySQL: mysql -h localhost -u your_username -p your_database_name < /path/to/script.sql
      Enter your password when prompted.
    • PostgreSQL: psql -h localhost -U your_username -d your_database_name -f /path/to/script.sql
      The -f flag tells psql to execute the file and exit.
    • SQLite: sqlite3 /path/to/your_database.db < /path/to/script.sql
      No password needed.
  6. Verify execution success: After running, check for success messages (e.g., Query OK, 10 rows affected in MySQL) or errors. In PostgreSQL, psql shows row counts; in SQLite, you’ll see ok or error messages. You can also query your database to confirm changes (e.g., SELECT COUNT(*) FROM your_table;).

Common Mistakes

  • Forgetting to specify the database name (e.g., omitting -d your_database in PostgreSQL or your_database_name in MySQL), causing "No database selected" errors.
  • Using Windows-style backslashes in paths on macOS/Linux (e.g., C:\scripts\file.sql), which break the command. Use forward slashes or quotes.
  • Typing the file path incorrectly—especially missing spaces or quotes around paths with spaces (e.g., /my documents/script.sql should be "/my documents/script.sql" or /my\ documents/script.sql).
  • Running the file without proper privileges (e.g., a user lacking CREATE or INSERT permissions).
  • Assuming SQLite needs a running server—SQLite reads/writes directly to the database file and requires no daemon.

Tips

  • Use environment variables for passwords (e.g., MYSQL_PWD='secret' mysql ...) to avoid interactive prompts—ideal for scripts—but never hardcode them in shared scripts.
  • For large files, add --verbose (MySQL) or -v (PostgreSQL/SQLite) to see each command as it runs.
  • Test your SQL file first in a safe environment (e.g., a development database) to avoid unintended changes to production data.
  • Include USE your_database; at the top of your SQL file for MySQL to ensure it targets the right database, even if omitted in the command.
  • Always end your SQL file with a semicolon (;) on the last line to prevent silent truncation.

Troubleshooting

If execution fails, follow these checks in order:

  1. Is the database server running?: For MySQL/PostgreSQL, run systemctl status mysql or pg_isready (PostgreSQL) to confirm. Restart if needed (e.g., sudo systemctl start mysql).
  2. Are credentials correct?: Double-check username, password, host, and port. Try logging in interactively first (e.g., mysql -u user -p), then exit and run the file.
  3. Does the SQL file exist and have correct syntax?: Open it in a text editor and verify no truncated lines or encoding issues (e.g., UTF-8 BOM can cause errors). Run a small test file with one simple command (e.g., SELECT 1;) to isolate the issue.
  4. Is the file path accessible?: Ensure your user has read permissions on the SQL file. On Linux/macOS, run ls -l /path/to/script.sql and use chmod +r if needed.
  5. Are dependencies missing?: If your SQL uses stored procedures, triggers, or extensions (e.g., PostgreSQL’s pgcrypto), ensure they’re installed first (CREATE EXTENSION pgcrypto;).
  6. Check error messages closely: They often specify line numbers and the failing command. For MySQL, add --force to continue after errors (use cautiously); for PostgreSQL, use -v ON_ERROR_STOP=1 to halt on first error.

Frequently Asked Questions

Can I run an SQL file without entering a password?

Yes—using a .my.cnf file (MySQL), .pgpass (PostgreSQL), or by passing credentials directly in the command. For example, MySQL: mysql --defaults-extra-file=/path/to/my.cnf where my.cnf contains [client] and password=yourpass. Never commit this file to version control.

What if my SQL file has errors mid-way through?

It depends on the database and transaction handling. MySQL (with InnoDB) rolls back only the failed statement by default, but PostgreSQL wraps commands in a transaction unless you disable it. SQLite executes line-by-line. To avoid partial failures, wrap your script in explicit transactions (BEGIN; ... COMMIT;) if supported.

Can I run a SQL file on a remote database server?

Yes—just include the remote host and port in your command. For MySQL: mysql -h 192.168.1.100 -P 3306 -u user -p. Ensure the server allows remote connections (e.g., MySQL’s bind-address isn’t 127.0.0.1).

How do I run multiple SQL files in sequence?

Use shell scripting: for f in *.sql; do mysql -u user -p db < "$f"; done (bash) or chain commands with &&: mysql ... < file1.sql && mysql ... < file2.sql. The latter stops if the first fails.

Why does SQLite ignore my file?

SQLite’s .read command only executes commands while in interactive mode. If you’re using shell redirection (e.g., sqlite3 db < file.sql), ensure the file has valid SQL (no .read or other dot-commands). Dot-commands only work inside the sqlite3 shell.

Do I need to close the connection after running the file?

No—when using shell redirection or the -f flag, the client exits automatically after execution. In interactive mode, type exit; (MySQL), \q (PostgreSQL), or .quit (SQLite) to close the session cleanly.