Yes, you can run SQL commands directly from the command line with minimal setup: installing a lightweight SQL client like psql (PostgreSQL), mysql, or sqlite3 will let you execute queries, inspect databases, and automate tasks without a GUI. The only real prerequisite is knowing your database server’s credentials and connection details—no advanced programming is needed. Below, we walk you through the exact steps for each major database system, how to troubleshoot common failures, and best practices for efficiency.
What You'll Need
- Database server credentials (username/password, host address, port, and database name). If unsure, check with your administrator or database logs (e.g.,
psql -h localhost -U youruser -lfor PostgreSQL). - Terminal access (Linux/macOS: built-in; Windows: use Git Bash, WSL, or PowerShell with an SQL module like
sqlcmd). - Installed SQL client for your database type:
- PostgreSQL:
psql(package name varies:postgresqlon Debian/Ubuntu,psqlon macOS) - MySQL/MariaDB:
mysql(usually installed by default) - SQLite:
sqlite3(built into most OSes) - Microsoft SQL Server:
sqlcmd(install via Microsoft’s SSDT) or command-line toolmssql(pre-installed on Windows Server).
- PostgreSQL:
- (Optional) Connection string helpers like
pg_hba.conf(PostgreSQL) ormy.cnf(MySQL) to store credentials securely.
Step-by-Step
PostgreSQL (psql)
- Open a terminal and log in to PostgreSQL:
psql -h your_host -U your_user -d your_database(Replace placeholders with your actual values. If prompted for a password, enter it.)Labels may vary by OS or PostgreSQL version. On Windows with PostgreSQL installed via Chocolatey, use:
psql -U your_user -d your_database(host defaults to localhost). - Once logged in, verify you’re in the correct database by running:
\l(list databases) or\dn(list users). - Write and execute a SQL query:
SELECT * FROM your_table;PressEnterto run. For multi-line queries, use\before the line to continue:SELECT column1, column2 FROM table1 WHERE column1 = 'value' \; - Exit the session with:
\q(quit).To reconnect later, omit the
-dflag (you’ll be prompted for the database name).
MySQL/MariaDB (mysql)
- Launch MySQL in terminal:
mysql -u your_user -pWindows: Use
mysql -u your_user -p(prompt for password) ormysql -h your_host -u your_user -pto specify host. - Enter your password when prompted. You’ll see a
mysql>prompt. - Switch databases if needed:
USE your_database;Then run queries like:SELECT * FROM your_table; - Exit with:
EXIT;orquit.
SQLite (sqlite3)
- Open a terminal and navigate to your SQLite database file:
cd /path/to/your/database - Run the SQLite command-line tool:
sqlite3 your_database.db(Replace with your file name; SQLite uses.dbor.sqliteextensions.) - Execute queries directly:
SELECT * FROM your_table;SQLite will auto-complete table/column names if you typeSELECT * FROMand pressTab. - Exit with:
.exitorquit. - To create a new database, use:
sqlite3 new.dbthen runCREATE TABLE your_table (...);inside the session.
Microsoft SQL Server (sqlcmd)
- Install
sqlcmdif not already present (on Windows, pre-installed with SSDT). - Launch sqlcmd with credentials:
sqlcmd -S your_server -U your_user -P your_password -d your_databaseServer defaults to
localhostif omitted. For Windows authentication, omit-Uand-P, but include-E:sqlcmd -S your_server -E -d your_database - Run queries:
SELECT * FROM your_table;For batch execution, use:GOto split statements across lines. - Exit with:
QUIT
Common Mistakes
- Connection errors: Verify the host, port (default: 5432 for PostgreSQL, 3306 for MySQL, 1433 for SQL Server), username, and password. Check firewall rules—localhost should allow connections. For remote servers, ensure the database is configured to allow remote connections.
- Syntax errors: SQL syntax varies by dialect. Use the database’s documentation for precise syntax. For example:
- PostgreSQL: Uses
\for comments (not--). - MySQL/SQLite: Supports
--for multi-line comments. - SQL Server: Requires
GOfor batch execution.
- PostgreSQL: Uses
- Permission issues: Ensure your user has
SELECTpermissions on the tables. Grant them explicitly if needed:- PostgreSQL:
ALTER USER your_user WITH SUPERUSER;(or add to roles viapsql) - MySQL:
GRANT SELECT ON your_database.* TO 'your_user'@'%';
- PostgreSQL:
- Typo-induced failures: Use autocompletion (PostgreSQL:
TabafterSELECT * FROM; MySQL:Ctrl+Space) or tools likesqlflufffor validation.
Tips
- Save queries for reuse: Use aliases in queries for readability:
SELECT id AS 'UserID', email FROM users;Then referenceUserIDdirectly. For complex queries, save them as scripts and execute them with:psql -f script.sql(PostgreSQL) ormysql script.sql(MySQL). - Pipe data: Export query results to CSV:
psql -c "SELECT * FROM users;" -A -F',' | less(PostgreSQL;-A= aligned output,-F','= delimiter). - Debugging: Add
--sqltopsqlto show raw SQL, or useEXPLAINfor query optimization:EXPLAIN SELECT * FROM large_table; - Windows users: For SQL Server, use PowerShell’s
Import-Module Microsoft.SqlServerto enablesqlcmdcommands in pipelines:sqlcmd -S . -U your_user -P your_password -d your_db -Q "SELECT * FROM your_table" - Security: Avoid hardcoding credentials in scripts. Use environment variables or tools like
pg_hba.conf(PostgreSQL) ormy.cnf(MySQL) to manage connections securely. - Interactive mode: Enable auto-indentation in
psqlwith:SET sql_auto_prepend_comments ON;(Helps with complex queries.)
Troubleshooting
If the command line fails to connect or execute queries, follow this order:
- Check basic connectivity:
- Test if the server is reachable:
telnet your_host 5432(PostgreSQL default) ornc -zv your_host 3306(MySQL default). If no connection, verify the server is running and the host allows connections. - Restart the database service:
- PostgreSQL:
sudo service postgresql restart(Linux) or restart the Windows Service (Services.msc). - MySQL:
sudo service mysql restart(Linux) or restart the MySQL service.
- PostgreSQL:
- Test if the server is reachable:
- Verify credentials:
- Use a test query to check permissions:
SELECT * FROM information_schema.tables;(PostgreSQL/MySQL). If this fails, your user lacks access. - Test the password with a minimal query:
psql -h localhost -U your_user -d your_database -c "SELECT 1";If you get a password prompt, the password is correct; if you see an error, the user or database is wrong.
- Use a test query to check permissions:
- Check network/firewall:
- On Linux/macOS: Ensure
pg_hba.conf(PostgreSQL) ormy.cnf(MySQL) allows your connection method (e.g.,localfor localhost,hostfor remote). - On Windows: Verify the SQL Server network configuration allows remote connections in
SQL Server Configuration Manager > Protocols for [Instance Name]> TCP/IP.
- On Linux/macOS: Ensure
- Inspect logs:
- PostgreSQL: Check
/var/log/postgresql/postgresql-(Linux) or Windows Event Viewer.-main.log - MySQL: Check
/var/log/mysql/error.log(Linux) or MySQL error log in the data directory. - SQL Server: Open
SQL Server Error Login SSMS.
- PostgreSQL: Check
- Reinstall the client (last resort):
- On Linux: Reinstall PostgreSQL/MySQL:
sudo apt remove postgresql && sudo apt install postgresql(Debian/Ubuntu). - On Windows: Uninstall and reinstall the database software from the official site.
Warning: Reinstalling may delete existing databases or configurations. Backup critical data first.
- On Linux: Reinstall PostgreSQL/MySQL:
Frequently Asked Questions
How do I connect to a remote database from the command line?
Use the server’s IP address or domain name in your connection command. For example:
- PostgreSQL:
psql -h 192.168.1.100 -U your_user -d your_db - MySQL:
mysql -h 192.168.1.100 -u your_user -p - SQL Server:
sqlcmd -S 192.168.1.100 -U your_user -P your_password
my.cnf (or my.ini) to allow connections from specific IPs.
What if I get "No Such File or Directory" when using SQLite?
SQLite queries don’t require a directory—you use the database file directly. Run:
sqlite3 my_database.db
If the file exists but SQLite can’t find it, ensure you’re in the correct directory:
cd /path/to/where/my_database.db is
Then run the command-line tool again.
Can I run SQL commands from PowerShell without installing extra tools?
Yes, for SQL Server, use the built-in sqlcmd module with:
sqlcmd -S . -U your_user -P your_password -d your_db -Q "SELECT * FROM your_table"
For other databases, use PowerShell’s Invoke-Expression with a script block or pipe to mysql.exe (MySQL client). Example:
mysql.exe -u your_user -p -e "SELECT * FROM your_table"
(Note: This requires mysql.exe to be in your PATH.)
How do I export query results to a file from the command line?
Use the -o or --output-file flag with psql for PostgreSQL:
psql -c "SELECT * FROM users;" -A -o users_export.csv -F',' your_database
For MySQL, pipe to mysql_dump:
mysql -u your_user -p your_database | grep -o ".*\b" > users_export.csv
(Note: This is a simple pipe; for structured data, use mysqldump with -B for CSV output.)
What’s the fastest way to test a database connection?
Use a lightweight query that requires minimal permissions. For example:
psql -h localhost -U your_user -d your_db -c "SELECT 1"
(PostgreSQL)
or
mysql -u your_user -p -e "SELECT VERSION()"
(MySQL)
These commands don’t require table access and quickly verify the connection.
How do I reset a password for a user in the command line?
For PostgreSQL:
ALTER USER your_user WITH PASSWORD 'new_password';
For MySQL:
ALTER USER 'your_user'@'%' IDENTIFIED BY 'new_password';
(Replace '%' with a specific host if needed, e.g., 'your_host'.) For SQL Server, reset via SSMS or use sqlcmd with:
EXEC sp_set_password @username='your_user', @password='new_password', @confirm_password='new_password';
Can I use the command line to create a new database?
Yes! For PostgreSQL:
createdb your_new_database
For MySQL:
CREATE DATABASE your_new_database;
(You’ll need to run these via psql or mysql client, or use the command-line tools directly. For example, to create via mysql shell, use CREATE DATABASE your_new_database; as shown above.)