Running SQL queries via the command line is a game-changer for database admins, developers, and sysops who need speed, precision, and automation. Instead of clicking through interfaces, you directly execute queries like `SELECT * FROM users` in a terminal, pulling data instantly or altering tables with minimal overhead. This method is especially powerful for Linux/macOS systems, where most databases (MySQL, PostgreSQL, SQLite) integrate natively with shell commands. On Windows, PowerShell or the native command line (for older SQL Server versions) offers limited but effective alternatives. Without installing extra tools, you can start querying databases in under three minutes by connecting to your server and writing direct SQL commands.
What You'll Need
- A database server running MySQL, PostgreSQL, SQLite, or Microsoft SQL Server (or a local copy installed on your machine). For remote access, ensure the server has the correct firewall permissions.
- An operating system with a terminal (Linux/macOS) or command-line access via PowerShell (Windows). On Windows, newer versions of SQL Server Management Studio (SSMS) require a GUI, so command-line alternatives are best for direct queries.
- Authentication details: your username, password, or SSH keys for connecting to the remote server. For local SQLite files, just the file path is needed.
- Basic familiarity with SQL syntax (e.g., `SELECT`, `WHERE`, `JOIN`). You can always run `HELP` or `SHOW TABLES` in some shells to learn commands dynamically.
Step-by-Step
-
Choose your database client.
Start with a terminal emulator:
- Linux/macOS: Open Terminal (`Ctrl+Alt+T` or via Applications > Utilities > Terminal).
- Windows: Use PowerShell (open it via Start > Type "PowerShell") or Command Prompt (Windows 10/11). For SQL Server, connect to SSMS first and use its "SQL Command" button, but this is a GUI.
-
Connect to your database.
The exact command varies by database, but here’s how to start:
- MySQL/MariaDB: Run:
mysql -u [username] -p[password] [database_name](Press Enter to auto-fill prompts. Linux/macOS may show no password if stored in `~/.my.cnf`.) - PostgreSQL: Use psql:
psql -U [username] -d [database_name] -h [server_ip](Add `-W` to force password input; omit `-h` for localhost.) - SQLite: No server needed. Open a terminal and run:
sqlite3 [path_to_file.db](Replace `[path_to_file.db]` with your SQLite database file, e.g., `/home/user/mydb.sqlite`.) - Microsoft SQL Server (Windows): Use the native `sqlcmd` tool. First, download SQL Server Management Studio (SSMS) for setup, then run:
sqlcmd -S [server_name] -U [username] -P [password](Replace `server_name` with `localhost` for local installs; omit `-S` if connecting via SSMS’s "SQL Command" button.)
- MySQL/MariaDB: Run:
-
Verify connection and list tables.
Once connected, test your connection with:
- MySQL/PostgreSQL: Run `SHOW DATABASES;` or `\dt` (PostgreSQL).
- SQLite: Run `SELECT name FROM sqlite_master WHERE type='table';`.
- SQL Server: Use `\l` (lists databases) or `\dt` (lists tables in current DB).
-
Write your first query.
Execute basic commands like:
- Select data:
SELECT * FROM users;(Limited rows:SELECT * FROM users LIMIT 10;) - Filter records:
SELECT name, email FROM users WHERE age > 30; - Update data:
UPDATE orders SET status = 'shipped' WHERE customer_id = 123; - Drop a table (be cautious!):
DROP TABLE users;(This permanently deletes the table. Back up first if unsure.)
- Select data:
Common Mistakes
- Wrong credentials. Forgot the password? Reset it via your database admin panel or use:
ALTER USER [username] IDENTIFIED BY NEW_PASSWORD;(MySQL/PostgreSQL). Never use the root password for production—create dedicated users with minimal privileges. - Misspelled table/column names. Use `SHOW TABLES` (MySQL) or `\dt` (PostgreSQL) to confirm exact names before querying. SQLite is case-sensitive on case-sensitive filesystems (e.g., Linux).
- Syntax errors. Forgot parentheses or quotes? Use `HELP [command]` (e.g., `HELP SELECT`) to see valid syntax. For example, `SELECT` requires `FROM`:
SELECT * FROM users;Not:SELECT * users; - Permission issues. Some queries require `GRANT` privileges. Ask your DB admin to add you to the `DBA` role or run:
ALTER USER [username] WITH MAX_QUERY_SIZE UNLIMITED;(MySQL—limits query execution size.) - Connecting to the wrong server. Double-check the IP/hostname (`-h` flag) and port (default: 3306 for MySQL, 5432 for PostgreSQL). Use `telnet [ip] [port]` (Linux/macOS) or `Test-NetConnection` (PowerShell) to verify connectivity.
Tips
- Autocomplete in Linux/macOS. MySQL/PostgreSQL shells auto-complete commands. Type `SELECT * FROM` and press Tab to fill in the rest.
- Save queries in files. Create a `.sql` file (e.g., `query.sql`) and run:
mysql -u [user] -p< query.sql(Linux/macOS). For PowerShell, use `-file`:sqlcmd -S [server] -U [user] -d [db] -i query.sql - Use pipes for data export. Redirect output to a file:
mysql -u [user] -p orders | grep 'shipped' > shipped_orders.log(Linux/macOS). On Windows, use `sqlcmd -S [server] ... | Out-File` in PowerShell. - Enable remote access safely. Firewall rules for MySQL/PostgreSQL must allow the IP range of users accessing the server. Example (Linux):
sudo ufw allow from 192.168.1.0/24 to any port 3306(Restrict to trusted networks only!) - Debug slow queries. Use EXPLAIN to analyze query performance:
EXPLAIN SELECT * FROM users WHERE age > 30;Look for "Full Table Scan" or high `key` usage.
Troubleshooting
- Connected but no tables appear.
- Check if the database exists:
SHOW DATABASES;(MySQL) orSELECT datname FROM pg_database;(PostgreSQL). - If the database is empty, verify the user has access:
SHOW GRANTS FOR [username];(MySQL). - For SQLite, ensure the file exists and is readable:
ls -la [path_to_file.db](Linux/macOS).
- Check if the database exists:
- SQL Server `sqlcmd` fails on Windows.
- Ensure SSMS is installed and the `sqlcmd` tool is available. Download it from Microsoft.
- Run PowerShell as Administrator to allow network access.
- Test connectivity:
Test-NetConnection -ComputerName [server_name] -Port 1433(1433 is the default SQL Server port.)
- Permission denied when running as non-root.
- MySQL/PostgreSQL may require creating a user with limited privileges:
CREATE USER [username] WITH PASSWORD '[password]';(MySQL) orCREATE USER [username] IDENTIFIED BY '[password]';(PostgreSQL). - Grant access to the specific database:
GRANT ALL PRIVILEGES ON [database_name] TO [username];(MySQL).
- MySQL/PostgreSQL may require creating a user with limited privileges:
- Terminal won’t accept the password.
- Linux/macOS: Store credentials securely with:
mysql --defaults-file=~/.my.cnf(Edit `~/.my.cnf` to auto-fill credentials.) - Windows: Use environment variables or a config file in `%USERPROFILE%\.sqlcmd.conf`.
- Linux/macOS: Store credentials securely with:
Frequently Asked Questions
Can I use this method for MariaDB?
Yes—MariaDB is compatible with MySQL’s command-line tools. The syntax is identical to MySQL (e.g., `mysql -u [user] -p`), and `SHOW TABLES` works the same way.
What if my database isn’t on localhost?
Specify the server IP/hostname with `-h` (MySQL/PostgreSQL) or `-S` (SQL Server). Example:
mysql -u [user] -p -h 192.168.1.100 orders
(Replace `192.168.1.100` with your server’s IP.)
How do I exit the database shell?
Use `quit` (MySQL/PostgreSQL), `exit` (SQLite), or `Ctrl+D` (Linux/macOS) or `Ctrl+Z` + Enter (Windows).
Can I run SQL commands in Windows PowerShell for SQLite?
Yes—SQLite’s `sqlite3` command works directly in PowerShell. Example:
sqlite3 C:\path\to\mydb.db
Then run SQL queries in the SQLite shell.
What’s the difference between `LIMIT` and `WHERE`?
`WHERE` filters rows (e.g., `WHERE age > 30`), while `LIMIT` restricts the number of rows returned (e.g., `LIMIT 10`). Together, they’re powerful:
SELECT * FROM users WHERE status = 'active' LIMIT 5;
(Only 5 active users appear.)
How do I backup a database via command line?
MySQL/PostgreSQL:
mysqldump -u [user] -p[password] [database_name] > backup.sql
(PostgreSQL: `pg_dump -U [user] -d [database_name] > backup.sql`). SQLite:
cp [file.db] [file.db.backup]
(Copy the file instead of dumping to SQL.)