MySQL is the world's most popular open-source relational database management system that uses SQL to manage data.
It's known for its scalability, reliability, and ease of use.
mysql is the official CLI client to command the MySQL database. It supports interactive and noninteractive use.
Below list the 10 most commonly used mysql commands with examples.
1. Connect to a database - mysql -u xxx -p -h xxx -P xxx db
Connects to the local MySQL server via socket /tmp/mysql.sock as the specified user and prompts for a password.
Connects to the MySQL server on the specified host at port 3306 and prompts for a password.
Connects to the MySQL server on the specified host and port and prompts for a password.
Connects to the specified database on the specified host and port as the specified user and prompts for a password.
2. Run a single command - mysql -e
Use -e to execute a single statement.
Alternatively, you can pipe the statements from a file.
3. List all databases - SHOW DATABASES
4. Switch to another database - USE xxx
5. List all tables under a database - SHOW TABLES
6. Describe table schema - DESCRIBE xxx
7. List user and grants - SHOW GRANTS;
SHOW GRANTS [FOR user_or_role [USING role [, role] ...]]
8. Show connections - SHOW PROCESSLIST
SHOW [FULL] PROCESSLIST
Without the FULL keyword, SHOW PROCESSLIST displays only the first 100 characters of each statement in the Info field.
If you want to apply filtering, then query the underlying INFORMATION_SCHEMA.PROCESSLIST table.
9. Kill connection - KILL
KILL [CONNECTION | QUERY] processlist_id
KILL CONNECTION is the same as KILL with no modifier: It terminates the connection associated with the given processlist_id, after terminating any statement the connection is executing. This can be useful if you want to terminate a long-running or problematic connection that is causing issues for other users or processes.
KILL QUERY terminates the statement the connection is currently executing, but leaves the connection itself intact. This can be useful if you have a specific query that is causing issues or is taking too long to execute, and you want to terminate only that query without affecting other queries or processes running on the same connection.
10. Quit - \q, quit, exit, Ctrl+D/Ctrl+Z
Alternatively, you can use the shortcut key Ctrl+D (or Ctrl+Z on Windows).
Other Tips
Displaying query results vertically - \G
Some query results are much more readable when displayed vertically using \G.
At Bytebase, we believe in the power of collaboration and open communication, and we have a number of communities that you can join to connect with other like-minded.