Deals Of The Week - hours only!Up to 80% off on all courses and bundles.-Close
Introduction
Automatically-created indexes
SQL index best practices
10. Deleting all data from tables
Summary

Instruction

Perfect! Finally, let's discuss how we can quickly delete all data from a table with indexes. You may be tempted to use the following:

DELETE FROM passenger_count;

The statement above will delete all data from the table passenger_count without deleting the actual table or the indexes. However, it'll be quite slow – the database engine will delete the rows one by one, and it'll have to update the indexes each time. Instead, we can use the following:

TRUNCATE TABLE passenger_count;

Just like DELETE FROM, the statement above will delete all data from the table passenger_count and keep the table structure and indexes up to date. However, it'll be much faster, as all rows will be deleted at once and the indexes will become empty.

TRUNCATE TABLE is much faster than DELETE FROM, but it has its limitations: You can't use a WHERE clause with TRUNCATE TABLE, and in most databases it won't work if you have foreign keys in your table.

Exercise

The company that asked us for help with their database went bankrupt! What a pity!

Delete all data from the table invoice. Use the quick method we've shown you.

Stuck? Here's a hint!

Use a TRUNCATE keyword.