MSDN Documentation

Updating and Deleting Data in SQL Server

This tutorial will guide you through the essential SQL Server commands for modifying and removing data from your tables: UPDATE and DELETE. Mastering these operations is crucial for maintaining the integrity and accuracy of your database.

1. Updating Data with the UPDATE Statement

The UPDATE statement is used to modify existing records in a table. You can update one or more columns in one or more rows.

Basic Syntax


UPDATE table_name
SET column1 = value1, column2 = value2, ...
WHERE condition;
            

Example: Updating a Single Row

Let's say you have a Products table and you need to update the price of a specific product.


-- Assuming you want to update the price of the product with ProductID 101
UPDATE Products
SET UnitPrice = 25.50
WHERE ProductID = 101;
            

Example: Updating Multiple Columns in Multiple Rows

You can update multiple columns at once. For instance, if you want to increase the stock quantity for all products manufactured by 'Acme Corp' and also set their Discontinued status to 0.


UPDATE Products
SET UnitsInStock = UnitsInStock + 10, Discontinued = 0
WHERE Manufacturer = 'Acme Corp';
            
Caution: Always test your UPDATE statements on a development or staging environment before running them on production data. Omitting the WHERE clause will update every single row in the table, which can be disastrous.

2. Deleting Data with the DELETE Statement

The DELETE statement is used to remove one or more rows from a table.

Basic Syntax


DELETE FROM table_name
WHERE condition;
            

Example: Deleting a Single Row

To remove a specific customer from the Customers table.


-- Assuming you want to delete the customer with CustomerID 50
DELETE FROM Customers
WHERE CustomerID = 50;
            

Example: Deleting Multiple Rows Based on a Condition

Imagine you want to remove all orders that were placed before a certain date.


-- Delete all orders placed before January 1st, 2022
DELETE FROM Orders
WHERE OrderDate < '2022-01-01';
            
Important: The DELETE statement removes rows permanently. Once deleted, data cannot be easily recovered without backups. Consider using TRUNCATE TABLE if you need to remove all rows quickly, but be aware that TRUNCATE is logged differently and has different implications than DELETE.

TRUNCATE TABLE vs. DELETE

Use TRUNCATE when you want to remove all data from a table and reset it to an empty state, and you are certain you don't need to recover the data or apply specific conditions.


-- Removes all rows from the LogEntries table very efficiently
TRUNCATE TABLE LogEntries;
            

Conclusion

The UPDATE and DELETE statements are fundamental to database management. Always exercise caution when using them, especially without a precise WHERE clause. Regularly backing up your database is essential for data recovery in case of accidental data loss.