Как очистить таблицу sql

от admin

Как очистить таблицу в MySQL

В MySQL, как и в других СУБД можно очищать таблицы. Очистка таблицы позволяет удалять данные при этом не затрагивая саму структуру таблицы. В MySQL существует несколько способов очистки таблицы. В частности, можно выделить очистку таблицы при помощи команд DELETE и TRUNCATE .

Обе команды выполняют одну и ту же задачу, но имеют несколько отличий о которых будет рассказано далее в статье. Также будет упомянуто об удалении данных из таблицы при наличии внешних ключей ( foreign key ). В данной статье будет рассмотрено как очистить таблицу в MySQL различными способами в операционной системе Ubuntu 20.04.

Как очистить таблицу в MySQL

Для очистки таблицы в MySQL существует несколько способов. Далее будут рассмотрены все возможные способы.

1. Удаление данных таблицы с помощью DELETE

Для удаления данных из таблицы можно воспользоваться инструкцией DELETE которая может удалять строки таблицы по заданному условию. Предположим, есть таблица MyGuests в которой есть пользователь John:

При помощи оператора DELETE и заданного условия — в данном случае удаление будет происходит по столбцу firstname который принимает значение имени пользователя будет удалена запись с номером (id) 1 и именем John:

DELETE FROM MyGuests WHERE firstname = ‘John’;

0IAAAAASUVORK5CYII=

Также оператор DELETE может удалять все строки таблицы сразу. В качестве примера есть таблица с двумя записями:

wPbRaK+HpwjqAAAAABJRU5ErkJggg==

Удалим все строки за один раз не задавая никаких условий. Для этого необходимо выполнить следующий SQL запрос:

DELETE FROM MyGuests;

D0jAi4fJLLPKAAAAAElFTkSuQmCC

На этом очистка таблицы MySQL завершена.

2. Удаление данных таблицы с помощью TRUNCATE

Также для удаления всех строк в таблице существует специальная команда TRUNCATE. Она схожа с DELETE, однако он не позволяет использовать WHERE. Также стоит выделить следующие особенности при очистки таблицы MySQL с помощью оператора TRUNCATE:

  • 1) TRUNCATE не позволяет удалять отдельные строки;
  • 2) DELETE блокирует каждую строку, а TRUNCATE всю таблицу;
  • 3) TRUNCATE нельзя использовать с таблицами содержащими внешние ключи других таблиц;
  • 4) После использования оператора TRUNCATE в консоль не выводится информация о количестве удаленных строк из таблицы.

В качестве примера возьмем таблицу с двумя записями из предыдущего примера:

wPbRaK+HpwjqAAAAABJRU5ErkJggg==

Для очистки этой таблицы MySQL от всех записей необходимо выполнить следующий SQL запрос:

AAAAAElFTkSuQmCC

Как уже было упомянуто ранее команда TRUNCTE не выводит количество удалённых строк в таблице поэтому в консоль был выведен текст 0 rows affected.

Как очистить таблицу с Foreign Key Constraint

Если в таблице присутствуют внешние ключи (Foreign Key) то просто так очистить таблицу не получится. Предположим, есть 2 таблицы — Equipment и EquipmentCategory:

uAAAAABJRU5ErkJggg==

В таблице Equipment присутствует столбец с именем category_id, который связан внешним ключом со столбцом id в другой таблице — EquipmentCategory. Например:

  • id
  • category_id
  • name
  • id
  • name

Если попытаться очистить все строки таблицы EquipmentCategory при помощи оператора TRUNCATE то будет выведена следующая ошибка:

ERROR 1701 (42000): Cannot truncate a table referenced in a foreign key constraint (`Inventory`.`Equipment`, CONSTRAINT `Equipment_ibfk_1`)

H4MLkDZh0EBYAAAAAElFTkSuQmCC

Данная ошибка говорит о том, что таблица ссылается на другую таблицу и имеет ограничение на удаление в виде внешнего ключа. Чтобы избежать данной ошибки можно воспользоваться отключением проверки внешних ключей и добавлением параметра ON DELETE CASCADE при создании таблицы.

1. Отключение проверки внешних ключей

Чтобы очистить таблицу при наличии в ней внешних ключей можно отключить проверку внешних ключей. Для этого нужно выполнить следующую команду:

cDloNFGT405U9o5GdyKv3wcICGE9BUwIwEz9hXWJApv5jiQbBW8OD89ghZ5dKHAQxqNL1ASiyXUDDP2HV3yU+WQrB5gTNuSaQmCzcLJsVMgq8T6SqcJKcmJvGuK7byVmWpnhifH36Gbao9GAIKASBrpwASvOGqVaXrMaJBfkWm0qmJYWvuIsgUJDH5n6WeLs+MHx7cDpeql3Im0lSrzTXJU575f5TWzoezznzLAAAAAElFTkSuQmCC

Данная команда отключит проверку внешних ключей и тем самым позволит очистить таблицу при помощи команды TRUNCATE:

AAAAAElFTkSuQmCC

Также очистить таблицу можно и при помощи DELETE:

DELETE FROM Equipment;

D0jAi4fJLLPKAAAAAElFTkSuQmCC

После очистки таблицы можно вернуть проверку внешних ключей при помощи команды:

GRa4gAAAABJRU5ErkJggg==

Однако такой способ использовать не рекомендуется, потому что вы теряете консистентность данных в базе данных и программа использующая её может работать некорректно. Есть и другое решение. При удалении таблицы удалять все связанные с ней записи в других таблицах.

2. Добавление опции ON DELETE CASCADE

Опция ON DELETE CASCADE используется для неявного удаления строк из дочерней таблицы всякий раз, когда строки удаляются из родительской таблицы. Опция ON DELETE CASCADE её можно задать при создании таблицы, однако если вы этого не сделали, то можно удалить CONSTRAINT и создать его заново.

Для просмотра информации о внешнем ключе содержащемся в таблице необходимо выполнить команду SHOW CREATE TABLE:

SHOW CREATE TABLE EquipmentCategory;

В данном примере таблица называется EquipmentCategory и в ней присутствует константа с именем EquipmentCategory_ibfk_1.

Далее необходимо удалить внешний ключ при помощи команд ALTER TABLE и DROP . Например, если EquipmentCategory — имя таблицы, а EquipmentCategory_ibfk_1 — имя внешнего ключа выполните:

ALTER TABLE EquipmentCategory DROP FOREIGN KEY EquipmentCategory_ibfk_1;

После этого внешний ключ необходимо вернуть обратно добавив к нему опцию ON DELETE CASCADE. Команда будет следующей :

ALTER TABLE EquipmentCategory ADD FOREIGN KEY (category_id) references EquipmentCategory(id) on DELETE CASCADE;

После этого таблицу можно очистить при помощи команды TRUNCATE :

Выводы

В данной статье было рассмотрено как очистить таблицу MySQL от данных. Были рассмотрены команды DELETE и TRUNCATE а также созданы таблицы с наполненной информацией для демонстрации удаления информации. Если у вас остались вопросы задавайте их в комментариях!

delete all from table

handle's user avatar

You can use the below query to remove all the rows from the table, also you should keep it in mind that it will reset the Identity too.

This should be faster:

because RDBMS don’t have to look where is what.

You should be fine with truncate though:

Sarfraz's user avatar

This is deletes the table table_name .

Replace it with the name of the table, which shall be deleted.

Altay Akkus's user avatar

There is a mySQL bug report from 2004 that still seems to have some validity. It seems that in 4.x, this was fastest:

TRUNCATE table_name was DELETE FROM internally back then, providing no performance gain.

This seems to have changed, but only in 5.0.3 and younger. From the bug report:

[11 Jan 2005 16:10] Marko Mäkelä

I’ve now implemented fast TRUNCATE TABLE, which will hopefully be included in MySQL 5.0.3.

Pekka's user avatar

Is a DDL(Data Definition Language), you can delete all data and clean identity. If you want to use this, you need DDL privileges in table.

DDL statements example: CREATE, ALTER, DROP, TRUNCATE, etc.

Is a DML(Data Manipulation Language), you can delete all data. DML statements example: SELECT, UPDATE, etc.

It is important to know this because if an application is running on a server, when we run a DML there will be no problem. But sometimes when using DDL we will have to restart the application service. I had that experience in postgresql.

SQL Clear Table

SQL Clear Table

We can clear the table contents in SQL using two ways. One of the ways of doing so is to use the data definition language command named TRUNCATE that deletes all the records present in the particular table that exists in our SQL database server. Another way of clearing the table is by using the Data manipulation language command DELETE FROM in which we can delete all the contents of the particular table by skipping any restriction on the columns of the table in the where clause and clearing the contents of the table. In this article, we will see how we can clear the table contents in SQL by using truncate command and delete command.

Читать:
Отображать только безопасное содержимое веб страниц как убрать

Using Truncate Command

We can use the ready-made method that is provided in the data definition language commands of SQL named TRUNCATE to remove all the contents of the table in SQL.

Hadoop, Data Science, Statistics & others

Syntax of Truncate Command:

In the above syntax, the name of the table is the table name of which we want to clear all the contents and records that exist in that table. The keyword TABLE needs to be used when using the TRUNCATE command.

Let us consider one example. The table named educba_identity1 which contains 5 rows and has the structure and contents as shown in the output of the below query statement.

Code:

Output:

SQL Clear Table 1

Now to delete all the rows and clear the table named educba_identity1 using the truncate command, we can make the use of the following query statement.

Code:

Output:

SQL Clear Table 2

Let us once again check the contents of the table educba_identity1 and see whether the table is cleared using the following SQL command.

Code:

Output:

SQL Clear Table 3

We can observe that the table named educba_identity1 has been cleared successfully and there is none of the record present in the table.

Using Delete Command

We can clear the contents of the table by using the delete command which is one of SQL command of the set of the data manipulation language commands that are available in SQL. This command is most often used to delete the selected rows present in the table.

Syntax of Delete Command:

In the above syntax, the name of the table is the table name of which we want to clear all the contents and records that exist in that table. The keyword TABLE needs to be used when using the TRUNCATE command.

Let us consider one example. The table named educba_identity2 which contains 5 rows and has the structure and contents as shown in the output of the below query statement.

Code:

Output:

SQL Clear Table 4

Now to delete all the rows and clear the table named educba_identity2 using the truncate command, we can make the use of the following query statement.

Code:

Output:

SQL Clear Table 5

Let us once again check the contents of the table educba_identity1 and see whether the table is cleared using the following SQL command.

Code:

Output:

SQL Clear Table 6

We can observe that the table named educba_identity2 has been cleared successfully and there is none of the record present in the table.

Using Drop Table

We can alternatively use the drop command to delete the whole table along with its contents and structure that completely vanishes the existence of that table in our database in the SQL. But we will have to create the same table again using the CREATE table command in SQL. Note that drop command not only clears the table contents but also the structure of the table.

Let us consider one example in which we have one existing table named educba_writers_demo that has the columns and the contents of the table that are as shown in the output of the below query statement.

Code:

Output:

SQL Clear Table 7

Now, let us drop the table by using the drop command in SQL that clears the table contents as well as the table existence in our database.

Code:

Output:

drop the table by using the drop command

Let us check the contents of the table by using the following query statement.

Code:

The execution of output of the above query statement is as shown below that shows the error saying that the table does not exist.

Output:

error saying

Let us recreate the table using the following create table command.

Code:

Output:

recreate the table

This successfully creates the table named educba_writers_demo that has the same structure. Let us try rechecking the contents of the table.

Code:

Output:

educba_writers_demo

This shows that the table contents have been cleared.

Conclusion – SQL Clear Table

We can clear the contents of the table in SQL by using multiple methods that include the usage of the data definition language command name truncates or data manipulation command named DELETE. An alternative method of clearing the contents of the table involves dropping the table that deleted the table as well as the contents of the table and recreates the table again using the CREATE table command.

Recommended Articles

We hope that this EDUCBA information on “SQL Clear Table” was beneficial to you. You can view EDUCBA’s recommended articles for more information.

TRUNCATE TABLE

Оператор TRUNCATE TABLE используется для удаления всех записей из таблицы в Oracle. Он выполняет ту же функцию что и DELETE, только без условий WHERE.

Предупреждение: Если вы очистите таблицу с помощью оператора TRUNCATE TABLE, то ее откат невозможен.

Синтаксис

Синтаксис для оператора TRUNCATE TABLE в Oracle/PLSQL:

Параметры или аргументы

Необязательный. Если указано, то это имя схемы к которой принадлежит таблица.

Таблица, которую вы хотите очистить.

PRESERVE MATERIALIZED VIEW LOG

Необязательный. Если указано, то materialized view log будет сохранено, когда таблица очищается. Это поведение по умолчанию.

PURGE MATERIALIZED VIEW LOG

Необязательный. Если указано, то materialized view log будет очищен, когда таблица очищается.

Необязательный. Если указано, всё хранилище очищающихся строк будет высвобождено, за исключением пространства, которое было выделено в MINEXTENTS . Это поведение по умолчанию.

Необязательный. Если указано, всё хранилище очищающихся строк останется распределенным в таблице.

Пример

В Oracle очищение таблицы является быстрым способом, чтобы очистить записи из таблицы, если вам не нужно беспокоиться об откате. Одной из причин является то, что, когда таблица очищается, это не влияет на какие-либо из индексов, триггеров или зависимостей таблицы. Очищение таблицы также намного проще, чем удаление таблицы и ее воссоздания.

Рассмотрим пример того, как использовать оператор TABLE TRUNCATE в Oracle/PLSQL.

Похожие статьи