To run SQL commands from the command line using a username and password, you typically use a database client like mysql for MySQL/MariaDB or psql for PostgreSQL. You must have the database client installed, network access to the server (if remote), and valid credentials. This method lets you execute queries, scripts, or batch operations without a GUI.

What You'll Need

  • A database server (e.g., MySQL, MariaDB, or PostgreSQL) running and accessible
  • The corresponding command-line client installed on your machine (mysql or psql)
  • Your database username and password
  • The hostname or IP address of the database server (use localhost for local connections)
  • For remote connections: correct firewall rules, network access, and user permissions (e.g., GRANT privileges)

Step-by-Step

  1. Verify the client is installed: Open a terminal (Linux/macOS) or Command Prompt/PowerShell (Windows) and type mysql --version or psql --version. If you see version output, the client is installed. If not, install it: on Ubuntu/Debian, run sudo apt install mysql-client or sudo apt install postgresql-client; on macOS with Homebrew, use brew install mysql-client or brew install postgresql; on Windows, download the official installer from MySQL or PostgreSQL websites.
  2. Connect to the database using credentials: Use the following syntax:
    • For MySQL/MariaDB: mysql -h hostname -u username -p
    • For PostgreSQL: psql -h hostname -U username -d database_name
    Replace hostname with localhost (or your server’s IP/domain), username with your database user (e.g., root or admin), and database_name with the target database (PostgreSQL requires this, MySQL does not for initial login). After pressing Enter, you’ll be prompted to enter the password—type it carefully (no characters appear for security).
  3. Execute a test command: Once connected, run a simple command to verify access:
    • In MySQL: SELECT 1; or SHOW DATABASES;
    • In PostgreSQL: SELECT version(); or \l (lists databases)
    If the command returns results, your connection and credentials are correct.
  4. Run a SQL script or inline command: To avoid interactive prompts, execute a single command directly:
    • MySQL: mysql -h hostname -u username -p -e "SELECT * FROM users;" database_name
    • PostgreSQL: psql -h hostname -U username -d database_name -c "SELECT * FROM users;"
    Replace the SQL statement inside quotes. You’ll still be prompted for the password unless you use environment variables (see Tips).
  5. Run a SQL file (batch script): Save your SQL commands in a file (e.g., query.sql), then run:
    • MySQL: mysql -h hostname -u username -p database_name < query.sql
    • PostgreSQL: psql -h hostname -U username -d database_name -f query.sql
    This is ideal for migrations, bulk inserts, or scheduled tasks.

Common Mistakes

  • Typing the password on the command line: Avoid -p password (e.g., mysql -u root -p mypass). This exposes your password in shell history and process lists. Always use -p without a value to trigger a secure prompt.
  • Forgetting the database name in PostgreSQL: PostgreSQL requires the -d flag with a database name for most commands. Omitting it causes errors like psql: error: FATAL: database "username" does not exist.
  • Using the wrong port: Default ports are 3306 (MySQL) and 5432 (PostgreSQL). If your server uses non-default ports, add -P port_number (MySQL) or -p port_number (PostgreSQL).
  • Case sensitivity in PostgreSQL usernames: PostgreSQL treats unquoted identifiers as lowercase. If your user is created as "AdminUser" (with quotes), you must specify -U "AdminUser" with quotes.
  • Assuming localhost works for remote servers: If connecting to a remote database, ensure the server allows remote connections (e.g., MySQL’s bind-address is not 127.0.0.1, and the user has remote host permissions like 'user'@'%').

Tips

  • Use environment variables for non-interactive scripts: Set MYSQL_PWD (MySQL) or PGPASSWORD (PostgreSQL) in your shell session or script. Example: export PGPASSWORD="yourpass" && psql -h localhost -U admin -d mydb -c "SELECT 1;". Note: This is only safe in private, non-shared scripts—never commit credentials to version control.
  • Test connectivity first: Use telnet hostname 3306 (MySQL) or nc -zv hostname 5432 (PostgreSQL) to confirm the port is open before troubleshooting credentials.
  • Use ~/.my.cnf or ~/.pgpass for saved credentials: Create a secure config file (e.g., ~/.pgpass with format hostname:port:database:username:password) and set permissions to 600. This avoids repeated prompts while keeping passwords out of commands.
  • Check SSL/TLS requirements: Some databases enforce SSL. Add --ssl-mode=REQUIRED (MySQL) or sslmode=require (PostgreSQL) if you see SSL-related errors.

Troubleshooting

If you cannot connect or run commands, follow these checks:

  1. Can you reach the server? Ping the hostname or use telnet hostname port. If it hangs or fails, the issue is network/firewall—not credentials. Verify the server is running, accessible on the correct port, and your network allows outbound traffic to that port.
  2. Is the username/password correct? Double-check for typos, extra spaces, or invisible characters. Try logging in via a GUI tool (e.g., phpMyAdmin, pgAdmin) to confirm credentials work elsewhere. For MySQL, test with mysql -u root -p -e "SELECT USER();"—if it shows root@localhost, you’re authenticated.
  3. Are permissions granted? In MySQL, run SHOW GRANTS FOR 'username'@'host'; (as root). In PostgreSQL, use \du+ in the psql shell to list roles and privileges. Ensure the user has SELECT or other needed rights on the target database/table.
  4. Is the database name correct? MySQL commands fail silently if you specify a nonexistent database. List databases first: SHOW DATABASES; (MySQL) or \l (PostgreSQL).
  5. Is the client version compatible? Older clients may not support newer server protocols. Try updating the client (e.g., sudo apt update && sudo apt upgrade mysql-client).
  6. Check error messages carefully: Common errors include:
    • ERROR 1045 (28000): Access denied → Wrong credentials or user permissions.
    • FATAL: password authentication failed (PostgreSQL) → Password mismatch or pg_hba.conf misconfiguration (requires server-side edit).
    • Can't connect to MySQL server → Server is down, unreachable, or port blocked.

Frequently Asked Questions

Can I run SQL commands without entering a password interactively?

Yes—use environment variables like PGPASSWORD or MYSQL_PWD, or store credentials in ~/.pgpass (PostgreSQL) or ~/.my.cnf (MySQL). Always restrict file permissions to 600 and avoid hardcoding passwords in scripts.

Why does my PostgreSQL connection ask for a password even when using -U?

PostgreSQL uses pg_hba.conf to define authentication methods. If the entry for your connection type (e.g., host all all 0.0.0.0/0 md5) specifies md5 or scram-sha-256, it requires a password. Change the method to trust only for local testing (not recommended in production).

How do I connect to a remote database over the internet?

Ensure the database server listens on a public IP (not just 127.0.0.1), open the port (3306/5432) in its firewall, and confirm the user account has remote access (e.g., 'user'@'%' in MySQL). Prefer SSH tunneling for security: ssh -L 3307:localhost:3306 user@server, then connect to localhost:3307.

Can I use special characters in my password?

Yes, but escape them properly in scripts. In shell, wrap the password in single quotes (e.g., 'p@ss#word!') to avoid shell interpretation. For -p prompts, special characters are handled safely by the client.

What’s the difference between -e in MySQL and -c in PostgreSQL?

Both execute a single SQL statement and exit. MySQL uses -e "statement" and requires the database name after flags. PostgreSQL uses -c "statement" and needs -d for the database. Neither supports multi-line statements with -e/-c—use -f with a file instead.

Why do I get "Access denied for user 'root'@'localhost'" in MySQL?

On fresh installations, root may require sudo (e.g., sudo mysql) if using auth_socket authentication. To enable password login, run ALTER USER 'root'@'localhost' IDENTIFIED BY 'newpass'; as root via socket, then use -p normally.