sql truncate

Galaxy Glossary

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

TRUNCATE TABLE is a SQL command used to remove all rows from a table. It's faster than DELETE but doesn't allow for filtering or using a WHERE clause.
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 command is a powerful tool for quickly emptying a table in a SQL database. Unlike the DELETE command, which can be used to remove rows based on specific criteria, TRUNCATE TABLE removes *all* rows from the table. This makes it significantly faster than DELETE, especially for large tables, because it doesn't require processing individual row deletions. It's crucial to understand that TRUNCATE TABLE is a DML (Data Manipulation Language) statement, meaning it directly modifies the data within a table. It's important to note that TRUNCATE TABLE is a DML statement that permanently removes all rows from a table. This operation cannot be undone unless you have a backup or use a transaction that can be rolled back. It's also important to remember that TRUNCATE TABLE does not return any rows or information about the rows that were deleted. This is a key difference from DELETE, which often returns a count of the rows deleted.

Why sql truncate is important

TRUNCATE TABLE is essential for quickly clearing a table's contents, especially when preparing for large-scale data loads or maintenance tasks. Its speed advantage over DELETE makes it a valuable tool for database administrators and developers.

Example Usage

```sql -- Create a sample 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 data again (should be empty) SELECT * FROM Customers; ```

Common Mistakes

Want to learn about other SQL terms?