Two ways to delete data in MySQL


There are two ways to delete data in MySQL, one is the DELETE statement and the other is the TRUNCATE TABLE statement. The DELETE statement can select the records to be deleted through WHERE. Whereas using TRUNCATE TABLE will delete all records in the table. Therefore, the DELETE statement is more flexible.

  If you want to clear all records in the table, you can use the following two methods:

  DELETE FROM table1
  TRUNCATE TABLE table1

  The TABLE in the second record is optional.

  If you want to delete some records in the table, you can only use the DELETE statement.

  DELETE FROM table1 WHERE ...;

  If DELETE does not add the WHERE clause, then it is the same as TRUNCATE TABLE, but they are different, that is, DELETE can return the number of records deleted, while TRUNCATE TABLE returns 0.

  If there is an auto-increment field in a table, after all records are deleted using TRUNCATE TABLE and DELETE without the WHERE clause, the auto-increment field will restore the starting value to 1. If you don't want to do this, you can add it to the DELETE statement Always true WHERE, such as WHERE 1 or WHERE true.

  DELETE FROM table1 WHERE 1;

  The above statement will scan every record when executed. But it doesn't compare because the WHERE condition is always true. Although this can maintain the maximum value of auto-increment, since it scans all records, its execution cost is much larger than that of DELETE without the WHERE clause.

  The biggest difference between DELETE and TRUNCATE TABLE is that DELETE can select records to delete through the WHERE statement. But it doesn't execute very fast. It can also return the number of records deleted. TRUNCATE TABLE cannot delete the specified records, and cannot return the deleted records. But it executes very fast.

  Unlike standard SQL statements, DELETE supports ORDER BY and LIMIT clauses, through which we can have more control over the records to be deleted. For example, when we only want to delete a part of the records filtered by the WHERE clause, we can use LIMIB. If we want to delete the last few records, we can use ORDER BY and LIMIT together. Suppose we want to delete the first 6 records whose name is equal to "Mike" in the users table. The following DELETE statement can be used:

  DELETE FROM users WHERE name = 'Mike' LIMIT 6;

  Generally, MySQL is not sure which 6 records are deleted. To be more secure, we can use ORDER BY to sort the records.

  DELETE FROM users WHERE name = 'Mike' ORDER BY id DESC LIMIT 6;

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325740519&siteId=291194637