Running a SQL file from the command line in MySQL lets you execute a batch of database commands—like creating tables, inserting data, or modifying schemas—without typing each line manually. This is essential for deploying scripts, restoring backups, or automating database setups. Before you begin, ensure MySQL is installed and running, you have access to the target database, and you know the correct credentials (username and password). The SQL file must be a plain text file with valid MySQL syntax, saved with a .sql extension.
What You'll Need
- A working MySQL server (version 5.7 or later recommended)
- Command-line access to the machine where MySQL is installed
- A valid MySQL username and password with sufficient privileges (e.g., CREATE, INSERT, DROP permissions)
- A SQL file (e.g.,
schema.sqlordata-import.sql) containing valid MySQL statements - The name of the target database where the SQL commands should be applied
Step-by-Step
- Open your system’s terminal or command prompt. On Windows, use Command Prompt or PowerShell. On macOS or Linux, use Terminal.
- Verify MySQL is running by typing
mysql --versionand pressing Enter. If you see a version number (e.g.,mysql 8.0.36), MySQL is installed and accessible. If not, install MySQL or add it to your system PATH. - Locate your SQL file. Note the full file path. For example, on Linux/macOS, it might be
/home/user/scripts/schema.sql. On Windows, it could beC:\Users\User\Documents\data-import.sql. Use forward slashes (/) even on Windows to avoid escaping issues. - Connect to MySQL and select the target database in one command. Use:
mysql -u username -p database_name < /path/to/your/file.sql. Replaceusernamewith your MySQL username,database_namewith the name of the database you want to modify, and/path/to/your/file.sqlwith the actual path to your SQL file. Press Enter. - When prompted, enter your MySQL password. You won’t see characters as you type—this is normal. Press Enter after typing the password.
- Wait for the command to complete. If successful, you’ll see no output (unless there are errors). The SQL file has been executed. If there are errors, they will appear in the terminal.
- To confirm execution, reconnect to MySQL:
mysql -u username -p, then enter your password. TypeUSE database_name;and runSHOW TABLES;or aSELECTquery to verify your data or schema changes.
Common Mistakes
- Using the wrong file path: If the file path is incorrect or contains spaces without quotes, MySQL won’t find the file. Always test the path in your terminal first with
ls /path/to/file.sql(Linux/macOS) ordir C:\path\to\file.sql(Windows). - Forgetting the database name: If you omit the database name from the command, MySQL won’t know where to apply the SQL, and you’ll get errors like
Unknown database. Always specify the database in the command, even if you useUSE database;inside the SQL file. - Using Windows backslashes: In Windows, using
\in the file path can cause parsing errors. Use forward slashes (/) or double backslashes (\\) consistently. - Running the command without privileges: If your MySQL user lacks permissions to create tables, insert data, or drop objects, the script will fail. Grant necessary rights using
GRANTstatements in MySQL. - Trying to run the file inside the MySQL prompt: Typing
source file.sqlinside the MySQL shell works, but using<from the system shell is more efficient for automation. Don’t mix the two approaches.
Tips
- Always back up your database before running an unknown SQL file. Use
mysqldump -u username -p database_name > backup.sqlto create a safe copy. - Use the
-v(verbose) flag to see progress:mysql -u username -p database_name < file.sql -v. Add morev’s (-vv,-vvv) to increase verbosity. - For large files, consider adding
--max_allowed_packet=512Mto avoid packet size errors:mysql -u username -p database_name --max_allowed_packet=512M < file.sql. - Test the SQL file first in a development or staging database. Never run untested scripts on production systems.
- Use absolute paths, not relative ones. Relative paths like
./script.sqlcan fail if your current directory changes during execution. - If your SQL file contains comments or statements with semicolons, ensure they’re valid MySQL syntax. Some editors add invisible Unicode characters that break execution.
Troubleshooting
- Access denied for user: Confirm your username and password. Check if the user has permission to connect from your host (e.g.,
'username'@'localhost'vs'username'@'%'). Usemysql -u username -p -h 127.0.0.1to specify the host explicitly. - File not found: Verify the path. Try copying the file to your home directory and using a simple path like
~/script.sql. On Windows, avoid spaces in paths or wrap the path in quotes:< "C:\My Folder\file.sql". - Unknown database: Make sure the database exists. Create it first with:
mysql -u username -p -e "CREATE DATABASE IF NOT EXISTS database_name;". - SQL syntax error: Open the SQL file in a text editor and check the line number indicated in the error. Common issues: missing semicolons, invalid keywords, or unsupported syntax for your MySQL version.
- Command hangs or doesn’t respond: The SQL file may contain a long-running query or infinite loop. Check for large
INSERTstatements withoutCOMMIT, or missingENDin stored procedures. UseCtrl+Cto cancel and inspect the file. - Empty output and no errors: The SQL file may contain only comments or DDL statements that don’t generate output. Verify changes by querying the database afterward.
Frequently Asked Questions
Can I run a SQL file without entering the password manually?
Yes, but it’s less secure. Use the-pYourPassword flag directly (no space): mysql -u username -pYourPassword database_name < file.sql. Avoid this on shared systems as the password may appear in command history.
Does the SQL file need to end with a semicolon?
Yes, each SQL statement should end with a semicolon. MySQL treats semicolons as statement terminators. If your file lacks them, commands may fail or run incorrectly.Can I run multiple SQL files at once?
Yes. Chain them using shell operators. On Linux/macOS:cat file1.sql file2.sql | mysql -u username -p database_name. On Windows: use type file1.sql file2.sql | mysql -u username -p database_name.
What if my SQL file has special characters or accents?
Ensure your SQL file is saved in UTF-8 encoding. Add--default-character-set=utf8mb4 to your MySQL command to handle Unicode properly: mysql -u username -p database_name --default-character-set=utf8mb4 < file.sql.
Why does my script work in phpMyAdmin but not in the command line?
phpMyAdmin may auto-detect the database or use different default settings. Command-line MySQL requires explicit database selection and strict syntax. Check for hidden characters, different MySQL versions, or missingUSE database; statements in your file.
Can I run a SQL file remotely?
Yes, if the MySQL server accepts remote connections. Use the-h flag: mysql -h your-server-ip -u username -p database_name < file.sql. Ensure the server’s firewall allows port 3306 and the user has remote access permissions.