SQL in Command Prompt: How to Connect and Run Queries
In this article
To work with SQL in the command prompt, you must first install a database engine (like MySQL, PostgreSQL, or SQL Server) and then use the corresponding Command Line Interface (CLI) tool to connect to the server using a command such as mysql -u username -p. This process allows you to manage databases, create tables, and execute queries without needing a graphical user interface (GUI), which is essential for automation, server management, and performance tuning.
What You'll Need
- A computer running Windows, macOS, or Linux.
- A database management system (DBMS) installed on your local machine or a remote server (e.g., MySQL Community Server, PostgreSQL, or Microsoft SQL Server).
- Administrative access to the computer to modify environment variables.
- The credentials for the database, including the username, password, and the host address (usually
localhostfor local installations). - The specific CLI client tool that comes with your DBMS (e.g.,
mysql.exefor MySQL,psqlfor PostgreSQL, orsqlcmdfor SQL Server).
Step-by-Step
- Verify Installation: Before opening the prompt, ensure your database server is actually running. For Windows users, you can check this in the Services app (search for "Services" in the Start menu) and look for the service named "MySQL" or "PostgreSQL." Ensure the status is "Running." If it is stopped, right-click the service and select Start.
- Configure Environment Variables: The command prompt will not recognize SQL commands unless the folder containing the CLI executable is in your system's PATH.
- Locate the
binfolder of your installation (e.g.,C:\Program Files\MySQL\MySQL Server 8.0\bin). - Search for "Edit the system environment variables" in the Windows search bar.
- Click "Environment Variables" in the System Properties window.
- Under "System variables," find the variable named
Path, select it, and click Edit. - Click "New" and paste the full path to the
binfolder. - Click OK on all windows to save the changes.
- Locate the
- Open the Command Prompt: Press
Win + R, typecmd, and press Enter. If you are on macOS or Linux, open the Terminal application. - Initiate the Connection: Type the connection command based on your software. For MySQL, type
mysql -u root -p. Here,-u rootspecifies the user "root," and-ptells the system to prompt you for a password. Press Enter. - Enter Your Password: The prompt will ask for your password. Type it in carefully. Note that for security reasons, the cursor will not move and no characters (like asterisks) will appear as you type. Press Enter once finished.
- Select a Database: Once you see the SQL welcome message and a prompt like
mysql>, you are connected. To start working with a specific database, typeUSE database_name;(replacingdatabase_namewith your actual database) and press Enter. - Execute SQL Queries: You can now run standard SQL commands. For example, to see all tables in the current database, type
SHOW TABLES;. To retrieve data, useSELECT * FROM table_name;. Remember that every command in the CLI must end with a semicolon (;) to be executed. - Exit the Environment: When you are finished, type
exitorquitand press Enter to return to the standard command prompt.
Common Mistakes
One of the most frequent errors is forgetting the semicolon at the end of a statement. In a GUI, the software often handles the execution trigger, but in the command prompt, the CLI will simply move to a new line and wait for more input if the semicolon is missing. You may see a -> prompt, which indicates the system thinks you are still writing a multi-line query.
Another common mistake is attempting to run the mysql or psql command before adding the installation path to the system environment variables. This results in the error: "'mysql' is not recognized as an internal or external command." Users often try to restart the computer, but the issue is specifically the missing PATH entry, not a system crash.
Case sensitivity is also a common pitfall. While SQL keywords (like SELECT or INSERT) are case-insensitive, table names and column names can be case-sensitive depending on the operating system and the database configuration (especially in MySQL on Linux). If a query fails with a "Table not found" error, double-check the capitalization.
Finally, users often confuse the command prompt's shell (CMD/Bash) with the SQL shell. You cannot run a command like SELECT * FROM users; directly in the Windows Command Prompt. You must first connect to the database server to enter the SQL-specific environment before these commands will function.
Tips
To avoid typing long passwords in plain text (which can be saved in your command history), always use the -p flag without specifying the password immediately after it. This forces the prompt to ask for the password securely.
If you have a complex SQL script saved in a .sql file, you don't have to type it line by line. You can import the file directly from the command prompt using the source command: source C:\path\to\your\file.sql;. This is the most efficient way to build large schemas or migrate data.
Use the DESCRIBE table_name; command frequently. When working in a text-only environment, it is easy to forget the exact spelling of a column or the data type it requires. Describing the table provides a quick reference of the structure without having to query the actual data.
For those using PostgreSQL, remember that the command is psql. PostgreSQL also uses "backslash commands" for administrative tasks. For example, \l lists all databases and \dt lists all tables in the current database. These are much faster than writing full SQL queries for metadata.
Troubleshooting
If you receive an "Access Denied" error, first verify that the username and password are correct. If you are using the root account and it still fails, check if the user is allowed to connect from your current host. Some databases are configured to only allow root access from localhost. If you are connecting to a remote server, you may need to grant permissions to your specific IP address.
If the command prompt says the server is not running or cannot be reached (Connection Refused), check your firewall settings. The database server listens on a specific port (MySQL uses 3306, PostgreSQL uses 5432). Ensure that your firewall is not blocking traffic on these ports. Additionally, check the my.cnf or postgresql.conf file to ensure the server is configured to listen on the correct network interface.
If you find yourself stuck in a query because you forgot the semicolon and have typed several lines of incorrect code, you can usually cancel the current input by pressing Ctrl + C. This will kill the current statement and return you to the fresh SQL prompt without disconnecting you from the server.
In cases where the environment variable was added but the command is still not recognized, close all open command prompt windows and open a new one. The command prompt only loads environment variables upon startup; it will not detect changes made to the PATH while a session is already active.
Frequently Asked Questions
Can I run SQL in CMD without installing a server?
No, the command prompt is just an interface. You must have a database engine (the server) installed locally or hosted on a remote machine to process the SQL queries.
What is the difference between MySQL and the MySQL Command Line Client?
MySQL is the database server that stores the data and handles the logic. The Command Line Client is the tool you use to send instructions to that server.
Why is my password not showing when I type it?
This is a security feature called "silent input." It prevents people looking over your shoulder from seeing how many characters are in your password.
Do I have to use the root user for everything?
No, and for security reasons, you shouldn't. It is best practice to create a specific user with limited privileges for your daily tasks and only use the root account for administrative changes.
How do I clear the screen in the SQL prompt?
Most SQL CLIs do not have a built-in "clear" command like the standard shell. However, in some environments, system cls (Windows) or system clear (Linux/Mac) will work, or you can simply exit and restart the session.
Can I use this to manage SQLite databases?
Yes, but SQLite is different because it is serverless. Instead of connecting to a service, you simply run sqlite3 database_name.db to open the file directly in the command prompt.