Modifying data safely
DELETE
Remove selected rows from a disposable copy while preserving canonical tables.
Lesson 47 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. Remove selected rows from a disposable copy while preserving canonical tables. Run changing examples only on a disposable training instance. The example uses a session-local object or rolls back its changes.
Run the example
SELECT ProductID, ProductName INTO #PracticeProducts
FROM dbo.Products WHERE ProductID BETWEEN 1 AND 3;
DELETE FROM #PracticeProducts WHERE ProductID = 3;
SELECT ProductID, ProductName FROM #PracticeProducts ORDER BY ProductID;
DROP TABLE #PracticeProducts;Read it step by step
- SELECT INTO creates a session-local temporary copy of three product rows.
- DELETE removes only ProductID 3 from that copy.
- The final SELECT shows the two survivors; dropping the temp table leaves the canonical Products table unchanged.
Check the result
| ProductID | ProductName |
|---|---|
| 1 | Laptop Stand |
| 2 | USB-C Dock |
ProductID 3 still exists in dbo.Products.
Practice
Create the same three-product temp copy, delete ProductID 2, and show the survivors.
Check your answer and expected result
Reveal answer
SELECT ProductID, ProductName INTO #PracticeProducts
FROM dbo.Products WHERE ProductID BETWEEN 1 AND 3;
DELETE FROM #PracticeProducts WHERE ProductID = 2;
SELECT ProductID, ProductName FROM #PracticeProducts ORDER BY ProductID;
DROP TABLE #PracticeProducts;| ProductID | ProductName |
|---|---|
| 1 | Laptop Stand |
| 3 | Webcam |
Products 1 and 3 remain in the temporary copy.
Your progress
Reveal the check answer or reach the end to complete this lesson.