В каких случаях предпочтительнее использовать инструкцию truncate table а не delete

Приветствую всех на сайте Info-Comp.ru! Сегодня я расскажу Вам об отличиях, которые существуют между инструкциями TRUNCATE TABLE и DELETE в языке T-SQL, Вы узнаете, в каких случаях лучше использовать DELETE, а в каких предпочтительней TRUNCATE.

Отличия TRUNCATE от DELETE в языке T-SQL

Для того чтобы удалить данные из таблицы в Microsoft SQL Server можно использовать несколько инструкций, в частности DELETE и TRUNCATE TABLE. Эти операторы похожи, так как их предназначение одно – это удаление строк из таблицы. В связи с этим у многих возникают вопросы, например – а в чем отличие TRUNCATE от DELETE? или Когда лучше использовать TRUNCATE, а когда DELETE? Подобные вопросы задают и на собеседованиях, ведь понимание различий между этими операторами помогает разработчикам SQL эффективно работать с данными, строить приложения и запросы.

Заметка! Сборник статей для изучения языка T-SQL и Microsoft SQL Server – в этом материале я собрал лучшие свои статьи по SQL Server и сгруппировал их по уровню подготовки.

Для начала давайте дадим короткое определение этим двум операторам.

Содержание

  1. Что такое DELETE?
  2. Что такое TRUNCATE TABLE?
  3. Сравнительная таблица отличий TRUNCATE TABLE и DELETE
  4. Пример отличия в работе TRUNCATE TABLE от DELETE

DELETE – это SQL инструкция языка T-SQL, которая удаляет одну или несколько строк из таблицы или представления в Microsoft SQL Server, при этом эта операция всегда полностью регистрируется в журнале транзакций, т.е. каждая удаленная строка.

Что такое TRUNCATE TABLE?

TRUNCATE TABLE – это SQL инструкция языка T-SQL, которая удаляет все строки в таблице, не записывая в журнал транзакций удаление отдельных строк данных. TRUNCATE TABLE похожа на инструкцию DELETE без предложения WHERE, но она выполняется быстрее и требует меньше ресурсов.

Сравнительная таблица отличий TRUNCATE TABLE и DELETE

Теперь давайте сформируем сравнительную таблицу, в которой отразим все отличия и особенности работы TRUNCATE TABLE и DELETE в языке T-SQL.

DELETE TRUNCATE TABLE
DELETE – это оператор DML (Data Manipulation Language) TRUNCATE TABLE – это оператор DDL (Data Definition Language);
DELETE может удалить часть данных за счет использования WHERE TRUNCATE TABLE удаляет все данные из таблицы, секцию WHERE использовать нельзя
DELETE записывает в журнал транзакций удаление каждой строки TRUNCATE TABLE удаляет все строки в таблице, не записывая при этом удаление отдельных строк данных в журнал транзакций
Для DELETE требуется больший объем журнала транзакций Для TRUNCATE TABLE требуется меньший объем журнала транзакций, за счет того, что она не заносит в журнал запись для каждой удаляемой строки
DELETE выполняется медленнее TRUNCATE TABLE выполняется быстрее также за счет меньшего использования журнала транзакций
DELETE удаляет строки по одной за раз TRUNCATE TABLE удаляет все строки в таблице путем освобождения страниц
DELETE создает блокировку на каждую строку, которую требуется удалить из таблицы TRUNCATE TABLE блокирует в целом таблицу и страницу, чтобы удалить все записи
DELETE сохраняет счетчик идентификаторов и не сбрасывает его до начального значения TRUNCATE TABLE сбрасывает счетчик идентификаторов до начального значения
DELETE может активировать триггер TRUNCATE TABLE не может активировать триггер, поскольку в данном случае в журнал не записываются удаление отдельных строк
DELETE сохраняет статистику объекта и выделенное пространство TRUNCATE TABLE освобождает все страницы данных таблицы, поэтому TRUNCATE удаляет всю статистику и выделенное пространство
DELETE можно использовать, если таблица является частью индексированного представления TRUNCATE TABLE нельзя использовать, если таблица является частью индексированного представления
Чтобы использовать DELETE, необходимы соответствующие права на удаление данных Чтобы использовать TRUNCATE TABLE, у Вас должны быть права на ALTER TABLE, т.е. на изменение таблицы

Заметка! Чем отличаются функции от хранимых процедур в T-SQL.

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

Самым очевидным здесь является то, что если Вам нужно удалить не все данные из таблицы, а только часть, т.е. по условию WHERE, то Вы можете использовать только DELETE.

Курс по SQL для начинающих

А, например, если Вам приходится периодически очищать всю таблицу, и значения идентификаторов не важны, то вполне возможно предпочтительней будет использовать TRUNCATE TABLE, так как это будет быстрей, и ресурсов затрачиваться будет меньше.

Пример отличия в работе TRUNCATE TABLE от DELETE

Для примера давайте создадим таблицу со столбцом идентификаторов, затем добавим в нее данные и удалим их сначала инструкцией DELETE, а потом попробуем выполнить то же самое только инструкцией TRUNCATE TABLE (предварительно пересоздав таблицу).

Создание тестовой таблицы

  
   CREATE TABLE Goods(
      ProductId INT IDENTITY(1,1) NOT NULL,
      ProductName VARCHAR(100) NOT NULL
   );

Выполняем удаление с помощью DELETE

   
   --Добавляем данные
   INSERT INTO Goods
      VALUES ('Компьютер'),
             ('Монитор'),
             ('Принтер');
        
   --Выборка данных                   
   SELECT * FROM Goods;
        
   --Удаляем все данные инструкцией DELETE
   DELETE Goods;
        
   --Снова добавляем данные
   INSERT INTO Goods
      VALUES ('Компьютер'),
             ('Монитор'),
             ('Принтер');
        
   --Выборка данных
   SELECT * FROM Goods;

Скриншот 1

Выполняем удаление инструкцией TRUNCATE TABLE

   
   --Добавляем данные
   INSERT INTO Goods
      VALUES ('Компьютер'),
             ('Монитор'),
             ('Принтер');

   --Выборка данных
   SELECT * FROM Goods;

   --Удаляем все данные инструкцией TRUNCATE TABLE
   TRUNCATE TABLE Goods;

  --Снова добавляем данные
  INSERT INTO Goods
     VALUES ('Компьютер'),
            ('Монитор'),
            ('Принтер');

   --Выборка данных
   SELECT * FROM Goods;

Скриншот 2

Как видите, в первом случае счетчик не сбросился, и нумерация продолжилась, а во втором счетчик начался с самого начала.

Заметка! Для комплексного изучения языка SQL и T-SQL рекомендую посмотреть мои видеокурсы по T-SQL, в которых используется последовательная методика обучения специально для начинающих.

На сегодня это все, пока!

I have some tables that I build as a part of my report rollup. I don’t need them afterwards at all. Someone mentioned to truncate them as it would be faster.

juan's user avatar

juan

80.3k52 gold badges162 silver badges195 bronze badges

asked Sep 25, 2008 at 20:02

Brian G's user avatar

2

Deleting records from a table logs every deletion and executes delete triggers for the records deleted. Truncate is a more powerful command that empties a table without logging each row. SQL Server prevents you from truncating a table with foreign keys referencing it, because of the need to check the foreign keys on each row.

Truncate is normally ultra-fast, ideal for cleaning out data from a temporary table. It does preserve the structure of the table for future use.

If you actually want to remove the table definitions as well as the data, simply drop the tables.

See this MSDN article for more info

answered Sep 25, 2008 at 20:07

JoshL's user avatar

JoshLJoshL

10.7k11 gold badges55 silver badges61 bronze badges

2

DROP TABLE deletes the table.

TRUNCATE TABLE empties it, but leaves its structure for future data.

answered Sep 25, 2008 at 20:03

ceejayoz's user avatar

ceejayozceejayoz

177k40 gold badges303 silver badges368 bronze badges

2

DROP and TRUNC do different things:

TRUNCATE TABLE

Removes all rows from a table without
logging the individual row deletions.
TRUNCATE TABLE is similar to the
DELETE statement with no WHERE clause;
however, TRUNCATE TABLE is faster and
uses fewer system and transaction log
resources.

DROP TABLE

Removes one or more table definitions
and all data, indexes, triggers,
constraints, and permission
specifications for those tables.

As far as speed is concerned the difference should be small. And anyway if you don’t need the table structure at all, certainly use DROP.

answered Sep 25, 2008 at 20:10

daremon's user avatar

daremondaremon

4,8942 gold badges27 silver badges27 bronze badges

I think you means the difference between DELETE TABLE and TRUNCATE TABLE.

DROP TABLE

remove the table from the database.

DELETE TABLE

without a condition delete all rows. If there are trigger and references then this will process for every row. Also a index will be modify if there one.

TRUNCATE TABLE

set the row count zero and without logging each row. That it is many faster as the other both.

answered Sep 25, 2008 at 20:06

Horcrux7's user avatar

Horcrux7Horcrux7

23.8k21 gold badges98 silver badges156 bronze badges

1

None of these answer point out an important difference about these two operations. Drop table is an operation that can be rolled back. However, truncate cannot be rolled back [‘TRUNCATE TABLE’ can be rolled back as well]. In this way dropping a very large table can be very expensive if there are many rows, because they all have to be recorded in a temporary space in case you decide to roll it back.

Usually, if I want to get rid of a large table, I will truncate it, then drop it. This way the data will be nixed without record, and the table can be dropped, and that drop will be very inexpensive because no data needs to be recorded.

It is important to point out though that truncate just deletes data, leaving the table, while drop will, in fact, delete the data and the table itself. (assuming foreign keys don’t preclude such an action)

SolutionYogi's user avatar

SolutionYogi

31.8k12 gold badges70 silver badges78 bronze badges

answered Sep 25, 2008 at 20:16

Nathan Feger's user avatar

Nathan FegerNathan Feger

19.1k11 gold badges62 silver badges71 bronze badges

2

DROP Table

DROP TABLE [table_name];

The DROP command is used to remove a table from the database. It is a DDL command. All the rows, indexes and privileges of the table will also be removed. DROP operation cannot be rolled back.

DELETE Table

DELETE FROM [table_name]
WHERE [condition];

DELETE FROM [table_name];

The DELETE command is a DML command. It can be used to delete all the rows or some rows from the table based on the condition specified in WHERE clause. It is executed using a row lock, each row in the table is locked for deletion. It maintain the transaction log, so it is slower than TRUNCATE.
DELETE operations can be rolled back.

TRUNCATE Table

TRUNCATE TABLE [table_name];

The TRUNCATE command removes all rows from a table. It won’t log the deletion of each row, instead it logs the deallocation of the data pages of the table, which makes it faster than DELETE. It is executed using a table lock and whole table is locked for remove all records. It is a DDL command. TRUNCATE operations cannot be rolled back.

answered Dec 6, 2017 at 5:37

Optimizer's user avatar

OptimizerOptimizer

6877 silver badges7 bronze badges

1

TRUNCATE TABLE keeps all of your old indexing and whatnot. DROP TABLE would, obviously, get rid of the table and require you to recreate it later.

Filip De Vos's user avatar

Filip De Vos

11.6k1 gold badge48 silver badges60 bronze badges

answered Sep 25, 2008 at 20:04

Kevin Fairchild's user avatar

Kevin FairchildKevin Fairchild

10.9k6 gold badges33 silver badges52 bronze badges

Drop gets rid of the table completely, removing the definition as well. Truncate empties the table but does not get rid of the definition.

answered Sep 25, 2008 at 20:04

DMKing's user avatar

DMKingDMKing

1,7051 gold badge10 silver badges13 bronze badges

Truncating the table empties the table. Dropping the table deletes it entirely. Either one will be fast, but dropping it will likely be faster (depending on your database engine).

If you don’t need it anymore, drop it so it’s not cluttering up your schema.

answered Sep 25, 2008 at 20:04

Dan Udey's user avatar

Dan UdeyDan Udey

2,9672 gold badges21 silver badges18 bronze badges

DELETE TableA instead of TRUNCATE TableA?
A common misconception is that they do the same thing. Not
so. In fact, there are many differences between the two.

DELETE is a logged operation on a per row basis. This means
that the deletion of each row gets logged and physically deleted.

You can DELETE any row that will not violate a constraint, while leaving the foreign key or any other contraint in place.

TRUNCATE is also a logged operation, but in a different way.
TRUNCATE logs the deallocation of the data pages in which the data
exists. The deallocation of data pages means that your data
rows still actually exist in the data pages, but the
extents have been marked as empty for reuse. This is what
makes TRUNCATE a faster operation to perform over DELETE.

You cannot TRUNCATE a table that has any foreign key
constraints. You will have to remove the contraints, TRUNCATE the
table, and reapply the contraints.

TRUNCATE will reset any identity columns to the default seed
value.

answered Oct 5, 2013 at 19:58

Raja's user avatar

RajaRaja

513 bronze badges

1

truncate removes all the rows, but not the table itself, it is essentially equivalent to deleting with no where clause, but usually faster.

answered Sep 25, 2008 at 20:04

mmaibaum's user avatar

mmaibaummmaibaum

2,37913 silver badges11 bronze badges

1

I have a correction for one of the statements above… «truncate cannot be rolled back»

Truncate can be rolled back. There are some cases when you can’t do a truncate or drop table, such as when you have a foreign key reference. For a task such as monthly reporting, I’d probably just drop the table once I didn’t need it anymore. If I was doing this rollup reporting more often then I’d probably keep the table instead and use truncate.

Hope this helps, here’s some more info that you should find useful…

Please see the following article for more details:
http://sqlblog.com/blogs/denis_gobo/archive/2007/06/13/1458.aspx

Also, for more details on delete vs. truncate, see this article:
http://www.sql-server-performance.com/faq/delete_truncate_difference_p1.aspx

Thanks!
Jeff

answered Sep 25, 2008 at 20:59

Jeff's user avatar

JeffJeff

3883 silver badges10 bronze badges

TRUNCATE TABLE is functionally
identical to DELETE statement with no
WHERE clause: both remove all rows in
the table. But TRUNCATE TABLE is
faster and uses fewer system and
transaction log resources than DELETE.

The DELETE statement removes rows one
at a time and records an entry in the
transaction log for each deleted row.
TRUNCATE TABLE removes the data by
deallocating the data pages used to
store the table’s data, and only the
page deallocations are recorded in the
transaction log.

TRUNCATE TABLE removes all rows from a
table, but the table structure and its
columns, constraints, indexes and so
on remain. The counter used by an
identity for new rows is reset to the
seed for the column. If you want to
retain the identity counter, use
DELETE instead. If you want to remove
table definition and its data, use the
DROP TABLE statement.

You cannot use TRUNCATE TABLE on a
table referenced by a FOREIGN KEY
constraint; instead, use DELETE
statement without a WHERE clause.
Because TRUNCATE TABLE is not logged,
it cannot activate a trigger.

TRUNCATE TABLE may not be used on
tables participating in an indexed
view.

From http://msdn.microsoft.com/en-us/library/aa260621(SQL.80).aspx

answered Sep 26, 2008 at 1:12

Ricardo C's user avatar

Ricardo CRicardo C

2,20520 silver badges24 bronze badges

In the SQL standard, DROP table removes the table and the table schema — TRUNCATE removes all rows.

Marcus Adams's user avatar

Marcus Adams

53k9 gold badges92 silver badges143 bronze badges

answered Sep 25, 2008 at 20:04

hangy's user avatar

hangyhangy

10.8k6 gold badges43 silver badges63 bronze badges

The answers here match up to the question, but I’m going to answer the question you didn’t ask. «Should I use truncate or delete?» If you are removing all rows from a table, you’ll typically want to truncate, since it’s much much faster. Why is it much faster? At least in the case of Oracle, it resets the high water mark. This is basically a dereferencing of the data and allows the db to reuse it for something else.

answered Sep 25, 2008 at 20:12

Dan Coates's user avatar

Dan CoatesDan Coates

2,0023 gold badges17 silver badges21 bronze badges

DELETE VS TRUNCATE

  1. The DELETE statement removes rows one at a time and records an entry in the transaction
    log for each deleted row. TRUNCATE TABLE removes the data by deallocating the data
    pages used to store the table data and records only the page deallocations in the
    transaction log
  2. We can use WHERE clause in DELETE but in TRUNCATE you cannot use it
  3. When the DELETE statement is executed using a row lock, each row in the table is locked
    for deletion. TRUNCATE TABLE always locks the table and page but not each row
  4. After a DELETE statement is executed, the table can still contain empty pages.If the
    delete operation does not use a table lock, the table (heap) will contain many empty
    pages. For indexes, the delete operation can leave empty pages behind, although these
    pages will be deallocated quickly by a background cleanup process
  5. TRUNCATE TABLE removes all rows from a table, but the table structure and its columns,
    constraints, indexes, and so on remain
  6. DELETE statement doesn’t RESEED identity column but TRUNCATE statement RESEEDS the
    IDENTITY column
  7. You cannot use TRUNCATE TABLE on tables that:
    1. Are referenced by a FOREIGN KEY constraint. (You can truncate a table that has a
      foreign key that references itself.)
    2. Participate in an indexed view.
    3. Are published by using transactional replication or merge replication
  8. TRUNCATE TABLE cannot activate a trigger because the operation does not log individual
    row deletions

Brad Gilbert's user avatar

Brad Gilbert

33.8k11 gold badges78 silver badges129 bronze badges

answered Apr 7, 2010 at 9:06

Sasikiran's user avatar

Drop
drop whole table and all its structure

truncate
delete all rows from table
it is different from delete that it also delete indexes of rows

answered Mar 29, 2018 at 8:36

ZIA's user avatar

Delete Statement

Delete Statement delete table rows and return the number of rows is deleted from the table.in this statement, we use where clause to deleted data from the table

  • Delete Statement is slower than Truncate statement because it deleted records one by one

Truncate Statement

Truncate statement Deleted or removing all the rows from the table.

  • It is faster than the Delete Statement because it deleted all the records from the table
  • Truncate statement not return the no of rows are deleted from the table

Drop statement

Drop statement deleted all records as well as the structure of the table

answered Mar 24, 2018 at 17:39

Zubair Saif's user avatar

Zubair SaifZubair Saif

1,1061 gold badge14 silver badges29 bronze badges

DELETE

The DELETE command is used to remove rows from a table. A WHERE clause can be used to only remove some rows. If no WHERE condition is specified, all rows will be removed. After performing a DELETE operation you need to
COMMIT or ROLLBACK the transaction to make the change permanent or to undo it.

TRUNCATE

TRUNCATE removes all rows from a table. The operation cannot be rolled back … As such, TRUCATE is faster and doesn’t use as much undo space as a DELETE.

From: http://www.orafaq.com/faq/difference_between_truncate_delete_and_drop_commands

Community's user avatar

answered Dec 3, 2008 at 6:03

ПрограммированиеData science+3

Даже не знаю с чего начать вам сей увлекательный рассказ.

DELETE — инструкция, которая позволяет удалить одну, несколько или все строки из таблицы. 

TRUNICATE — удаляет все данные из таблицы

Кроме того, DELETE позволяет использовать условия WHERE которых вы можете указать в каких случаях необходимо произвести удаления, а TRUNICATE вам этого сделать не позволит, WHERE в ней нет.

DELETE — медленнее, TRUNICATE — быстрее ( заметно будет при больших объёмах данных.

DELETE записывает в журнал транзакций каждое удаление

для DELETE требуются права на удаление, а TRUNICATE требует права на изменение таблицы ( ALTER TABLE)

вызов DELETE может активировать триггеры,  а TRUNICATE нет ( читай про журнал транзакций)

DELETE блокирует удаляемую строку (строки) TRUNICATE — блокирует таблицу.

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

Я сталкивался, что если делаешь DETELE, то имеющиеся индексы автоматически перестраиваются (один из факторов его… Читать дальше

Узнайте, как операторы TRUNCATE и DELETE работают в SQL, в чем разница между ними и когда лучше использовать один, а не другой.

При работе с таблицами базы данных может потребоваться удалить подмножество строк или все строки. Чтобы удалить строки из таблицы базы данных, вы можете использовать инструкции SQL TRUNCATE или DELETE в зависимости от варианта использования.

В этом руководстве мы подробно рассмотрим каждое из операторов, поймем, как они работают, и решим, когда лучше использовать TRUNCATE вместо DELETE и наоборот.

Прежде чем мы двинемся дальше, полезно рассмотреть следующие подмножества SQL:

  • Операторы языка определения данных (DDL) используются для создания объектов базы данных, таких как таблицы, и управления ими. Операторы SQL CREATE, DROP и TRUNCATE являются примерами операторов DDL.
  • Операторы языка манипулирования данными (DML) используются для управления данными в объектах базы данных. Операторы DML используются для выполнения операций создания, чтения, обновления и удаления записей.
  • Операторы языка запросов данных (DQL) используются для извлечения данных из таблиц базы данных. Все операторы SELECT относятся к подмножеству DQL.

Оглавление

Синтаксис оператора SQL TRUNCATE

Синтаксис использования оператора SQL TRUNCATE следующий:

TRUNCATE TABLE table_name;

Выполнение приведенной выше команды TRUNCATE удаляет все строки в таблице, указанной в table_name, но не удаляет таблицу.

Операция усечения не сканирует все записи в таблице. Таким образом, при работе с большими таблицами базы данных это происходит быстрее.

Пример использования SQL TRUNCATE

📑 Примечание: если у вас есть MySQL установлен на вашем компьютере, вы можете кодировать с помощью клиента командной строки MySQL. Вы также можете следовать в другой СУБД по вашему выбору, такой как PostgreSQL.

Давайте сначала создадим базу данных для работы с:

mysql> CREATE DATABASE db1;
Query OK, 1 row affected (1.50 sec)

Затем выберите базу данных, которую мы только что создали:

mysql> use db1;
Database changed

Следующим шагом является создание таблицы базы данных. Запустите следующую инструкцию CREATE TABLE, чтобы создать простую таблицу задач:

-- Create the tasks table
CREATE TABLE tasks (
    task_id INT AUTO_INCREMENT PRIMARY KEY,
    title VARCHAR(255) NOT NULL,
    due_date DATE,
    status ENUM('Pending', 'In Progress', 'Completed') DEFAULT 'Pending',
    assignee VARCHAR(100)
);

В этом примере таблица задач имеет следующие столбцы:

  • task_id: автоматически увеличивающийся уникальный идентификатор для каждой задачи.
  • title: Название или название задачи, не более 255 символов.
  • due_date: срок выполнения задачи, представленный в виде даты.
  • статус: статус задачи, который может быть «Ожидание», «Выполняется» или «Завершено». По умолчанию установлено значение «Ожидание».
  • правопреемник: правопреемник для конкретной задачи.

Теперь, когда мы создали таблицу tasks, давайте вставим в нее записи:

-- Inserting multiple records into the tasks table
INSERT INTO tasks (title, due_date, status, assignee)
VALUES
    ('Task 1', '2023-08-10', 'Pending', 'John'),
    ('Task 2', '2023-08-11', 'In Progress', 'Jane'),
    ('Task 3', '2023-08-12', 'Completed', 'Mike'),
    ('Task 4', '2023-08-13', 'Pending', 'Alice'),
    ('Task 5', '2023-08-14', 'In Progress', 'Bob'),
    ('Task 6', '2023-08-15', 'Completed', 'Emily'),
    ('Task 7', '2023-08-16', 'Pending', 'David'),
    ('Task 8', '2023-08-17', 'In Progress', 'Olivia'),
    ('Task 9', '2023-08-18', 'Pending', 'Daniel'),
    ('Task 10', '2023-08-19', 'Completed', 'Sophia'),
    ('Task 11', '2023-08-20', 'Pending', 'Matthew'),
    ('Task 12', '2023-08-21', 'In Progress', 'Ava'),
    ('Task 13', '2023-08-22', 'Completed', 'William'),
    ('Task 14', '2023-08-23', 'Pending', 'Ella'),
    ('Task 15', '2023-08-24', 'In Progress', 'James'),
    ('Task 16', '2023-08-25', 'Completed', 'Lily'),
    ('Task 17', '2023-08-26', 'Pending', 'Benjamin'),
    ('Task 18', '2023-08-27', 'In Progress', 'Mia'),
    ('Task 19', '2023-08-28', 'Pending', 'Henry'),
    ('Task 20', '2023-08-29', 'Completed', 'Isabella');

После запуска оператора вставки вы должны увидеть аналогичный вывод:

Query OK, 20 rows affected (0.18 sec)
Records: 20  Duplicates: 0  Warnings: 0

Теперь запустите команду TRUNCATE table, чтобы удалить все записи из таблицы tasks:

TRUNCATE TABLE tasks;
Query OK, 0 rows affected (0.72 sec)

При этом удаляются все записи, а не таблица. Вы можете убедиться в этом, запустив SHOW TABLES; вот так:

SHOW TABLES;
+---------------+
| Tables_in_db1 |
+---------------+
| tasks         |
+---------------+
1 row in set (0.00 sec)

И запрос SELECT для извлечения данных из таблицы tasks возвращает пустой набор:

SELECT * FROM tasks;
Empty set (0.00 sec)

Как использовать оператор SQL DELETE

Синтаксис оператора SQL DELETE

Общий синтаксис для использования оператора SQL DELETE следующий:

DELETE FROM table_name 
WHERE condition;

Условие в предложении WHERE — это предикат, определяющий, какие строки следует удалить. Оператор DELETE удаляет все строки, для которых предикат имеет значение True.

Таким образом, оператор DELETE позволяет лучше контролировать, какие записи удаляются.

Но что происходит, когда вы используете оператор DELETE без предложения WHERE?🤔

DELETE FROM table_name;

Выполнение оператора DELETE, как показано, удаляет все строки в таблице базы данных.

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

Пример использования SQL DELETE

Теперь давайте посмотрим на оператор удаления SQL в действии.

Мы удалили все записи из таблицы tasks. Таким образом, вы можете повторно запустить инструкцию INSERT (которую мы запускали ранее) для вставки записей:

-- Inserting multiple records into the tasks table
INSERT INTO tasks (title, due_date, status, assignee)
VALUES
    ('Task 1', '2023-08-10', 'Pending', 'John'),
    ('Task 2', '2023-08-11', 'In Progress', 'Jane'),
    ('Task 3', '2023-08-12', 'Completed', 'Mike'),
    ...
    ('Task 18', '2023-08-27', 'In Progress', 'Mia'),
    ('Task 19', '2023-08-28', 'Pending', 'Henry'),
    ('Task 20', '2023-08-29', 'Completed', 'Isabella');

Сначала воспользуемся оператором DELETE с предложением WHERE. Следующий запрос удаляет все строки со статусом «Завершено»:

DELETE FROM tasks WHERE status="Completed";
Query OK, 6 rows affected (0.14 sec)

Теперь запустите этот запрос SELECT:

SELECT * FROM tasks;

Вы увидите, что в настоящее время имеется 14 строк:

+---------+---------+------------+-------------+----------+
| task_id | title   | due_date   | status      | assignee |
+---------+---------+------------+-------------+----------+
|       1 | Task 1  | 2023-08-10 | Pending     | John     |
|       2 | Task 2  | 2023-08-11 | In Progress | Jane     |
|       4 | Task 4  | 2023-08-13 | Pending     | Alice    |
|       5 | Task 5  | 2023-08-14 | In Progress | Bob      |
|       7 | Task 7  | 2023-08-16 | Pending     | David    |
|       8 | Task 8  | 2023-08-17 | In Progress | Olivia   |
|       9 | Task 9  | 2023-08-18 | Pending     | Daniel   |
|      11 | Task 11 | 2023-08-20 | Pending     | Matthew  |
|      12 | Task 12 | 2023-08-21 | In Progress | Ava      |
|      14 | Task 14 | 2023-08-23 | Pending     | Ella     |
|      15 | Task 15 | 2023-08-24 | In Progress | James    |
|      17 | Task 17 | 2023-08-26 | Pending     | Benjamin |
|      18 | Task 18 | 2023-08-27 | In Progress | Mia      |
|      19 | Task 19 | 2023-08-28 | Pending     | Henry    |
+---------+---------+------------+-------------+----------+
14 rows in set (0.00 sec)

Выполнение следующего оператора DELETE удаляет все оставшиеся 14 записей в таблице:

DELETE FROM tasks;
Query OK, 14 rows affected (0.20 sec)

И таблица задач теперь пуста:

SELECT * FROM tasks;
Empty set (0.00 sec)

Оператор SQL DROP

На данный момент мы узнали:

  • Оператор TRUNCATE удаляет все строки из таблицы.
  • Оператор DELETE — без предложения WHERE — удаляет все записи из таблицы.

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

DROP TABLE table_name;

Теперь давайте удалим таблицу tasks из базы данных:

mysql> DROP TABLE tasks;
Query OK, 0 rows affected (0.43 sec)

Вы увидите, что SHOW TABLES; возвращает пустой набор (поскольку мы удалили единственную таблицу, которая присутствовала в базе данных):

mysql> SHOW TABLES;
Empty set (0.00 sec)

Когда использовать TRUNCATE или DELETE в SQL

ФункцияTRUNCATEDELETESСинтаксисTRUNCATE TABLE имя_таблицы; с условием WHERE: DELETE FROM имя_таблицы ГДЕ условие;
Без предложения WHERE: DELETE TABLE имя_таблицы;Подмножество SQLЯзык определения данных (DDL)Язык манипулирования данными (DML)ЭффектУдаляет все строки в таблице базы данных.При запуске без предложения WHERE оператор DELETE удаляет все записи в таблице базы данных.ПроизводительностьБольше эффективнее оператора DELETE при работе с большими таблицами. Менее эффективен, чем оператор TRUNCATE.

Подводить итоги:

  • Если вам нужно удалить все строки из большой таблицы базы данных, используйте оператор TRUNCATE.
  • Чтобы удалить подмножество строк на основе определенных условий, используйте оператор DELETE.

Подводя итоги

Завершим нашу дискуссию подведением итогов:

  • При работе с таблицами базы данных может потребоваться удалить подмножество строк или все строки в определенной таблице. Для этого вы можете использовать операторы TRUNCATE или DELETE.
  • Оператор TRUNCATE имеет синтаксис: TRUNCATE TABLE имя_таблицы;. Он удаляет все строки в таблице, указанной в table_name, но не удаляет саму таблицу.
  • Оператор DELETE имеет следующий синтаксис: DELETE FROM имя_таблицы WHERE условие;. Это удаляет строки, для которых условие предиката истинно.
  • Выполнение инструкции SQL DELETE без предложения WHERE удаляет все строки в таблице. Таким образом, функционально это дает тот же результат, что и оператор SQL TRUNCATE.
  • Запуск TRUNCATE особенно быстрее при работе с большими таблицами, так как он не сканирует всю таблицу. Поэтому, когда вам нужно удалить все строки в большой таблице базы данных, запуск truncate может быть более эффективным.
  • Когда вам нужно удалить подмножество строк — на основе определенного условия — вы можете использовать оператор SQL DELETE.

Для быстрого ознакомления с часто используемыми командами SQL ознакомьтесь с этой памяткой по SQL.

Here is a summary of some important differences between these sql commands:

sql truncate command:

1) It is a DDL (Data Definition Language) command, therefore commands such as COMMIT and ROLLBACK do not apply to this command (the exceptions here are PostgreSQL and MSSQL, whose implementation of the TRUNCATE command allows the command to be used in a transaction)

2) You cannot undo the operation of deleting records, it occurs automatically and is irreversible (except for the above exceptions — provided, however, that the operation is included in the TRANSACTION block and the session is not closed). In case of Oracle — Includes two implicit commits, one before and one after the statement is executed. Therefore, the command cannot be withdrawn while a runtime error will result in commit anyway

3) Deletes all records from the table, records cannot be limited to deletion. For Oracle, when the table is split per partition, individual partitions can be truncated (TRUNCATE) in isolation, making it possible to partially remove all data from the table

4) Frees up the space occupied by the data in the table (in the TABLESPACE — on disk). For Oracle — if you use the REUSE STORAGE clause, the data segments will not be rolled back, i.e. you will keep space from the deleted rows allocated to the table, which can be a bit more efficient if the table is to be reloaded with data. The high mark will be reset

5) TRUNCATE works much faster than DELETE

6) Oracle Flashback in the case of TRUNCATE prevents going back to pre-operative states

7) Oracle — TRUNCATE cannot be granted (GRANT) without using DROP ANY TABLE

8) The TRUNCATE operation makes unusable indexes usable again

9) TRUNCATE cannot be used when the enabled foreign key refers to another table, then you can:

  • execute the command: DROP CONSTRAINT, then TRUNCATE, and then play it through CREATE CONSTRAINT or
  • execute the command: SET FOREIGN_KEY_CHECKS = 0; then TRUNCATE, then: SET_FOREIGN_KEY_CHECKS = 1;

10) TRUNCATE requires an exclusive table lock, therefore, turning off exclusive table lock is a way to prevent TRUNCATE operation on the table

11) DML triggers do not fire after executing TRUNCATE (so be very careful in this case, you should not use TRUNCATE, if a delete trigger is defined in the table to perform an automatic table cleanup or a logon action after row deletion). On Oracle, DDL triggers are fired

12) Oracle — TRUNCATE cannot be used in the case of: database link
13) TRUNCATE does not return the number of records deleted

14) Transaction log — one log indicating page deallocation (removes data, releasing allocation of data pages used for storing table data and writes only page deallocations to the transaction log) — faster execution than DELETE. TRUNCATE only needs to adjust the pointer in the database to the table (High Water Mark) and the data is immediately deleted, therefore it uses less system resources and transaction logs

15) Performance (acquired lock) — table and page lock — does not degrade performance during execution

16) TRUNCATE cannot be used on tables involved in transactional replication or merge replication

sql delete command:

1) It is a DML (Data Manipulation Language) command, therefore the following commands are used for this command: COMMIT and ROLLBACK

2) You can undo the operation of removing records by using the ROLLBACK command

3) Deletes all or some records from the table, you can limit the records to be deleted by using the WHERE clause

4) Does not free the space occupied by the data in the table (in the TABLESPACE — on the disk)

5) DELETE works much slower than TRUNCATE

6) Oracle Flashback works for DELETE

7) Oracle — For DELETE, you can use the GRANT command

8) The DELETE operation does not make unusable indexes usable again

9) DELETE in case foreign key enabled refers to another table, can (or not) be applied depending on foreign key configuration (if not), please:

  • execute the command: DROP CONSTRAINT, then TRUNCATE, and then play it through CREATE CONSTRAINT or
  • execute the command: SET FOREIGN_KEY_CHECKS = 0; then TRUNCATE, then: SET_FOREIGN_KEY_CHECKS = 1;

10) DELETE requires a shared table lock

11) Triggers fire

12) DELETE can be used in the case of: database link

13) DELETE returns the number of records deleted

14) Transaction log — for each deleted record (deletes rows one at a time and records an entry in the transaction log for each deleted row) — slower execution than TRUNCATE. The table may still contain blank pages after executing the DELETE statement. DELETE needs to read records, check constraints, update block, update indexes, and generate redo / undo. All of this takes time, hence it takes time much longer than with TRUNCATE

15) Performance (acquired lock) — record lock — reduces performance during execution — each record in the table is locked for deletion

16) DELETE can be used on a table used in transactional replication or merge replication

Понравилась статья? Поделить с друзьями:
  • В каких случаях допускается разработка временных инструкций по охране труда
  • В каких случаях должны досрочно пересматриваться инструкции по охране труда
  • В каких случаях должностная инструкция обязательна
  • В каких пропорциях разводить торнадо от сорняков инструкция по применению
  • В какие сроки эксплуатирующая организация обязана пересматривать инструкции на рабочих местах