Running an SQL query from the command line lets you interact directly with a database without a graphical interface, making it fast, scriptable, and ideal for automation or remote servers. You need a database client installed and network access to the database server. This guide covers MySQL and PostgreSQL, the two most common open-source databases.
What You'll Need
- A working installation of MySQL or PostgreSQL client tools
- Database server address, port, username, and password
- Database name to query
- Command-line terminal (Terminal on macOS/Linux, Command Prompt or PowerShell on Windows)
- Network connectivity to the database server (if remote)
Step-by-Step
- Open your terminal or command prompt. On macOS or Linux, open Terminal. On Windows, open Command Prompt or PowerShell.
- Verify the database client is installed by typing
mysql --versionfor MySQL orpsql --versionfor PostgreSQL. If you see a version number, you’re ready. If not, install the client: on Ubuntu/Debian, usesudo apt install mysql-clientorsudo apt install postgresql-client; on macOS with Homebrew, usebrew install mysql-clientorbrew install postgresql; on Windows, download the official MySQL or PostgreSQL client package from their websites. - For MySQL, connect using:
mysql -h hostname -P port -u username -p database_name. Replacehostnamewith the server address (e.g.,localhostif local, or an IP or domain),portwith the port (default is 3306),usernamewith your database user, anddatabase_namewith the name of the database. Press Enter. You’ll be prompted for your password—type it carefully (it won’t show on screen) and press Enter. - For PostgreSQL, connect using:
psql -h hostname -p port -U username -d database_name. Replace the same fields as above. Default port is 5432. Press Enter and enter your password when prompted. - Once connected, you’ll see a prompt like
mysql>ordatabase_name=>. Type your SQL query directly, ending with a semicolon (;). For example:SELECT * FROM users WHERE active = 1;. Press Enter to execute. - To exit the SQL shell, type
quit;or\q(backslash-q) for PostgreSQL, then press Enter. - To run a query without entering the interactive shell, use the
-eflag. For MySQL:mysql -h hostname -P port -u username -p database_name -e "SELECT * FROM users WHERE active = 1;". For PostgreSQL:psql -h hostname -p port -U username -d database_name -c "SELECT * FROM users WHERE active = 1;". The query runs and outputs results directly to the terminal. - To save results to a file, append
> output.txtto the command. For example:mysql -h localhost -u root -p mydb -e "SELECT name FROM customers;" > customers_list.txt. The output will be written tocustomers_list.txtin your current directory.
Common Mistakes
- Forgetting the semicolon (;) at the end of the SQL statement—this prevents execution in interactive mode.
- Using incorrect hostname or port—double-check with your database administrator or hosting provider. Local databases often use
localhost, not127.0.0.1, though both may work. - Typing the password on the command line (e.g.,
-p mypassword)—this exposes it in shell history and process lists. Always use-palone and enter it interactively. - Using wrong case for database or table names—PostgreSQL is case-sensitive by default; MySQL depends on the OS file system. Always quote identifiers with backticks or double quotes if unsure.
- Running a query without specifying the database name—some clients require it, others don’t. Always include it to avoid "No database selected" errors.
Tips
- Use environment variables to avoid typing credentials repeatedly. Set
MYSQL_PWD(for MySQL) orPASSWORD(for PostgreSQL) in your shell profile—but be cautious about file permissions, as these may be readable by others. - For repetitive queries, create shell scripts. Save your SQL in a file like
query.sql, then runmysql -u user -p db < query.sql. - Use the
--batchflag with MySQL (or-tfor PostgreSQL) to get clean, tab-separated output ideal for scripting or importing into spreadsheets. - If you’re connecting remotely, ensure the database server allows external connections. Check firewall rules and server configuration files like
my.cnf(MySQL) orpg_hba.conf(PostgreSQL). - Use
SHOW DATABASES;in MySQL or\lin PostgreSQL to list available databases before selecting one. - Always test queries in a safe environment before running on production databases. Use
SELECTfirst to preview data beforeUPDATEorDELETE.
Troubleshooting
- "Command not found": The client isn’t installed or not in your PATH. Reinstall the client or add its directory to your system PATH.
- "Access denied": Verify username, password, and host. Ensure the user has privileges to connect from your IP address. For MySQL, check with
SELECT User, Host FROM mysql.user;(requires admin access). - "Can't connect to MySQL server": The server is offline, unreachable, or blocking your connection. Ping the server IP first. If it’s remote, check if port 3306 (MySQL) or 5432 (PostgreSQL) is open using
telnet hostname portornc -v hostname port. - "Unknown database": The database name is misspelled or doesn’t exist. Use
SHOW DATABASES;(MySQL) or\l(PostgreSQL) to list valid names. - SQL syntax error: Check for typos, missing semicolons, or unsupported functions. Use
DESCRIBE table_name;(MySQL) or\d table_name(PostgreSQL) to verify column names and structure. - Connection times out: This often indicates network issues or server overload. Try again later, or contact your hosting provider. If using a cloud database (e.g., AWS RDS), check the security group settings allow your IP.
- Results are truncated: Use
\Ginstead of;in MySQL to display results vertically, which avoids column width limits.
Frequently Asked Questions
Can I run SQL queries from the command line without installing a database client?
No. You must have the appropriate client tool installed—MySQL Client or PostgreSQL Client—to communicate with the database server. Web interfaces or GUI tools don’t replace this requirement.Is it safe to run SQL queries from the command line?
Yes, if you follow security best practices: never include passwords in commands, restrict user permissions, and avoid running queries as root or admin unless absolutely necessary.Can I run SQL queries on a remote server this way?
Yes. As long as the database server accepts remote connections, you can use the command-line client from your local machine as long as you have the correct hostname, port, credentials, and network access.What if the database requires SSL?
Add the--ssl-mode=REQUIRED flag for MySQL or sslmode=require for PostgreSQL. Example: mysql -h server.com -u user -p --ssl-mode=REQUIRED db_name.
How do I run multiple SQL statements in one command?
Separate them with semicolons. For example:mysql -u user -p db -e "SELECT * FROM users; SELECT COUNT(*) FROM orders;". Both queries execute sequentially.
Can I use this method to import data from a file?
Yes. UseLOAD DATA INFILE in MySQL or COPY in PostgreSQL. For example: mysql -u user -p db -e "LOAD DATA INFILE '/path/to/data.csv' INTO TABLE mytable FIELDS TERMINATED BY ',';". Ensure the file path is accessible to the database server, not your local machine.