DROP TABLE оператор MySQL
MySQL оператор DROP TABLE позволяет стереть или удалить таблицу из базы данных MySQL.
Синтаксис
Простая форма синтаксиса для оператора DROP TABLE в MySQL:
Полный синтаксис для оператора MySQL DROP TABLE:
Параметры или аргументы
TEMPORARY — необязательный. Он указывает, что только временные таблицы должны быть удалены с помощью оператора DROP TABLE.
table_name — имя таблицы для удаления из базы данных.
table_name1 , table_name2 — таблицы для удаления из базы данных при удалении более одной таблицы в операторе DROP TABLE.
IF EXISTS — необязательный. Если указан, то оператор DROP TABLE не будет вызывать ошибку, если одна из таблиц не существует.
RESTRICT — необязательный. Он не влияет на оператор DROP TABLE, но включен в синтаксис, чтобы упростить перенос таблиц в разные базы данных.
CASCADE — необязательный. Он не влияет на оператор DROP TABLE, но включен в синтаксис, чтобы упростить перенос таблиц в разные базы данных.
Примечание
- Если вы используете MySQL оператор DROP TABLE для удаления одной или нескольких таблиц, которые не существуют, база данных будет вызывать ошибку (если вы не укажете параметр IF EXISTS в операторе DROP TABLE).
Пример
Рассмотрим пример, показывающий, как удалить таблицу с помощью оператора MySQL DROP TABLE.
Удаление одной таблицы
Во-первых, давайте рассмотрим простой пример DROP TABLE, который показывает, как использовать оператор DROP TABLE для удаления одной таблицы в MySQL.
Например:
Как удалить таблицу mysql
Для создания таблиц используется команда CREATE TABLE . Эта команды применяет ряд операторов, которые определяют столбцы таблицы и их атрибуты. Общий формальный синтаксис команды CREATE TABLE:
После команды CREATE TABLE идет название таблицы. Имя таблицы выполняет роль ее идентификатора в базе данных, поэтому оно должно быть уникальным. Затем в скобках перечисляются названия столбцов, их типы данных и атрибуты. В самом конце можно определить атрибуты для всей таблицы. Атрибуты столбцов, а также атрибуты таблицы указывать необязательно.
Создадим простейшую таблицу. Для этого выполним следующий скрипт:
Таблица не может создаваться сама по себе. Она всегда создается в определенной базе данных. Вначале здесь создается база данных productsdb. И затем, чтобы указать, что все дальнейшие операции, в том числе создание таблицы, будут производиться с этой базой данных, применяется команда USE .
Далее собственно идет создание таблицы, которая называется Customers. Она определяет четыре столбца: Id, Age, FirstName, LastName. Первые два столбца представляют идентификатор клиента и его возраст и имеют тип INT , то есть будут хранить числовые значения. Следующие столбцы представляют имя и фамилию клиента и имеют тип VARCHAR(20) , то есть представляют строку длиной не более 20 символов. В данном случае для каждого столбца определены имя и тип данных, при этом атрибуты столбцов и таблицы в целом отсутствуют.
И в результате выполнения этой команды будет создана база данных productsdb, в которой будет создана таблица Customers.
Переименование таблиц
Если после создания таблицы мы захотим ее переименовать, то для этого нужно использовать команду RENAME TABLE , которая имеет следующий синтаксис:
Например, переименуем таблицу Customers в Clients:
Полное удаление данных
Для полного удаления данных, очистки таблицы применяется команда TRUNCATE TABLE . Например, очистим таблицу Clients:
Удаление таблиц
Для удаления таблицы из БД применяется команда DROP TABLE , после которой указывается название удаляемой таблицы. Например, удалим таблицу Clients:
How to Drop a Table in MySQL
The DROP TABLE statement allows a table to be removed from a MySQL database. This statement deletes the entire structure as well as the content of the table.
The tutorial explores DROP statement commands and shows options to drop tables from MySQL databases.

- Access to a terminal window/command line
- A system running MySQL
- A working or test database
- A MySQL user with the necessary privileges (DROP privileges required)
DROP TABLE MySQL Command Syntax
To remove a table in MySQL, use the DROP TABLE statement. The basic syntax of the command is as follows:
Let’s break down the syntax:
- The DROP TABLE statement deletes a table and its rows permanently.
- The [TEMPORARY] option ensures you remove temporary tables only.
- The [IF EXISTS] option drops a table only if it exists.
- The [RESTRICT] option will be available in future iterations of MySQL. It ensures that a parent row is not deleted if a child row is referencing a value in said parent row.
- The [CASCADE] option ensures that when you delete a row, all rows in related tables that reference that row are deleted as well. This option will be available in future iterations of MySQL.
Note: When deleting a MySQL table, all user privileges associated with that table remain. If you create a new table with the same name as the deleted one, the existing user privileges will be assigned. Consider whether that impacts your security.
Use the DROP Statement to Remove a Table
To permanently remove a table, enter the following statement within the MySQL shell:
Replace table1 with the name of the table you want to delete. The output confirms that the table has been removed.
Use DROP to Remove Only Existing Tables
MySQL generates an error if you try to drop a table that does not exist. This can be an issue when including the DROP statement in a predefined script.
To check MySQL if a table exists first:
The IF EXISTS option generates a warning if table1 does not exist.
Using this option prevents a script from getting stuck on an error. Display the warning by entering:
How to DROP Multiple Tables
To drop multiple tables with a single DROP statement:
The IF EXISTS option shows one warning as table1 does not exist.
Note: Consider identifying duplicate values in MySQL databases and then deleting them to improve data efficiency.
How to DROP a Temporary Table
Temporary tables are used to generate and store a data set shortly before using it.
For example, you might decide to store the results of a SELECT statement with multiple JOIN statements in a temporary table. Next, query the temporary table with ease.
To remove temporary tables without risking losing regular tables, use the TEMPORARY option:
How to DROP Tables Based on Character Strings
MySQL does not have a built-in command to drop tables that match a string of characters. Instead, use a script to help perform this task.
1. Define the database and string of characters you want to filter:
Replace tableselection with the name of your database. Replace table% with the string of characters you want to select and delete. Make sure to leave the % wildcard at the end.
2. Create a MySQL statement that selects all of the tables that match the string of characters:
This code selects all tables with the table% characters specified from the information_schema table. It then concatenates them and executes a DROP statement against the group.
3. Create a selection from the results of this code:
4. Display the contents of the command:
The code in the section below is presented in its entirety for ease of use:
Note: If you are interested in how to create index in new table, read our guide How to Create or Add an Index in MySQL With Examples.
You have learned how to use Drop Table to remove tables from a MySQL database. The options presented in this tutorial provide you with full control.
Additionally, you are now able to create code that helps find and delete tables based on character strings. Learn about the most important MySQL commands and how to use them in our MySQL commands cheat sheet article with a downloadable PDF.
Как удалить таблицу mysql
MySQL 8.0 Reference Manual Including MySQL NDB Cluster 8.0
13.1.32 DROP TABLE Statement
DROP TABLE removes one or more tables. You must have the DROP privilege for each table.
Be careful with this statement! For each table, it removes the table definition and all table data. If the table is partitioned, the statement removes the table definition, all its partitions, all data stored in those partitions, and all partition definitions associated with the dropped table.
Dropping a table also drops any triggers for the table.
DROP TABLE causes an implicit commit, except when used with the TEMPORARY keyword. See Section 13.3.3, “Statements That Cause an Implicit Commit”.
When a table is dropped, privileges granted specifically for the table are not automatically dropped. They must be dropped manually. See Section 13.7.1.6, “GRANT Statement”.
If any tables named in the argument list do not exist, DROP TABLE behavior depends on whether the IF EXISTS clause is given:
Without IF EXISTS , the statement fails with an error indicating which nonexisting tables it was unable to drop, and no changes are made.
With IF EXISTS , no error occurs for nonexisting tables. The statement drops all named tables that do exist, and generates a NOTE diagnostic for each nonexistent table. These notes can be displayed with SHOW WARNINGS . See Section 13.7.7.42, “SHOW WARNINGS Statement”.
IF EXISTS can also be useful for dropping tables in unusual circumstances under which there is an entry in the data dictionary but no table managed by the storage engine. (For example, if an abnormal server exit occurs after removal of the table from the storage engine but before removal of the data dictionary entry.)
The TEMPORARY keyword has the following effects:
The statement drops only TEMPORARY tables.
The statement does not cause an implicit commit.
No access rights are checked. A TEMPORARY table is visible only with the session that created it, so no check is necessary.
Including the TEMPORARY keyword is a good way to prevent accidentally dropping non- TEMPORARY tables.
The RESTRICT and CASCADE keywords do nothing. They are permitted to make porting easier from other database systems.