To use the MySQL command line, open your terminal or command prompt and enter mysql -u username -p, then provide your password when prompted. This allows you to interact directly with the MySQL database engine to create databases, manage tables, and execute SQL queries without needing a graphical user interface. This method is essential for server administration, automation via scripts, and performing high-performance database operations.
What You'll Need
- A computer with MySQL Server installed and running.
- The MySQL Client installed (usually bundled with the server).
- A valid MySQL user account (such as the 'root' user) and its corresponding password.
- Access to a terminal (Command Prompt or PowerShell on Windows, Terminal on macOS, or Bash/Zsh on Linux).
- MySQL added to your system's PATH environment variable so the
mysqlcommand is recognized from any directory.
Step-by-Step
- Open your Terminal or Command Prompt: Launch the command-line interface of your operating system. On Windows, search for "cmd" or "PowerShell". On macOS or Linux, open the "Terminal" application.
- Initiate the Connection Command: Type the following command and press Enter:
mysql -u root -p. In this command,-uspecifies the user you want to log in as (in this case, 'root'), and-ptells MySQL to prompt you for a password. If you are connecting to a remote server, usemysql -h hostname -u username -p, replacing "hostname" with the server's IP address or domain. - Enter Your Password: After pressing Enter, the terminal will display "Enter password:". Type your password carefully. Note that for security reasons, the cursor will not move and no characters (like asterisks) will appear as you type. Press Enter once the password is typed.
- Verify the Connection: If successful, the prompt will change to
mysql>. This indicates you are now inside the MySQL monitor and the system is ready to accept SQL commands. - Explore Existing Databases: To see what databases are available on the server, type
SHOW DATABASES;and press Enter. Remember that every command in the MySQL command line must end with a semicolon (;) to be executed. - Select a Database: To start working with a specific database, use the
USEcommand. For example,USE my_database_name;. The system will respond with "Database changed", meaning any subsequent table queries will apply to this specific database. - Create a New Database: If you need a fresh environment, type
CREATE DATABASE project_db;. You can then verify its creation by runningSHOW DATABASES;again. - Create a Table: Once a database is selected, you can define a table. For example:
CREATE TABLE users (id INT AUTO_INCREMENT PRIMARY KEY, username VARCHAR(50), email VARCHAR(100));. This creates a table named 'users' with three columns: an auto-incrementing ID, a username, and an email. - Insert Data: Add a record to your table using the
INSERT INTOcommand:INSERT INTO users (username, email) VALUES ('jdoe', 'jane@example.com');. - Retrieve Data: To view the data you just inserted, use the
SELECTstatement:SELECT * FROM users;. This will display a formatted table of all records in the 'users' table. - Exit the Command Line: When you are finished, type
EXIT;orQUIT;and press Enter to return to your standard system terminal.
Common Mistakes
The most frequent error for beginners is forgetting the semicolon (;) at the end of a statement. If you press Enter without a semicolon, MySQL will simply move to a new line with a -> prompt, indicating that it is still waiting for you to complete the command. To fix this, simply type the semicolon and press Enter.
Another common mistake is typing the password directly into the initial command (e.g., mysql -u root -pMyPassword). While this works, it is a significant security risk because the password remains in your terminal's command history in plain text, where other users or malicious software can find it. Always use the -p flag without a password to trigger the secure prompt.
Users often confuse the system terminal (bash/cmd) with the MySQL monitor. If you try to run SHOW DATABASES; directly in the Windows Command Prompt without first logging into MySQL, you will receive an error stating that the command is not recognized. Ensure the prompt says mysql> before entering SQL queries.
Case sensitivity is another pitfall. While SQL keywords like SELECT and INSERT are case-insensitive, table names and database names may be case-sensitive depending on the operating system the server is running on (Linux is typically case-sensitive, while Windows is not). To avoid errors, always maintain consistent casing for your identifiers.
Tips
To make the output of large tables easier to read in the terminal, you can use the
or shortcuts, but a more powerful option is the
vertical formatting. If a table has too many columns to fit on one screen, end your query with
instead of a semicolon (e.g., SELECT * FROM users\G). This displays each column on a new line, making the data much more legible.
Use the DESCRIBE command to quickly understand the structure of a table. For example, DESCRIBE users; will show you the column names, data types, whether a column can be NULL, and which column is the primary key. This is faster than trying to remember the CREATE TABLE syntax you used previously.
If you have a complex SQL script saved in a .sql file, you don't have to type it manually. You can import the file from the system terminal using the command mysql -u username -p database_name < file.sql. This is the standard way to perform database migrations or restore backups.
Utilize the status command (
or STATUS;) to check the current connection details, including the server version, uptime, and the current character set. This is helpful when debugging encoding issues with special characters.
Troubleshooting
If you receive the error 'mysql' is not recognized as an internal or external command, it means the MySQL binary folder is not in your system's PATH environment variable. To fix this on Windows, find the bin folder where MySQL is installed (usually C:\Program Files\MySQL\MySQL Server X.X\bin), copy the path, and add it to your System Environment Variables under "Path". Restart your terminal after making this change.
If you encounter Access denied for user 'root'@'localhost' (using password: YES), it means the password you entered is incorrect or the user does not have permission to connect from the local host. Double-check your password. If you have forgotten the root password, you will need to restart the MySQL server with the --skip-grant-tables option to reset it, which requires administrative access to the server machine.
When you see Can't connect to MySQL server on 'localhost' (Error: 10061), the MySQL service is likely not running. On Windows, open "Services.msc", find the "MySQL" service, and click "Start". On Linux, use the command sudo systemctl start mysql or sudo service mysql start.
If the terminal hangs or becomes unresponsive during a long-running query, you can try pressing Ctrl + C to cancel the current operation and return to the mysql> prompt. If the entire terminal is frozen, you may need to kill the process from your system's task manager or activity monitor.
Frequently Asked Questions
How do I clear the screen in the MySQL command line?
On Linux and macOS, you can use Ctrl + L to clear the screen. On Windows, there is no built-in SQL command to clear the terminal; you must exit the MySQL monitor, run cls in the command prompt, and log back in.
Can I run MySQL commands without a password?
Only if the user account was specifically created without a password or if the server is configured to allow anonymous access, which is highly discouraged for security reasons. Most installations require a password for the root user.
What is the difference between MySQL and MariaDB in the command line?
For basic operations, they are nearly identical. MariaDB is a fork of MySQL, and the mysql command-line client works with both. Most standard SQL queries will behave exactly the same way in both environments.
How do I delete a database entirely?
Use the command DROP DATABASE database_name;. Be extremely careful with this command, as it permanently deletes the database and all tables and data contained within it; this action cannot be undone.
How do I change my MySQL password via the command line?
Once logged in, use the command ALTER USER 'username'@'localhost' IDENTIFIED BY 'new_password'; followed by FLUSH PRIVILEGES; to apply the changes immediately.