Basic MySQL Commands to Manage Databases (With Examples)

MySQL is an open-source relational database management system that is widely used across a variety of industries for software products ranging from simple web apps to complex enterprise-level systems. Known for its reliability, performance, and ease of use, MySQL is a cornerstone in the tech stack of countless companies.

MySQL uses Structured Query Language (SQL) to manage and manipulate data. You write a command (a.k.a. a query) in SQL, run it against your database, and get the corresponding output. The very basics of SQL are not that complex, yet they give everything a developer, DBA, or analyst might need for their everyday database management tasks like retrieving the required data, editing it, migrating it between different databases, backing it up, and much more.

This tutorial will give you a detailed overview of these basics, namely, the most common MySQL commands with real examples, syntax explanations, and use cases. Mastering them will help you cover all the essential operations and pave the way to more complex ones.

What are MySQL commands?

In simple words, MySQL commands are instructions that are written in SQL and used to interact with the MySQL server to manage databases, manipulate data, control user access, and maintain data integrity.

These commands can be divided into four main categories:

  • DDL (Data Definition Language) commands are used to define and modify database structure. These include CREATE, ALTER, DROP, and TRUNCATE.
  • DML (Data Manipulation Language) commands are used to retrieve and manage data in tables. These include SELECT, INSERT, UPDATE, and DELETE.
  • DCL (Data Control Language) commands are used to control access to data. These include privilege management commands like GRANT and REVOKE.
  • TCL (Transaction Control Language) commands are used to manage transactions and ensure data consistency. These include START TRANSACTION, COMMIT, ROLLBACK, and SAVEPOINT.
MySQL commands

Commands can be executed against databases using a number of tools that can be generally divided into two types: command-line tools (e.g., MySQL Command-Line Client) and GUI tools (e.g., MySQL Workbench or dbForge Studio for MySQL). Execution always happens on the MySQL server, regardless of where the command is written or triggered.

Below, we'll show you how these commands work. For better clarity, we will illustrate them with examples executed in a user-friendly GUI for MySQL.

MySQL environment setup

But before proceeding to the actual execution of commands, you will need to get some prerequisites ready. Let's have a look.

First and foremost, you need a MySQL server instance, local or remote, along with valid credentials to access it. At the very least, these credentials must include a host name, a user name, and a password.

Next, you need a database on your server to run commands against. In our case, we'll use the sakila test database.

Finally, you'll need a specialized database management tool acting as a layer that helps you communicate with your databases. Like we mentioned previously, it can be either a command-line tool or a more convenient and intuitive GUI-based tool. In our case, we'll opt for the latter and use dbForge Studio for MySQL, a high-end IDE that boasts a clean interface that is easy to use and understand.

dbForge Studio is available for a free 30-day trial, so you can just as well try it to practice interactions with your own databases. To do that:


This is what it's going to look like.

Connecting to a MySQL server in dbForge Studio

Basic MySQL command list with examples

Once you connect to a MySQL server via dbForge Studio (or any other tool of your choice), you can proceed to write and execute commands against the databases it contains. The basic list of commands is as follows.

General syntax What it does
CREATE DATABASE database_name; Creates a new database with the specified name.
DROP DATABASE database_name; Deletes an existing database and all its contents.
USE database_name; Selects a database to run queries against.
SHOW DATABASES; Lists all databases on the server.
CREATE TABLE table_name (...); Creates a new table with specified columns and types.
DROP TABLE table_name; Deletes a table and its data from the database.
ALTER TABLE table_name ...; Modifies the structure of an existing table.
SHOW TABLES; Displays all tables in the currently selected database.
DESCRIBE table_name; Shows the structure (columns, types, etc.) of a table.
INSERT INTO table_name (...) VALUES (...); Adds a new row of data to a table.
SELECT * FROM table_name; Retrieves all data from a table.
SELECT COUNT(*) FROM table_name; Counts the total number of rows in a table.
SELECT column1, column2 FROM table_name WHERE ...; Queries specific columns with a filter.
UPDATE table_name SET ... WHERE ...; Updates existing data in a table.
DELETE FROM table_name WHERE ...; Removes rows from a table based on a condition.
CREATE USER 'user'@'host' IDENTIFIED BY 'password'; Creates a new MySQL user.
GRANT ALL PRIVILEGES ON db.* TO 'user'@'host'; Assigns privileges to a user.
REVOKE ALL PRIVILEGES ON db.* FROM 'user'@'host'; Removes a user's permissions.
SHOW GRANTS FOR 'user'@'host'; Displays granted permissions for a specific user.

Now let's conveniently group these commands and review them in detail with practical examples.

Database management commands

We will begin with commands that perform basic operations with databases, including creation, deletion, and selection.

CREATE DATABASE

CREATE DATABASE database_name; will create a new database on your server. If a database with such a name exists, your command will return an error.

Optionally, you can write a larger query that includes further details about the database you want to create; for instance, character set and collation.

CREATE DATABASE sakila_test
CHARACTER SET utf8mb4
COLLATE utf8mb4_general_ci;

Now let's run this command in dbForge Studio to see how it works out.

Running a CREATE DATABASE command in dbForge Studio for MySQL

DROP DATABASE

DROP DATABASE database_name; will delete the specified database and all of its contents from the server permanently. This operation cannot be undone, so make sure you are deleting the correct database. Also note that an attempt to drop a non-existent database will return an error; to avoid it, you can include an IF EXISTS clause as follows: DROP DATABASE IF EXISTS database_name;. It will make the operation successful even if your target database does not exist.

Let's drop our newly created database in the Studio.

Running a DROP DATABASE command in dbForge Studio for MySQL

USE

USE database_name; selects a specific database to run your commands/queries against. After you run USE, all subsequent operations will be performed on the selected database unless you specify otherwise. Also note that after selecting the database, you can create tables, insert data, and run queries without prefixing the database name.

Running a USE command in dbForge Studio for MySQL

SHOW DATABASES

Run SHOW DATABASES; as it is to retrieve a list of all databases available on your MySQL server. Let's run it against our server instance in dbForge Studio.

Running a SHOW DATABASES command in dbForge Studio for MySQL
Note
If you are using dbForge Studio, you can benefit a lot from the integrated dbForge AI Assistant, a smart AI-powered sidekick that generates, fixes, and optimizes queries, as well as consults you on everything SQL. You can use your natural language to describe the query you want to get, and the Assistant will generate it in a matter of moments. What's more, you can attach any required database, and the Assistant will be able to generate queries that will be relevant to that particular database.

Table management commands

Now that we've learned how to create, drop, and show databases, let's take one step further and proceed to actual tables.

CREATE TABLE

If you need to create a table in your database, run the CREATE TABLE command. Its general syntax is as follows:

CREATE TABLE table_name (
    column1 datatype constraints,
    column2 datatype constraints,
    ...
);

An actual query may look like this.

Running a CREATE TABLE command in dbForge Studio for MySQL
Note
You can ask dbForge AI Assistant to suggest a CREATE TABLE query based on your instructions. What's more, it can explain the output and provide you with advice on forming the precise query that you want to get.

DROP TABLE

Next, DROP TABLE table_name; will permanently delete the employees table and all of its data from your database. Drop tables with caution, because this operation cannot be undone.

Running a DROP TABLE command in dbForge Studio for MySQL

ALTER TABLE

If you need to modify the structure of an existing table, use the ALTER TABLE command. Its general syntax may vary depending on the change you would like to introduce. For instance, here's how you add a column.

ALTER TABLE table_name ADD column_name datatype;

Here's how you drop a column.

ALTER TABLE table_name DROP COLUMN column_name;

And here's how you modify a column by changing its data type.

ALTER TABLE table_name MODIFY column_name new_datatype;

Let's modify a table by adding a new column.

Running an ALTER TABLE command in dbForge Studio for MySQL

SHOW TABLES

Next, you can run SHOW TABLES; as it is to list all the tables in your databases.

Running a SHOW TABLES command in dbForge Studio for MySQL

DESCRIBE

Finally, run DESCRIBE to view the structure of a table: columns, data types, nullability, keys, and suchlike.

DESCRIBE table_name;
-- or
DESC table_name;

Let's see how this query works in dbForge Studio. Note how the integrated autocompletion helps you as you type.

Typing a DESCRIBE command in dbForge Studio for MySQL

Now let's run it.

Running a DESCRIBE command in dbForge Studio for MySQL

Data manipulation commands

These are commands that will help you retrieve and manage data.

SELECT

The SELECT command is used to retrieve data from one or more tables.

SELECT column1, column2 FROM table_name WHERE condition;

This is how it works in dbForge Studio.

Running a SELECT command in dbForge Studio for MySQL

INSERT

The INSERT command is used to add new records (rows) to a table.

INSERT INTO table_name (column1, column2, ...) VALUES (value1, value2, ...);

Let's insert a new record in the Studio. To keep it simple, we'll just add a new record to the film table.

Running an INSERT command in dbForge Studio for MySQL

UPDATE

The UPDATE command is used to modify existing records in a table.

UPDATE table_name SET column1 = value1, column2 = value2 WHERE condition;

Now let's update the title of the same film in our table.

Running an UPDATE command in dbForge Studio for MySQL
Note
Make sure you always include a WHERE clause in your query unless you intend to update all rows.

DELETE

The DELETE command is used to remove records from a table. Just like with UPDATE, if you omit the WHERE clause, the command will delete all rows in the table.

DELETE FROM table_name WHERE condition;

Let's remove the record we've just added.

Running a DELETE command in dbForge Studio for MySQL

Query filtering and sorting

Filtering and sorting commands help narrow down and organize the output in the optimal way. Let's see how to use them.

WHERE

The WHERE clause filters rows based on a condition before any grouping or aggregation. Its syntax is as follows.

SELECT * FROM table_name WHERE condition;

Let's get a list of films that were released in 2007.

Running a query with a WHERE clause in dbForge Studio for MySQL

ORDER BY

The ORDER BY clause sorts query results by one or more columns (ascending or descending). This is what it looks like.

SELECT * FROM table_name ORDER BY column1 [ASC|DESC];

See how it works in the Studio, with the results ordered by category_id, in ascending order.

Running a query with an ORDER BY clause in dbForge Studio for MySQL

LIMIT

This command limits the number of returned rows.

SELECT * FROM table_name LIMIT number;

Now, back in the Studio, let's reorder our table by film_id and retrieve 5 last rows (to do the latter, we'll apply the descending order).

Running a query with a LIMIT clause in dbForge Studio for MySQL

GROUP BY

The GROUP BY clause groups rows that have the same values in specified columns for use with aggregate functions (COUNT(), SUM(), AVG(), etc.).

SELECT column, AGG_FUNC(column2) FROM table_name GROUP BY column;

We need another simple example. Let's count the number of rentals per customer.

Running a query with a GROUP BY clause in dbForge Studio for MySQL

HAVING

The HAVING clause filters results after grouping. It is typically used with GROUP BY.

SELECT column, AGG_FUNC(column2) FROM table_name
GROUP BY column
HAVING condition;

Let's find customers who have made more than 30 rentals.

Running a query with a HAVING clause in dbForge Studio for MySQL

User- and privilege-related commands

User management ensures that only authorized users have the right level of access to your database. Let's see the commands that will help you handle users and privileges in MySQL.

CREATE USER

The CREATE USER command is used to create a new user account.

CREATE USER 'username'@'host' IDENTIFIED BY 'password';

Let's create a new user in the Studio. We will use '%' as the host to allow access from any host.

Running a CREATE USER command in dbForge Studio for MySQL

GRANT

The GRANT command is used to assign privileges to a user.

GRANT privileges ON database.table TO 'username'@'host';

Common privileges include the following:

  • SELECT, INSERT, UPDATE, DELETE
  • ALL PRIVILEGES
  • CREATE, DROP, ALTER
  • GRANT OPTION (allows the user to grant privileges to others)

Let's grant SELECT and INSERT privileges to our new user.

Running a GRANT command in dbForge Studio for MySQL

REVOKE

The REVOKE command is used to remove privileges from a user.

REVOKE privileges ON database.table FROM 'username'@'host';

For example, let's deprive our user of INSERT privileges on the address table.

Running a REVOKE command in dbForge Studio for MySQL

SHOW GRANTS

The SHOW GRANTS command is used to display the privileges granted to a user.

SHOW GRANTS FOR 'username'@'host';

This is how the SHOW GRANTS command works for our user.

Running a SHOW GRANTS command in dbForge Studio for MySQL
Note
If you're using dbForge Studio for MySQL, you can manage users in a more flexible and convenient manner. Namely, you can use the integrated Security Manager. Its intuitive interface will make your routine privilege management a breeze.

Security Manager in dbForge Studio for MySQL

JOIN operations

JOINs in MySQL allow you to retrieve data from multiple tables based on related columns. There are several different types of JOINs.

  • INNER JOIN returns rows with matching values across all specified tables.
  • LEFT OUTER JOIN includes all rows from the left table and only matching rows from the right table. Non-matching rows from the right table are filled with NULLs.
  • RIGHT OUTER JOIN returns all rows from the right table and only the rows from the left table that meet the JOIN condition. Non-matching rows from the left table are filled with NULLs.
  • CROSS JOIN combines every row from one table with each row from another, resulting in a table with all possible row combinations.
  • SELF JOIN allows comparisons within the same table or the extraction of hierarchical data. Table aliases are used here to avoid repeating the same table name.

It is also worth noting that MySQL does not directly support FULL OUTER JOIN, which would return both matching and non-matching rows from the joined tables. However, you can achieve this effect by combining LEFT and RIGHT OUTER JOINs.

We have a comprehensive guide called Types of JOINs in MySQL With Examples. Check it out to learn all about the usage and specifics of MySQL JOINs.

Backup and export commands

Let's proceed to the means of backing up your databases, with a brief overview of each.

mysqldump

First of all, you can use mysqldump, a stock command-line MySQL tool that creates a file containing SQL statements to recreate your databases, tables, and data. This is its general syntax.

mysqldump -u [user] -p [database_name] > [file_name]

For instance, here is an example that shows the root user exporting the employees database to an SQL file.

mysqldump -u root -p employees > employees_backup.sql

INTO OUTFILE

Alternatively, you can use the SELECT ... INTO OUTFILE command to export data into a specified file. This is what it looks like, with a few extra specified parameters.

Running a SELECT ... INTO OUTFILE command in dbForge Studio for MySQL
Note
If you are using dbForge Studio for MySQL, you can set up wizard-aided import and export of MySQL data. It is much more flexible and intuitive than executing a command, with handy templates, CLI-powered automation, and up to 14 most popular file formats at your service.

Exporting data in dbForge Studio for MySQL

MySQL syntax rules and best practices

It comes as no surprise that following the syntax specifics and best practices will help you avoid errors, improve readability, and maintain consistency in your SQL code. Here are probably the most important of these, covering case sensitivity, punctuation, and formatting.

Case sensitivity

When it comes to case sensitivity, you need to remember the following rules:

  • SQL keywords (e.g., SELECT, FROM, WHERE) are not case-sensitive.
  • Database and table names are case-sensitive on Unix/Linux but not on Windows (depends on the operating system and MySQL settings).
  • Column names are generally not case-sensitive, but it's good to be consistent.

It is generally recommended to write SQL keywords in uppercase for clarity. You can also use lowercase for identifiers (e.g., table and column names).

Naming

Proper naming is vital for clarity and easier collaboration on your databases. To keep things right, adopt consistent naming conventions, be descriptive but concise in your naming, and avoid using special characters or spaces.

Semicolons

A semicolon ; typically ends an SQL statement. It is required when you need to run multiple statements in one execution or in scripts. The common best practice is to always end SQL statements with a semicolon to avoid unexpected behavior, especially in scripts.

Indentation

Use consistent indentation and line breaks to improve readability. Additionally, break long statements into multiple lines, especially for SELECT queries with multiple columns or JOIN clauses.

Quoting

Single quotes ' are used for string literals. Backticks ` are used for identifiers (e.g., table or column names), especially if they contain special characters, are reserved words, or include spaces.

The common best practices are to use single quotes for strings and avoid using backticks unless necessary.

Reserved words

Reserved words (e.g., ORDER, SELECT, GROUP) cannot be used as identifiers unless enclosed in backticks. Thus, it is better to avoid using reserved words for table or column names, but if you really must use them, backticks will do the trick.

Common syntax mistakes

Finally, let's briefly list the most common syntax mistakes to take note of.

  • A missing semicolon may prevent the command from running properly; thus, make sure it's there.
  • The misuse of quotes, most notably, mixing ' and ", will lead to errors. Thus, use ' for strings consistently.
  • Misspelled keywords will cause errors as well. Double-check them or use code completion or AI-powered code generation to prevent such mistakes.
  • Incorrect data types will cause errors if you try storing text in numeric columns. Make sure you are not mixing different types.
  • The absence of a WHERE clause in DELETE or UPDATE queries can delete all records in your table. Make sure you always use a condition.

All in all, following these rules and best practices will help you write clean, error-free, and easily maintainable SQL code.

Tips for writing and executing MySQL commands faster

Now let's take a look at a concise yet useful checklist of tips you should take note of in order to handle your MySQL commands faster.

  • Use AI to generate and optimize your queries; however, make sure you double-check those queries before running, just to know you're getting exactly what you need.
  • Employ tools with SQL autocompletion to reduce accidental syntax errors and speed up your casual typing.
  • Write and save reusable scripts for recurring tasks.
  • Use code snippets for frequent query patterns.
  • Use short and meaningful table aliases.
  • Wrap commands in transactions for safety, especially when making multiple related changes.
  • Adhere to clean, consistent formatting.
  • Write comments to document your queries; this might save you lots of time later on.
  • Use stored procedures for repetitive logic.
  • Master keyboard shortcuts in the tool you are using.

Why use dbForge Studio for MySQL to run commands faster

All the examples we mentioned above were illustrated with dbForge Studio for MySQL, our all-encompassing IDE that helps you cover virtually every database-related task in MySQL and MariaDB. Let's have a brief recap of all the features of the Studio that are related to SQL development (in other words, will help you write MySQL commands effortlessly).

  • Clean and intuitive SQL Editor to write and run your code from
  • Context-aware code completion and relevant database object suggestions
  • Instant syntax check
  • Easy formatting with flexible settings and custom profiles
  • Quick object information
  • A library of predefined and custom code snippets
  • Smart debugging of MySQL stored procedures, triggers, functions, and scripts
  • Visual query building on diagrams, just in case you don't like manual coding
  • Integration with multiple version control systems, invaluable for safe and transparent teamwork
  • AI-powered query generation, optimization, and troubleshooting (via dbForge AI Assistant)

All of these features, taken together, make a compelling toolset for your effective daily management of MySQL commands. And that's only one facet of the Studio, which has much more to offer.

Conclusion

Now that you know everything about writing and running the most important MySQL commands, we gladly invite you to get some firsthand experience with them using dbForge Studio for MySQL. Download it for a free 30-day trial, connect to your MySQL database server, and explore the immense range of features and capabilities delivered by this IDE.

We'd be happy if our Studio helped you write better SQL with less effort. Give it a go, and you'll see the results right away.


FAQ

What are commands in MySQL?

In MySQL, commands are instructions that perform a wide range of operations with databases, including but not limited to data retrieval and modification, user access management, and transaction control. Commands are written in SQL and given to a MySQL database server by the user.

What are the four types of SQL commands?

The four types of SQL commands are as follows:

  • Data Definition Language (DDL) commands define or modify database structures.
  • Data Manipulation Language (DML) commands help manage table data.
  • Data Control Language (DCL) commands deal with user access and permissions.
  • Transaction Control Language (TCL) commands manage transactions (groups of SQL commands executed together).
Can I run multiple MySQL commands at once?

Yes, you can place multiple MySQL commands in a single query and execute them together.

How do I export data from MySQL using a command?

You can use the SELECT ... INTO OUTFILE command to export data into a specified file. In this command, you can indicate additional parameters as follows:

SELECT * FROM employees
INTO OUTFILE '/var/lib/mysql-files/employees.csv'
FIELDS TERMINATED BY ',' 
ENCLOSED BY '"'
LINES TERMINATED BY '\n';

Alternatively, and more conveniently, you can import and export MySQL data with a GUI-powered tool like dbForge Studio for MySQL.

How do I manage users and permissions in MySQL?

To grant and revoke privileges to a specific user, you can write and run a corresponding Data Control Language (DCL) command.

To make the entire process more intuitive, you can manage users via dbForge Studio's integrated Security Manager.

How does dbForge Studio help with writing MySQL queries faster?

dbForge Studio has quite a few coding assistance tools that will help you make your routine SQL coding 2-4 times faster. These include context-aware code completion, relevant object suggestions, code snippets, and flexible code formatting.

And if you want to completely reinvent your daily SQL development, you can try the Studio's integrated dbForge AI Assistant, your smart copilot that's designed to generate and optimize SQL code, identify and explain possible issues with your queries, and consult you on everything related to SQL.

Can I visually design MySQL queries in dbForge Studio?

Yes, you can use the Studio's integrated Query Builder to design queries on diagrams visually, with no need for manual coding.

Does dbForge Studio support exporting results from a MySQL command?

Yes, you can conveniently export query results (any selection of data, actually) to files of multiple formats directly from the results grid.

How do I generate SQL queries using AI in dbForge Studio?

The Studio boasts an integrated dbForge AI Assistant, which can generate valid SQL code on request. That is, you simply launch the Assistant, write a request in your natural language, and, in response, get a query.

Moreover, you can attach any required database to the Assistant in order to provide it with the required context. As a result, the AI Assistant suggests queries that are tailored specifically to the attached database.

Can AI in dbForge Studio help me fix syntax errors?

Sure. Just give your query to the AI Assistant, and it will pinpoint whatever is wrong with it, with detailed explanations.

Can I convert natural language into SQL with dbForge Studio's AI features?

Easily. You only need to ask the Assistant and get an instant reply with the query you need. The more precise the question, the more precise the answer.

dbForge Studio for MySQL

Your best IDE for all kinds of database management tasks