Truncate Table SQL

Galaxy Glossary

How do you quickly remove all rows from a table in SQL?

The TRUNCATE TABLE statement is used to remove all rows from a table. It's a fast and efficient way to empty a table, but it cannot be undone.
Sign up for the latest in SQL knowledge from the Galaxy Team!
Thank you! Your submission has been received!
Oops! Something went wrong while submitting the form.

Description

The TRUNCATE TABLE statement is a powerful tool for quickly emptying a table. Unlike DELETE, which removes rows one by one, TRUNCATE TABLE removes all rows in a single operation. This makes it significantly faster, especially for large tables. Crucially, TRUNCATE TABLE is a DML (Data Manipulation Language) statement, meaning it modifies the data in the table. However, it's important to remember that TRUNCATE TABLE is irreversible. Any data removed using TRUNCATE TABLE cannot be recovered. This contrasts with the DELETE statement, which can often be rolled back if needed. Think of TRUNCATE TABLE as a hard reset for a table, clearing everything out. It's a useful tool for tasks like preparing a table for new data or cleaning up temporary data. It's also important to note that TRUNCATE TABLE often has implications for indexes and other table-level metadata, which are automatically updated by the database system. This is a key difference from DELETE, which might leave indexes intact until the database system has a chance to update them.

Why Truncate Table SQL is important

TRUNCATE TABLE is crucial for quickly clearing out data, especially in applications where you need to reset a table's contents. Its speed makes it a valuable tool for data preparation and cleanup tasks.

Example Usage


-- Example table
CREATE TABLE Customers (
    CustomerID INT PRIMARY KEY,
    FirstName VARCHAR(50),
    LastName VARCHAR(50)
);

-- Insert some data
INSERT INTO Customers (CustomerID, FirstName, LastName) VALUES
(1, 'John', 'Doe'),
(2, 'Jane', 'Smith'),
(3, 'Peter', 'Jones');

-- Verify the data
SELECT * FROM Customers;

-- Truncate the table
TRUNCATE TABLE Customers;

-- Verify the table is empty
SELECT * FROM Customers;

Common Mistakes

Want to learn about other SQL terms?