TRUNCATE statement
The TRUNCATE statement deletes every row of a table. CoraDB first drops the table's indexes and constraints internally, removes the rows and then rebuilds them, so TRUNCATE is much faster than DELETE FROM table_name without a WHERE clause on large tables. It also resets the table's AUTO_INCREMENT counter to its starting value.
Syntax
Section titled “Syntax”TRUNCATE [TABLE] table_name- table_name: the table to empty.
To run TRUNCATE you need the ALTER, INDEX and DELETE permissions on the table (see GRANT).
Example
Section titled “Example”The example uses a scratch table, so it does not change any of the sample data:
CREATE TABLE support_ticket ( id INT AUTO_INCREMENT PRIMARY KEY, customer_id INT NOT NULL, subject VARCHAR(100) NOT NULL, status VARCHAR(10) DEFAULT 'open');INSERT INTO support_ticket (customer_id, subject)VALUES (5, 'Wrong size delivered'), (15, 'Refund request'), (42, 'Damaged parcel');
SELECT id, customer_id, subject FROM support_ticket;| id | customer_id | subject |
|---|---|---|
| 1 | 5 | Wrong size delivered |
| 2 | 15 | Refund request |
| 3 | 42 | Damaged parcel |
After TRUNCATE, numbering starts again from 1:
TRUNCATE TABLE support_ticket;INSERT INTO support_ticket (customer_id, subject) VALUES (7, 'Missing invoice');
SELECT id, customer_id, subject FROM support_ticket;| id | customer_id | subject |
|---|---|---|
| 1 | 7 | Missing invoice |
With DELETE FROM support_ticket the new row would have received id 4.
Foreign keys
Section titled “Foreign keys”If other tables reference the table through a foreign key, TRUNCATE follows the foreign key's ON DELETE action:
RESTRICTorNO ACTION(the default): the statement fails while referencing rows exist.CASCADE: the referencing rows are deleted as well.
CREATE TABLE ticket_note ( id INT AUTO_INCREMENT PRIMARY KEY, ticket_id INT NOT NULL, note VARCHAR(200), FOREIGN KEY (ticket_id) REFERENCES support_ticket (id));INSERT INTO ticket_note (ticket_id, note) VALUES (1, 'Customer sent photos');
TRUNCATE TABLE support_ticket;ERROR: Update/Delete operations are restricted by the foreign key 'fk_ticket_note_ticket_id'.Had the foreign key been declared with ON DELETE CASCADE, the same TRUNCATE would have emptied ticket_note too.
See also
Section titled “See also”- DELETE: remove selected rows
- FOREIGN KEY constraint
- AUTO_INCREMENT