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, or sqlcmd)
  • Valid login credentials: username, password, hostname (e.g., localhost or an IP), and optionally port number
  • Network access if connecting to a remote server (firewall rules, allowed IP addresses)

Step-by-Step

  1. Verify the SQL server is running. Before connecting, ensure your database service is active. On Windows, open Task Manager and check for MySQL, Postgres, or sqlservr processes. On macOS or Linux, run systemctl status mysql (or postgresql, mssql-server for SQL Server) in the terminal. If it’s not running, start it using sudo systemctl start mysql (adjust for your service and Linux distro) or via the Services app on Windows.
  2. 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).
  3. Identify which SQL client you need. Different servers use different command-line tools:
    • MySQL: use mysql
    • PostgreSQL: use psql
    • Microsoft SQL Server: use sqlcmd
    Run which mysql, which psql, or which sqlcmd (on macOS/Linux) or where 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.
  4. 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 -P to be prompted for the password securely.
  5. 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 for sqlcmd). 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)
    If you get results, the connection is successful.
  6. Exit the client. Type EXIT; or \q (PostgreSQL), then press Enter. In sqlcmd, type QUIT or EXIT.

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.cnf or postgresql.conf) or use the service manager to confirm the active port.
  • Missing -p flag: In MySQL and PostgreSQL, omitting -p means no password is requested—even if your account has one. Always include -p to 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 root on MySQL or postgres on 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) or PGPASSWORD (PostgreSQL) to avoid typing passwords repeatedly in scripts. Never commit these to version control.
  • Save credentials securely: Create a .my.cnf file in your home directory for MySQL (with mode 600) containing [client] and user/password lines. PostgreSQL uses .pgpass with format host: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. In mysql, press Ctrl+R to search command history.

Troubleshooting

If you can’t connect, follow these checks in order:

  1. Is the server running? If you see Can’t connect to MySQL server on 'localhost' (10061) or connection refused, the service is likely stopped. Restart it and verify with systemctl status or task manager.
  2. Check your host and port: Is the host localhost or 127.0.0.1? Some systems bind only to one. Try both. Confirm the port matches the server’s configuration.
  3. 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 telnet or nc -zv <host> <port>.
  4. Authentication errors: Access denied for user means wrong credentials or user permissions. Verify the username exists and has access from your host (e.g., in MySQL, check SELECT host,user FROM mysql.user;). For PostgreSQL, check pg_hba.conf for host-based rules.
  5. Missing client tools: If command not found appears, install the client package. On Ubuntu, sudo apt install mysql-client or postgresql-client. On Windows, download the Microsoft Command Line Utilities for SQL Server from Microsoft’s site.
  6. SSL/TLS issues: If you see SSL connection error or similar, try adding --ssl-mode=DISABLED (MySQL) or sslmode=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 just localhost), 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 uses my.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 via ps aux. Use the -p flag to be prompted, or store credentials in a protected config file (e.g., .my.cnf with mode 600) instead.