Back to all posts

What is the difference between DELETE and TRUNCATE statements in SQL?

--What is the difference between DELETE and TRUNCATE statements in SQL? --DELETE and TRUNCATE are both SQL commands that can be used to remove data from a …

SQL
--What is the difference between DELETE and TRUNCATE statements in SQL?
--DELETE and TRUNCATE are both SQL commands that can be used to remove data from a table

--DELETE command is used to remove rows from a table based on a specific condition. 
--It can remove one or more rows, 
--but it is slower than the TRUNCATE command as it keeps track of the transaction log.

--TRUNCATE command, removes all rows from a table, 
--effectively resetting the table to its initial state. 
--It is faster than the DELETE command.

--Transaction log: When you DELETE data from a table, the data is logged in the transaction log.

CREATE TABLE #DUMMY1 (
    id INT IDENTITY(1,1) PRIMARY KEY,
    name VARCHAR(50),
    email VARCHAR(50)
);

INSERT INTO #DUMMY1 (name, email)
VALUES ( 'John Doe', 'john.doe@example.com'),
       ( 'Jane Doe', 'jane.doe@example.com'),
       ( 'Bob Smith', 'bob.smith@example.com');
SELECT * FROM #DUMMY1
DELETE FROM #DUMMY1
INSERT INTO #DUMMY1 ( name, email)
VALUES ( 'John Doe', 'john.doe@example.com'),
       ( 'Jane Doe', 'jane.doe@example.com'),
       ( 'Bob Smith', 'bob.smith@example.com');

SELECT * FROM #DUMMY1

CREATE TABLE #DUMMY2 (
    id INT IDENTITY(1,1) PRIMARY KEY,
    name VARCHAR(50),
    email VARCHAR(50)
);

INSERT INTO #DUMMY2 ( name, email)
VALUES ( 'John Doe', 'john.doe@example.com'),
       ( 'Jane Doe', 'jane.doe@example.com'),
       ('Bob Smith', 'bob.smith@example.com');

SELECT * FROM #DUMMY2
TRUNCATE TABLE #DUMMY2

INSERT INTO #DUMMY2 ( name, email)
VALUES ('John Doe', 'john.doe@example.com'),
       ( 'Jane Doe', 'jane.doe@example.com'),
       ( 'Bob Smith', 'bob.smith@example.com');

select * from #DUMMY2

DROP TABLE #DUMMY1
DROP TABLE #DUMMY2

Keep building your data skillset

Explore more SQL, Python, analytics, and engineering tutorials.