Tables and integrity
DROP TABLE versus TRUNCATE TABLE
Distinguish removing rows from removing the table definition.
Lesson 55 of 84
Reading: about 2 min
Lesson + practice: about 15 min
Difficulty: Intermediate
On this page4 sections
This lesson uses DDI_SQL_Training dataset v1.0.0 on SQL Server 2019 or later. Distinguish removing rows from removing the table definition. Run changing examples only on a disposable training instance. The example uses a session-local object or rolls back its changes.
Run the example
CREATE TABLE #Scratch (ID int NOT NULL PRIMARY KEY);
INSERT INTO #Scratch VALUES (1), (2);
TRUNCATE TABLE #Scratch;
SELECT COUNT(*) AS RowsAfterTruncate FROM #Scratch;
DROP TABLE #Scratch;Read it step by step
- TRUNCATE removes all rows from the temp table while preserving its definition.
- COUNT(*) can still query the empty table.
- DROP TABLE then removes the table definition too.
Check the result
| RowsAfterTruncate |
|---|
| 0 |
The canonical dataset is unaffected.
Practice
Create and drop a temp table, then check that OBJECT_ID reports it absent.
Check your answer and expected result
Reveal answer
CREATE TABLE #Scratch (ID int NOT NULL);
DROP TABLE #Scratch;
SELECT CASE WHEN OBJECT_ID(N'tempdb..#Scratch') IS NULL
THEN 1 ELSE 0 END AS WasDropped;| WasDropped |
|---|
| 1 |
WasDropped is 1 because the temp table definition no longer exists.
Your progress
Reveal the check answer or reach the end to complete this lesson.