Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mysql: Which to use when: drop table, truncate table, delete from table

Tags:

sql

mysql

List the differences between the following MySql commands.

  • drop table tablename;
  • truncate table tablename;
  • delete from tablename where 1;

Also from your experiences please tell me typical usage scenario for each.

like image 942
gameover Avatar asked Jan 06 '10 12:01

gameover


People also ask

What is the difference between DROP TABLE and TRUNCATE table and DELETE table?

The DELETE command deletes one or more existing records from the table in the database. The DROP Command drops the complete table from the database. The TRUNCATE Command deletes all the rows from the existing table, leaving the row with the column names.

When to use TRUNCATE vs 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 data and records only the page deallocations in the transaction log. DELETE command is slower than TRUNCATE command.

Do we need to TRUNCATE table before DROP?

No. TRUNCATE and DROP are almost identical in behavior and speed, so doing a TRUNCATE right before a DROP is simply unnecessary.

Does TRUNCATE table DELETE table?

The truncate command removes all rows of a table. We cannot use a Where clause in this. It is a DDL command. SQL Delete command places lock on each row requires to delete from a table.


2 Answers

  • drop table tablename;
    • After this, it's gone. No more table. No more data.
    • Use this when you don't need that table any more.
  • truncate table tablename;
    • After this, the table is empty, and (importantly) auto-incrementing keys are reset to 1. It's quite literally like having a brand new table.
    • Use this when you just want an empty table. It's faster than DELETE because it simply deletes all data. DELETE will scan the table to generate a count of rows that were affected.
  • delete from tablename;
    • This lets you filter which rows to delete based on an optional WHERE clause.
    • Use this when you want to delete specific records, eg: DELETE FROM tablename WHERE username = 'joe'
like image 69
nickf Avatar answered Sep 28 '22 07:09

nickf


  • Drop is deleting the table. I would drop the table if I didn't need it anymore
  • "Truncate operations drop and re-create the table, which is much faster than deleting rows one by one, particularly for large tables." - from MySQL manual
  • I would use delete to do a delete (of specific rows) with a query.

I rarely "delete" anything from my databases. I generally put a flag column such as deleted as a boolean value. I check for that. If its true, I don't present that data.

like image 27
Daniel A. White Avatar answered Sep 28 '22 07:09

Daniel A. White