MySQL Tutorial
MySQL Installation and Configuration
MySQL Database Operations
Database Design
MySQL Data Types
MySQL Storage Engines
MySQL Basic Operations of Tables
MySQL Constraints
MySQL Operators
MySQL Function
MySQL Manipulate Table Data
MySQL View
MySQL Indexes
MySQL Stored Procedure
MySQL Trigger
MySQL Transactions
MySQL Character Set
MySQL User Management
MySQL Database Backup and Recovery
MySQL Log
MySQL Performance Optimization
Let's talk about the TRUNCATE
statement in MySQL. The TRUNCATE
statement is a Data Definition Language (DDL) operation that is used to mark the extents of a table for deallocation (removal). The result of this operation quickly removes all data from a table, typically bypassing a number of integrity enforcing mechanisms intended to protect rows of a table.
Here's the basic syntax of TRUNCATE
:
TRUNCATE TABLE table_name;
So, if you have a table named employees
, and you want to delete all data from this table, you would use:
TRUNCATE TABLE employees;
IMPORTANT: Be very careful when using TRUNCATE
, as it will permanently delete all the data in the table. There is no way to undo this operation.
Comparison with DELETE
You might wonder how TRUNCATE
is different from DELETE
. Here are some key differences:
TRUNCATE
is faster than DELETE
, as it doesn't scan every record before removing it. TRUNCATE
just drops the table and recreates it.
You cannot use WHERE
clause with TRUNCATE
. It is all or nothing. With DELETE
, you can choose to delete certain records.
TRUNCATE
resets the identity of the table. If you have an auto-increment column, it will start from 1 after a TRUNCATE
operation. DELETE
does not reset the identity.
TRUNCATE
is a DDL (Data Definition Language) command whereas DELETE
is a DML (Data Manipulation Language) command. Therefore, TRUNCATE
operations drop and recreate the table, which is much faster than deleting rows one by one, particularly for large tables.
NOTE: TRUNCATE cannot be used on a table that has foreign key constraints applied on it. If you try to truncate a table having foreign key constraint, you will receive an error. You can only use the DELETE command for such tables, or drop the constraints, truncate, and then reapply the constraints.
MySQL TRUNCATE Table Example:
TRUNCATE TABLE table_name;
How to Use TRUNCATE in MySQL:
TRUNCATE TABLE employees;
Emptying a Table with TRUNCATE in MySQL:
TRUNCATE TABLE logs;
TRUNCATE vs DELETE in MySQL:
DELETE FROM records;
TRUNCATE TABLE records;
Resetting Auto-increment with TRUNCATE in MySQL:
TRUNCATE TABLE users;
TRUNCATE Table with Foreign Key Constraints in MySQL:
SET foreign_key_checks = 0; TRUNCATE TABLE orders; SET foreign_key_checks = 1;
Examples of Using TRUNCATE in MySQL Queries:
TRUNCATE TABLE customer_feedback;
TRUNCATE TABLE products;