Connecting to a SQL database via the command line allows direct, efficient interaction with your database server using SQL commands. You can run queries, manage users, create databases, and perform backups—all without a graphical interface. This guide covers connecting to common SQL servers (MySQL, PostgreSQL, Microsoft SQL Server) from the terminal. You’ll need the SQL server installed and running, plus valid login credentials (username, password, host, and optionally port).
What You'll Need
- A working installation of a SQL database server (e.g., MySQL, PostgreSQL, or Microsoft SQL Server)
- Command-line client tools installed (e.g.,
mysql,psql, orsqlcmd) - Valid login credentials: username, password, hostname (e.g.,
localhostor an IP), and optionally port number - Network access if connecting to a remote server (firewall rules, allowed IP addresses)
Step-by-Step
- Verify the SQL server is running. Before connecting, ensure your database service is active. On Windows, open Task Manager and check for
MySQL,Postgres, orsqlservrprocesses. On macOS or Linux, runsystemctl status mysql(orpostgresql,mssql-serverfor SQL Server) in the terminal. If it’s not running, start it usingsudo systemctl start mysql(adjust for your service and Linux distro) or via the Services app on Windows. - Open your system’s terminal or command prompt. On Windows, launch Command Prompt or PowerShell. On macOS, open Terminal (Applications > Utilities > Terminal). On Linux, open your default terminal emulator (e.g., GNOME Terminal, Konsole).
- Identify which SQL client you need. Different servers use different command-line tools:
- MySQL: use
mysql - PostgreSQL: use
psql - Microsoft SQL Server: use
sqlcmd
which mysql,which psql, orwhich sqlcmd(on macOS/Linux) orwhere mysql(on Windows) to confirm the tool is installed and in your system’s PATH. If not found, install the client tools—e.g., via package manager (sudo apt install mysql-client) or official installer from the vendor’s site. - MySQL: use
- Connect using the correct command syntax. Replace placeholders (in angle brackets) with your actual values:
- MySQL:
mysql -h <host> -P <port> -u <username> -p
Press Enter, then type your password (it won’t show as you type). Example:mysql -h localhost -P 3306 -u root -p - PostgreSQL:
psql -h <host> -p <port> -U <username> -d <dbname>
Example:psql -h localhost -p 5432 -U postgres -d mydb
Optionally, include the password in the command for automation (not recommended for security):PGPASSWORD='mypassword' psql ... - Microsoft SQL Server:
sqlcmd -S <server> -U <username> -P <password>
Example:sqlcmd -S localhost -U sa -P 'MyStr0ngP@ssw0rd'
Or omit-Pto be prompted for the password securely.
- MySQL:
- Test your connection. Once connected, you should see a prompt specific to the tool (e.g.,
mysql>,mydb=>for PostgreSQL, or a new line with no prompt forsqlcmd). Run a simple query to verify:SELECT 1;(works on all three)SHOW DATABASES;(MySQL only)\l(PostgreSQL to list databases)SELECT name FROM sys.databases;(SQL Server)
- Exit the client. Type
EXIT;or\q(PostgreSQL), then press Enter. Insqlcmd>, typeQUITorEXIT.
Common Mistakes
- Wrong port number: Default ports are 3306 (MySQL), 5432 (PostgreSQL), and 1433 (SQL Server), but administrators often change them. Double-check your server’s configuration file (e.g.,
my.cnforpostgresql.conf) or use the service manager to confirm the active port. - Missing
-pflag: In MySQL and PostgreSQL, omitting-pmeans no password is requested—even if your account has one. Always include-pto be prompted, or explicitly provide-p'password'(no space after-p). - Quoting passwords with spaces: If your password contains spaces or special characters, wrap it in quotes (e.g.,
-p'pass word!') or escape characters. In bash, avoid spaces:-p'Pass 123'is safer than-p Pass 123. - Case sensitivity: PostgreSQL usernames and database names are case-sensitive in some contexts. Use lowercase unless explicitly configured otherwise. MySQL table names may be case-sensitive on Linux but not Windows.
- Running commands as root without permission: Connecting as
rooton MySQL orpostgreson PostgreSQL is common for local dev, but many servers restrict remote root access for security. Use a dedicated user for remote connections.
Tips
- Use environment variables for convenience: Set
MYSQL_PWD(MySQL) orPGPASSWORD(PostgreSQL) to avoid typing passwords repeatedly in scripts. Never commit these to version control. - Save credentials securely: Create a
.my.cnffile in your home directory for MySQL (with mode600) containing[client]anduser/passwordlines. PostgreSQL uses.pgpasswith formathost:port:database:username:password. - Test connectivity first: Use
telnet <host> <port>(e.g.,telnet localhost 3306) to confirm the port is open and reachable before attempting a full SQL login. - Use TLS for remote connections: If connecting over the internet, enable SSL/TLS in your client (e.g.,
mysql --ssl-mode=REQUIRED) to encrypt your credentials and data. - Tab completion saves time: In
psql, press Tab after typing part of a command to auto-complete table or column names. Inmysql, press Ctrl+R to search command history.
Troubleshooting
If you can’t connect, follow these checks in order:
- Is the server running? If you see
Can’t connect to MySQL server on 'localhost' (10061)orconnection refused, the service is likely stopped. Restart it and verify withsystemctl statusor task manager. - Check your host and port: Is the host
localhostor127.0.0.1? Some systems bind only to one. Try both. Confirm the port matches the server’s configuration. - Firewall or security group blocking: If connecting remotely, ensure port 3306, 5432, or 1433 is open on the server’s firewall and cloud provider (e.g., AWS Security Groups). Test with
telnetornc -zv <host> <port>. - Authentication errors:
Access denied for usermeans wrong credentials or user permissions. Verify the username exists and has access from your host (e.g., in MySQL, checkSELECT host,user FROM mysql.user;). For PostgreSQL, checkpg_hba.conffor host-based rules. - Missing client tools: If
command not foundappears, install the client package. On Ubuntu,sudo apt install mysql-clientorpostgresql-client. On Windows, download theMicrosoft Command Line Utilities for SQL Serverfrom Microsoft’s site. - SSL/TLS issues: If you see
SSL connection erroror similar, try adding--ssl-mode=DISABLED(MySQL) orsslmode=disable(PostgreSQL) for testing—but only on trusted networks.
Frequently Asked Questions
Do I need to install the full database server to use the command line?
No—you only need the client tools. Most OS package managers offer lightweight client-only packages (e.g.,mysql-client, postgresql-client). The full server is only required if you want to host the database locally.
Can I connect to a remote SQL server from my laptop?
Yes, as long as the server is configured to accept remote connections (not justlocalhost), the port is open in the firewall, and you have valid credentials with remote access privileges. Many cloud providers (e.g., AWS RDS, Azure Database) require specific IP whitelisting.
How do I find the default port for my SQL server?
Check the server’s configuration file: MySQL usesmy.cnf or my.ini (port= line), PostgreSQL uses postgresql.conf (port =), and SQL Server uses SQL Server Configuration Manager under Network Configuration > Protocols.
Why does my password not show when I type it?
This is intentional for security. The terminal hides password input to prevent shoulder-surfing. Just type it and press Enter. If you press Enter without typing, you’ll get an authentication error.Can I run SQL scripts from the command line?
Yes. Use input redirection:mysql -u user -p < script.sql or psql -U user -d dbname -f script.sql. For SQL Server, use sqlcmd -S server -U user -i script.sql.
Is it safe to store my password in the command line?
Not recommended—command lines may be logged in your shell history or visible viaps aux. Use the -p flag to be prompted, or store credentials in a protected config file (e.g., .my.cnf with mode 600) instead.