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 (
mysqlorpsql) - Your database username and password
- The hostname or IP address of the database server (use
localhostfor local connections) - For remote connections: correct firewall rules, network access, and user permissions (e.g.,
GRANTprivileges)
Step-by-Step
- Verify the client is installed: Open a terminal (Linux/macOS) or Command Prompt/PowerShell (Windows) and type
mysql --versionorpsql --version. If you see version output, the client is installed. If not, install it: on Ubuntu/Debian, runsudo apt install mysql-clientorsudo apt install postgresql-client; on macOS with Homebrew, usebrew install mysql-clientorbrew install postgresql; on Windows, download the official installer from MySQL or PostgreSQL websites. - 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
hostnamewithlocalhost(or your server’s IP/domain),usernamewith your database user (e.g.,rootoradmin), anddatabase_namewith 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). - For MySQL/MariaDB:
- Execute a test command: Once connected, run a simple command to verify access:
- In MySQL:
SELECT 1;orSHOW DATABASES; - In PostgreSQL:
SELECT version();or\l(lists databases)
- In MySQL:
- 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;"
- MySQL:
- 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
- MySQL:
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-pwithout a value to trigger a secure prompt. - Forgetting the database name in PostgreSQL: PostgreSQL requires the
-dflag with a database name for most commands. Omitting it causes errors likepsql: 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-addressis not127.0.0.1, and the user has remote host permissions like'user'@'%').
Tips
- Use environment variables for non-interactive scripts: Set
MYSQL_PWD(MySQL) orPGPASSWORD(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) ornc -zv hostname 5432(PostgreSQL) to confirm the port is open before troubleshooting credentials. - Use
~/.my.cnfor~/.pgpassfor saved credentials: Create a secure config file (e.g.,~/.pgpasswith formathostname:port:database:username:password) and set permissions to600. This avoids repeated prompts while keeping passwords out of commands. - Check SSL/TLS requirements: Some databases enforce SSL. Add
--ssl-mode=REQUIRED(MySQL) orsslmode=require(PostgreSQL) if you see SSL-related errors.
Troubleshooting
If you cannot connect or run commands, follow these checks:
- 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. - 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 showsroot@localhost, you’re authenticated. - Are permissions granted? In MySQL, run
SHOW GRANTS FOR 'username'@'host';(as root). In PostgreSQL, use\du+in thepsqlshell to list roles and privileges. Ensure the user hasSELECTor other needed rights on the target database/table. - Is the database name correct? MySQL commands fail silently if you specify a nonexistent database. List databases first:
SHOW DATABASES;(MySQL) or\l(PostgreSQL). - 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). - Check error messages carefully: Common errors include:
ERROR 1045 (28000): Access denied→ Wrong credentials or user permissions.FATAL: password authentication failed(PostgreSQL) → Password mismatch orpg_hba.confmisconfiguration (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 likePGPASSWORD 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 just127.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.