Until now you only read data. Changing it is more powerful and more dangerous: one statement without a WHERE clause can damage a whole table. This guide shows how to INSERT, UPDATE and DELETE rows, how the three ways of removing data differ, and how transactions let you undo mistakes.
Part of the SQL Server for Beginners series. This article is the written version of lesson 4 of the Bigland Network video course, with the same sample data. The results shown were worked out by hand from that data, so run every example on a test database, not on production data.
Watch lesson 4 as a video or open it on YouTube. The written lesson below follows the same steps and the same sample data.
Contents
- 1. INSERT
- 2. UPDATE
- 3. DELETE, TRUNCATE, DROP
- 4. Transactions
- 5. Mistakes and best practices
- 6. Practice
1. INSERT: add rows
Use the sample tables from Lesson 2: JOINs. Employees.Id is an IDENTITY column, so SQL Server generates it. Always list the column names:
INSERT INTO Employees (FirstName, DeptId, Salary)
VALUES ('Hassan', 2, 4500);
Hassan receives Id 7. Several rows can go in one statement, which is shorter and faster than separate statements:
INSERT INTO Employees (FirstName, DeptId, Salary)
VALUES ('Lina', 1, 3800),
('Reda', 3, 3300);
Lina and Reda get Ids 8 and 9. You can also insert the result of a SELECT, which is a quick way to back up rows before a big change:
CREATE TABLE EmployeesBackup (Id INT, FirstName VARCHAR(50), DeptId INT, Salary INT);
INSERT INTO EmployeesBackup (Id, FirstName, DeptId, Salary)
SELECT Id, FirstName, DeptId, Salary
FROM Employees
WHERE DeptId = 3;
2. UPDATE: change rows
UPDATE Employees
SET Salary = 4600
WHERE FirstName = 'Hassan';
Separate several assignments with commas. The WHERE clause decides which rows change.
Danger: without
WHERE,UPDATE Employees SET Salary = 0;changes every row (all nine). There is no confirmation and no undo button outside a transaction. Check theWHEREclause every time.
The new value can use the old one. A ten percent raise for Sales (department 1) takes Amina from 4200 to 4620, Salma from 3600 to 3960 and Lina from 3800 to 4180:
UPDATE Employees
SET Salary = Salary * 1.10
WHERE DeptId = 1;
To change rows defined by another table, use UPDATE ... FROM ... JOIN. A raise of 200 for the IT department:
UPDATE e
SET e.Salary = e.Salary + 200
FROM Employees e
INNER JOIN Departments d ON e.DeptId = d.DeptId
WHERE d.DeptName = 'IT';
A habit that saves you: SELECT first
Before an UPDATE or DELETE, run a SELECT with the same WHERE. You see exactly which rows will be affected, then change only the first line:
SELECT *
FROM Employees
WHERE DeptId IS NULL; -- only Omar matches
3. DELETE, TRUNCATE and DROP
DELETE FROM Employees
WHERE Id = 9; -- removes Reda
DELETE FROM Employees
WHERE DeptId IS NULL; -- removes Omar (use IS NULL, not = NULL)
After these statements seven rows remain. Without WHERE, DELETE removes every row but keeps the table.
| Command | What it does |
|---|---|
| DELETE | Removes the rows you choose with WHERE. Logged row by row. Table stays. |
| TRUNCATE TABLE | Removes all rows very quickly, no WHERE, resets the identity counter. |
| DROP TABLE | Removes the whole table, including its structure. |
4. Transactions: COMMIT and ROLLBACK
A transaction groups statements into one unit that either completely succeeds or completely fails. BEGIN TRANSACTION starts it, COMMIT saves it and ROLLBACK undoes everything since the BEGIN. The classic example is a bank transfer. Create a small table first:
CREATE TABLE Accounts (Id INT PRIMARY KEY, Owner VARCHAR(50), Balance DECIMAL(10,2));
INSERT INTO Accounts VALUES (1,'Amina',1000),(2,'Youssef',500);
BEGIN TRANSACTION;
UPDATE Accounts SET Balance = Balance - 200 WHERE Id = 1;
UPDATE Accounts SET Balance = Balance + 200 WHERE Id = 2;
COMMIT;
| Owner | Balance |
|---|---|
| Amina | 800.00 |
| Youssef | 700.00 |
If anything failed between the two updates and you rolled back, both balances would stay as they were.
Testing a dangerous command
BEGIN TRANSACTION;
DELETE FROM Employees;
SELECT COUNT(*) AS Remaining FROM Employees; -- 0
ROLLBACK;
SELECT COUNT(*) AS Remaining FROM Employees; -- 7 again
Always end a transaction with COMMIT or ROLLBACK: an open transaction keeps rows locked and blocks other users (see How to Find and Fix Blocking in SQL Server).
TRY…CATCH
BEGIN TRY
BEGIN TRANSACTION;
UPDATE Accounts SET Balance = Balance - 200 WHERE Id = 1;
UPDATE Accounts SET Balance = Balance + 200 WHERE Id = 2;
COMMIT;
END TRY
BEGIN CATCH
IF @@TRANCOUNT > 0 ROLLBACK;
THROW;
END CATCH;
If any statement raises an error, execution jumps to CATCH, the transaction is rolled back and THROW reports the error, so a script never leaves half of its changes behind.
5. Common mistakes and best practices
UPDATEorDELETEwithoutWHERE.- Forgetting
COMMITorROLLBACK, which leaves locks open. - Values in a different order than the column list. Always list the columns.
- Inserting NULL into a required column, or a department Id that does not exist (constraint and foreign key errors, see Lesson 5: CREATE TABLE, Data Types and Constraints).
- Best practice: SELECT first, test inside a transaction, take a backup before large changes (How to Back Up and Restore a SQL Server Database with T-SQL) and use TRY…CATCH in scripts.
6. Practice (on a test database)
- Insert an employee named Sara in Finance (department 4) with a salary of 4000.
- Give every HR employee a raise of 300.
- Inside a transaction, delete employees who earn less than 3500, check the result, then roll back.
Answers: (1) INSERT INTO Employees (FirstName, DeptId, Salary) VALUES ('Sara', 4, 4000); The new Id is 10, not 9, because identity numbers are never reused. (2) UPDATE Employees SET Salary = Salary + 300 WHERE DeptId = 3; Karim goes from 3100 to 3400. (3) BEGIN TRANSACTION; DELETE FROM Employees WHERE Salary < 3500; SELECT * FROM Employees; ROLLBACK; only Karim is removed, and the rollback brings him back.
Frequently asked questions
Can I undo a DELETE after it ran?
Only if it ran inside a transaction that you have not committed yet (use ROLLBACK), or by restoring from a backup. Otherwise the rows are gone.
Is TRUNCATE faster than DELETE?
Yes for emptying a whole table, because it does not log each row. It cannot use WHERE and it resets the identity counter.
Why did my identity number skip a value?
Identity values are never reused, even after a delete or a rolled-back insert.
What to learn next
Next, build your own tables with data types and constraints in Lesson 5: CREATE TABLE, Data Types and Constraints. Previous lesson: Lesson 3: GROUP BY, HAVING and Subqueries.
The whole series
- Lesson 1: SELECT, WHERE and ORDER BY
- Lesson 2: JOINs
- Lesson 3: GROUP BY, HAVING and Subqueries
- Lesson 4: INSERT, UPDATE, DELETE and Transactions (this article)
- Lesson 5: CREATE TABLE, Data Types and Constraints
- Lesson 6: Indexes, Views and Stored Procedures
- Lesson 7: CTEs and Window Functions
- Lesson 8: Built-in Functions
- Lesson 9: Functions, Temp Tables and Table Variables
- Lesson 10: Triggers and Audit Tables
- Lesson 11: Security: Logins, Users and Roles
- Lesson 12: Backup, Restore and Recovery Models
- Lesson 13: Query Performance Tuning
- Lesson 14: SQL Server Agent Jobs and Maintenance
- Lesson 15: Encryption and Auditing Basics
- Lesson 16: Working with JSON
- Lesson 17: Temporal Tables and Row History
- Lesson 18: Partitioning and Large Tables
- lesson 19: Full Text Search
- lesson 20: Query Store and Slow Queries
Sources and further reading
- Microsoft Learn, Transact-SQL reference (Database Engine), on learn.microsoft.com: the official syntax for every statement used here.
- Microsoft Learn, SQL Server documentation, for SQL Server Management Studio (SSMS) and the sample concepts.
More tutorials like this
Msg 208 Invalid Object Name in SQL Server: Causes and Fix
Fix SQL Server Msg 208 Invalid object name: check the spelling, the database and the schema, with real SSMS examples and scripts to find…
SQL Server Query Store Tutorial: Find Slow Queries, Compare Plans and Force a Plan
Turn on Query Store, find the most expensive queries with the sys.query_store views and the SSMS reports, compare the plans of one query and…
SQL Server Full Text Search Tutorial: CONTAINS, FORMSOF and CONTAINSTABLE
Search words inside text columns fast: create a full text catalog and index, use CONTAINS, word forms, phrases and rank the best matches with…
