Database Management
- How to Add an Index
- How to Create a Table
- How to Delete a Table
- How to Rename a Table
- How to Truncate a Table
- How to Duplicate a Table
- How to Add a Column
- How to Remove a Column
- How to Change a Column Name
- How to Set a Column with Default Value
- How to Remove a Default Value to a Column
- How to Add a Not Null Constraint
- How to Remove a Not Null Constraint
- How to Drop an Index
- How to Create a View
- How to Drop a View
- How to Alter Sequence
Dates and Times
Analysis
- How to Use Coalesce
- How to Calculate Percentiles
- How to Get the First Row per Group
- How to Avoid Gaps in Data
- How to Do Type Casting
- How to Write a Common Table Expression
- How to Import a CSV
- How to Compare Two Values When One is Null
- How to Write a Case Statement
- How to Query a JSON Column
- How to Have Multiple Counts
- How to Calculate Cumulative Sum-Running Total
How to Truncate a Table in MySQL
Truncating a table is a fast and efficient way to delete all the records in a table without removing the table itself. The TRUNCATE TABLE
statement in MySQL is often preferred over the DELETE
statement when you want to remove all rows from a table, as it doesn't generate individual row delete operations, making it faster for large datasets.
Syntax
TRUNCATE TABLE table_name;
The TRUNCATE TABLE
statement is used to remove all rows from a table quickly and reset any auto-increment counters to zero. This action is irreversible, so be cautious when using it.
Steps to Truncate a Table
- Open your MySQL command-line client or any MySQL interface you prefer.
- Select the database that contains the table you want to truncate using the command:
- Execute the truncate statement to remove all rows from the table:
- Check if the table is empty:
USE database_name;
TRUNCATE TABLE your_table_name;
SELECT * FROM your_table_name;
Considerations
- Speed: Truncating a table is faster than deleting rows one by one using the
DELETE
statement. - Auto-Increment: The
TRUNCATE
command resets the auto-increment counter for the table, which might not be the case withDELETE
. - Locks: Unlike
DELETE
, which can be rolled back,TRUNCATE
is a DDL command and can't be rolled back if used outside of a transaction. - Triggers: Truncating a table does not activate any DELETE triggers that may be set up on the table.
Example
Suppose we have a table named employees
. If we want to remove all records from this table, we can simply execute:
TRUNCATE TABLE employees;
After executing this command, the table will be empty, and the auto-increment counter will be reset to zero.