SQL to delete all rows in a table
Code:
DELETE FROM table_name
WHERE 1=1;
Explanation:
The DELETE
statement is used to remove rows from a table in an SQL database. The WHERE
clause is used to specify which rows to delete. In this example, the WHERE
clause is 1=1
, which is always true. This means that all rows in the table_name
table will be deleted.
How to implement effectively:
- Use transactions: If you are deleting a large number of rows, it is a good idea to use a transaction. This will ensure that the deletion is either successful or it is rolled back, preventing any data loss.
- Truncate the table: If you are deleting all the rows in a table, you can use the
TRUNCATE
statement instead of theDELETE
statement. TheTRUNCATE
statement is faster than theDELETE
statement and it does not log the deletion. However, theTRUNCATE
statement cannot be rolled back, so it is important to be sure that you want to delete all the rows in the table before using it.