To run SQL command line code, you need a database server (like MySQL, PostgreSQL, or SQLite) installed locally or accessible remotely, plus a command-line client for that database. Once connected, you can execute SQL statements directly. This allows automation, scripting, and direct database management without GUI tools.
What You'll Need
- A database system installed (e.g., MySQL, PostgreSQL, SQLite, or SQL Server)
- The corresponding command-line client (usually installed with the database server)
- Valid connection credentials: hostname (or localhost), port, database name, username, and password
- A text editor for writing or reviewing SQL scripts (optional but recommended)
Step-by-Step
- Verify your database server is running. For local installations, start the service using your OS tools: on Windows, open Services and ensure the database service (e.g., "MySQL80" or "PostgreSQL x64") is running; on macOS or Linux, use
sudo systemctl start mysqlorbrew services start postgresqlas appropriate. If using a cloud-hosted database (e.g., AWS RDS), confirm it's in an "Available" state and accessible over the network. - Open a terminal or command prompt. On Windows, use Command Prompt or PowerShell; on macOS or Linux, use Terminal. Navigate to a convenient directory (e.g., your home folder) using
cd ~orcd /home/username. - Launch the database client with connection parameters. Use the correct command for your database:
- MySQL:
mysql -h hostname -P port -u username -p(e.g.,mysql -h localhost -P 3306 -u root -p). Press Enter, then type your password when prompted (no echo; press Enter again after typing). - PostgreSQL:
psql -h hostname -p port -U username -d database_name(e.g.,psql -h localhost -p 5432 -U postgres -d mydb). Enter password if required. - SQLite:
sqlite3 path/to/database.db(e.g.,sqlite3 mydata.db). If the file doesn’t exist, SQLite creates it automatically. - Microsoft SQL Server:
sqlcmd -S hostname -U username -P password(e.g.,sqlcmd -S localhost -U sa -P YourStrongPassw0rd). For security, omit-Pto be prompted for the password.
-hand-P(e.g.,mysql -u root -p). - MySQL:
- Test your connection. Once logged in, you should see a client-specific prompt (e.g.,
mysql>,mydb=>, or1>). Enter a simple SQL statement likeSELECT 1;orSELECT 'Hello World';and press Enter. A successful response (e.g.,+---+ | 1 | +---+ | 1 | +---+) confirms connectivity. - Execute your SQL command. Type your full SQL statement, ending with a semicolon
;(required for most clients), then press Enter. For multi-line commands (e.g.,CREATE TABLE), press Enter after each line—the client waits for the semicolon before executing. Example:CREATE TABLE users ( id INT PRIMARY KEY, name VARCHAR(100) NOT NULL );
- Run a SQL script file. If you have a file (e.g.,
script.sql), use the client’s "run file" command:- MySQL:
SOURCE /full/path/to/script.sql;(or\. /path/to/script.sql) - PostgreSQL:
\i /full/path/to/script.sql - SQLite:
.read /full/path/to/script.sql - SQL Server:
:r /full/path/to/script.sql(requires sqlcmd mode in SSMS; in CLI, usesqlcmd -i script.sql)
/home/user/scripts/init.sqlon Linux/macOS orC:\scripts\init.sqlon Windows) to avoid "file not found" errors. - MySQL:
- Exit the client. Type
EXIT;or\q(for PostgreSQL/SQLite), then press Enter to return to your system shell.
Common Mistakes
- Missing semicolons: Many clients (especially MySQL and SQLite) require
;to terminate statements—without it, commands hang waiting for more input. - Incorrect credentials: Typos in username, hostname, or password cause "Access denied" or "Connection refused" errors. Double-check case sensitivity (PostgreSQL usernames are case-sensitive in some contexts).
- Port mismatch: Using the wrong port (e.g., 3307 instead of 3306 for MySQL) prevents connection. Verify ports in your database config files or server logs.
- Path errors for script files: Relative paths (e.g.,
./script.sql) fail if the working directory isn’t where the file resides. Use absolute paths. - Unquoted strings: In SQL, text values need quotes:
INSERT INTO users VALUES (1, John);fails, butINSERT INTO users VALUES (1, 'John');works. - Case sensitivity: On Linux, table/column names may be case-sensitive (e.g.,
users≠Usersin PostgreSQL by default). Use double quotes for exact casing in identifiers.
Tips
- Use environment variables: Store passwords in
$MYSQL_PWD(MySQL) or$PGPASSWORD(PostgreSQL) to avoid typing them interactively (but avoid committing them to scripts). - Enable command history: In MySQL, use
mysql -h localhost -u root -p --auto-rehashfor tab completion. In PostgreSQL,psqlsaves history to~/.psql_historyby default. - Format output: In MySQL, run
\Ginstead of;for vertical output (easier to read wide tables). In SQLite, use.mode columnand.headers onfor table-like display. - Test in a safe environment: Use a local dev database for experimentation—never run
DELETEorDROPon production without backups. - Escape special characters: In SQL strings, escape single quotes with two single quotes:
'O''Brien'. - Use transactions: Wrap risky operations in
BEGIN;...COMMIT;orROLLBACK;to undo changes if something goes wrong.
Troubleshooting
If your SQL command fails, follow these checks in order:
- Confirm the server is reachable. Use
ping hostnameortelnet hostname port(e.g.,telnet localhost 3306). If telnet hangs or fails, the server isn’t listening on that port—check firewall rules or service status. - Verify credentials and permissions. Try logging in with a known-admin account (e.g.,
rootfor MySQL,postgresfor PostgreSQL). If it works, your user lacks privileges; grant them viaGRANTstatements. - Check SQL syntax. Copy the command into a text editor and compare with official docs. Common issues: missing commas in
CREATE TABLE, unquoted reserved words (e.g.,ORDERmust be"ORDER"in PostgreSQL), or unsupported commands (e.g., SQLite doesn’t supportFULL OUTER JOIN). - Review error messages carefully. MySQL errors start with
ERROR 1064 (42000):(syntax error). PostgreSQL showsERROR: syntax error at or near.... SQLite reportsSQL error: near.... Search the error code online for context-specific fixes. - Test with minimal commands. Replace your full query with
SELECT 1;to isolate connection issues from SQL logic problems. - Check file paths and permissions (for scripts). Ensure the script file exists, is readable by your user, and contains valid SQL. Run
cat script.sqlortype script.sqlto verify content. - Restart services. A simple server restart often resolves transient issues:
sudo systemctl restart mysqlorbrew services restart postgresql.
Frequently Asked Questions
Can I run SQL commands without installing a database server?
Yes, but only for lightweight or offline use. SQLite is serverless—you just need thesqlite3 CLI tool, which is often pre-installed on macOS/Linux. For web-based testing, use browser-based playgrounds like SQLFiddle or DB-Fiddle, but note they’re for learning, not persistent storage.
Why does my password not work even though I know it’s correct?
Common causes: the server uses a different authentication plugin (e.g., MySQL’scaching_sha2_password vs. mysql_native_password), the password contains special characters that need escaping in the shell (e.g., ! in Bash), or your user account is restricted to localhost connections. Try connecting via localhost instead of 127.0.0.1, or check the host field in the mysql.user table.
How do I save query results to a file from the command line?
Most clients support output redirection. In MySQL:SELECT * FROM users INTO OUTFILE '/tmp/users.csv' FIELDS TERMINATED BY ','; (ensure the path is writable and secure_file_priv permits it). In PostgreSQL: \copy users TO '/tmp/users.csv' WITH CSV; (uses client-side file access). In SQLite: .output /tmp/users.csv followed by your SELECT, then .output stdout.
Is it safe to enter passwords directly in the command line (e.g., -pMyPass)?
No—this exposes passwords in your shell history, process lists, and logs. Always omit the password flag (e.g., -p without a value) to be prompted interactively. For scripts, use configuration files (e.g., MySQL’s ~/.my.cnf with [client] section) and restrict file permissions to 600.
Can I run multiple SQL commands in one go?
Yes, separate them with semicolons (e.g.,SELECT 1; SELECT 2;). However, some clients (like SQLite) may not execute subsequent commands after an error in the first. PostgreSQL’s psql continues by default; MySQL halts on error unless you use --force.
What’s the difference between mysql and mysqladmin?
mysql is for interactive SQL execution. mysqladmin is a separate tool for administrative tasks (e.g., mysqladmin -u root -p status to check server health). Use mysql for queries and mysqladmin for server control, not data manipulation.