After learning how to retrieve data using SELECT statements, the next essential step in SQL Server is to understand how to modify that data efficiently and safely. This lesson covers how to insert, update, and delete records, including methods for optimizing these operations and keeping the data they touch correct in SQL Server 2025.
INSERT, UPDATE, and DELETE statements using literal values.INSERT Example:
INSERT INTO Employees (EmployeeID, FirstName, LastName, Salary)
VALUES (101, 'John', 'Doe', 60000);
UPDATE Example:
UPDATE Employees
SET Salary = 65000
WHERE EmployeeID = 101;
DELETE Example:
DELETE FROM Employees
WHERE EmployeeID = 101;
Tip: Always use parameterized queries within applications to prevent SQL injection attacks and to reuse execution plans efficiently.
The example above assumes EmployeeID is supplied directly. Many tables instead generate their primary key automatically through an IDENTITY column, in which case the column is left out of the INSERT entirely and SQL Server assigns the next value itself:
CREATE TABLE Employees (
EmployeeID INT IDENTITY(1,1) PRIMARY KEY,
FirstName NVARCHAR(50),
LastName NVARCHAR(50),
Salary MONEY
);
INSERT INTO Employees (FirstName, LastName, Salary)
VALUES ('John', 'Doe', 60000);
SELECT SCOPE_IDENTITY() AS NewEmployeeID;
SCOPE_IDENTITY() returns the identity value just generated by that specific statement, in the current scope, which is the safer choice over the older @@IDENTITY function; @@IDENTITY returns the last identity value generated in the current session regardless of scope, so a trigger firing on the inserted table and generating its own identity value elsewhere can silently return the wrong number. A SEQUENCE object is the other common way to generate key values in SQL Server, independent of any one table, useful when several tables need to share a single, centrally generated numbering scheme rather than each maintaining its own identity counter.
Occasionally a migration or a data-load script needs to insert an explicit value into an identity column rather than let SQL Server generate one, restoring a specific set of IDs from a backup, for instance. SET IDENTITY_INSERT allows exactly one table at a time to accept explicit identity values for the duration of the setting:
SET IDENTITY_INSERT Employees ON;
INSERT INTO Employees (EmployeeID, FirstName, LastName, Salary)
VALUES (500, 'Carlos', 'Reyes', 72000);
SET IDENTITY_INSERT Employees OFF;
This is an exception reserved for specific administrative tasks rather than routine application use; leaving it on, or forgetting to turn it off, defeats the purpose of an identity column generating its own consistent, gap-aware sequence of values.
INSERT from Another Table:
INSERT INTO HighEarners (EmployeeID, FirstName, LastName, Salary)
SELECT EmployeeID, FirstName, LastName, Salary
FROM Employees
WHERE Salary > 100000;
UPDATE from Another Table:
UPDATE E
SET E.Salary = B.NewSalary
FROM Employees E
JOIN BonusTable B ON E.EmployeeID = B.EmployeeID;
Tip: Ensure JOIN conditions are properly defined to prevent unintended cross joins and data corruption.
Before running an UPDATE ... FROM statement like the one above against production data, it is worth running the equivalent SELECT first, with the same FROM and JOIN clauses, to see exactly which rows and which new values the update would actually produce:
SELECT E.EmployeeID, E.Salary AS CurrentSalary, B.NewSalary
FROM Employees E
JOIN BonusTable B ON E.EmployeeID = B.EmployeeID;
If that result set looks right, row by row, the UPDATE built from the same join almost certainly is too. This habit catches a mismatched join condition before it silently updates far more, or far fewer, rows than intended, which is a considerably cheaper mistake to catch in a SELECT than to undo after an UPDATE has already committed.
INSERT Using Subquery:
INSERT INTO TopPerformers (EmployeeID, FullName)
SELECT EmployeeID, FirstName + ' ' + LastName
FROM Employees
WHERE EmployeeID IN (
SELECT EmployeeID
FROM Performance
WHERE Rating = 'A'
);
UPDATE Using Subquery:
UPDATE Employees
SET Salary = Salary * 1.10
WHERE DepartmentID = (
SELECT DepartmentID
FROM Departments
WHERE DepartmentName = 'Engineering'
);
DELETE Using Subquery:
DELETE FROM Employees
WHERE EmployeeID IN (
SELECT EmployeeID
FROM Resignations
WHERE ResignDate < GETDATE()
);
Tip: Subqueries must return a single scalar value when used in predicates like =. For multi-row results, use IN or EXISTS instead.
Between IN and EXISTS, the choice is not purely stylistic. EXISTS stops looking the moment it finds one matching row, since it only needs to know whether any row exists at all, which tends to perform better against a large subquery result set where IN would otherwise materialize every matching value first. The DELETE example above, rewritten with a correlated EXISTS subquery instead, expresses the same logic:
DELETE FROM Employees AS E
WHERE EXISTS (
SELECT 1
FROM Resignations AS R
WHERE R.EmployeeID = E.EmployeeID
AND R.ResignDate < GETDATE()
);
For small, well-indexed lookup sets the two forms often perform identically, and the query optimizer frequently rewrites one into the other internally; the difference becomes worth paying attention to mainly as the subquery's underlying row count grows.
MERGE specifically noted below.Example: Deleting Records in Batches
WHILE 1=1
BEGIN
DELETE TOP (1000)
FROM Logs
WHERE LogDate < '2023-01-01';
IF @@ROWCOUNT = 0 BREAK;
END
Batching a large delete this way keeps each individual transaction, and the locks it holds, small and short-lived, rather than one enormous delete holding a table-level lock for the entire operation. Watching the effect directly is straightforward with tools covered in this site's SQL Server monitoring material: querying sys.dm_tran_locks while the loop runs shows a brief lock held per 1000-row batch rather than one long-held lock, and SSMS's Activity Monitor shows the session cycling between running and briefly idle between iterations instead of sitting suspended under a single sustained lock the whole time.
Using MERGE for Complex Logic:
MERGE INTO Employees AS Target
USING NewSalaries AS Source
ON Target.EmployeeID = Source.EmployeeID
WHEN MATCHED THEN
UPDATE SET Target.Salary = Source.NewSalary
WHEN NOT MATCHED THEN
INSERT (EmployeeID, Salary)
VALUES (Source.EmployeeID, Source.NewSalary);
A caution on MERGE: MERGE is a convenient way to express an insert-or-update in one statement, combining what would otherwise be a separate INSERT and UPDATE, but it comes with a documented history of edge-case problems. Microsoft's own documentation for the statement carries a standing caution that its behavior under certain conditions, particularly concurrent modifications against the same rows and interactions with triggers, has in some reported cases not matched what the documentation describes. The practical guidance that follows from this is not to avoid MERGE outright, but to test it thoroughly against concurrent workloads before relying on it in production, to always qualify the ON clause precisely enough that it cannot match more than one source row per target row, and to prefer separate, explicit INSERT and UPDATE statements, wrapped in an explicit transaction, whenever strict concurrency correctness matters more than the convenience of a single statement.
Capturing What Changed with OUTPUT
Any INSERT, UPDATE, DELETE, or MERGE statement can report back the rows it actually affected using the OUTPUT clause, without a separate query afterward:
DELETE FROM Logs
OUTPUT DELETED.LogID, DELETED.LogDate
WHERE LogDate < '2023-01-01';
DELETED refers to the row as it existed before the statement ran; INSERTED refers to the row as it exists after, available in an INSERT or the matched-insert branch of a MERGE. An UPDATE can reference both at once, which is useful for logging exactly what changed:
UPDATE Employees
SET Salary = Salary * 1.10
OUTPUT DELETED.EmployeeID, DELETED.Salary AS OldSalary, INSERTED.Salary AS NewSalary
WHERE DepartmentID = 4;
OUTPUT can also write directly into a table rather than just returning a result set to the caller, through an OUTPUT ... INTO clause, which is a common way to build an audit trail of every row a batch job deleted or updated without adding a separate logging statement after the fact.
Check Execution Performance:
SET STATISTICS IO ON;
SET STATISTICS TIME ON;
Turned on before running a modification statement, these report the logical reads and CPU/elapsed time the statement actually consumed, directly in the Messages tab of SSMS's query results, which is often the fastest way to confirm whether an added index actually reduced the work a batch update has to do, before and after, without needing a full execution plan capture for a quick check.
Constraints ensure data validity during insert, update, and delete operations. SQL Server enforces these rules automatically to prevent invalid data from being stored.
Example: Default Constraint
ALTER TABLE Employees
ADD CONSTRAINT DF_Status DEFAULT 'Active' FOR Status;
INSERT INTO Employees (EmployeeID, FirstName, LastName)
VALUES (102, 'Jane', 'Smith');
-- Status defaults to 'Active'
Example: Check Constraint
ALTER TABLE Employees
ADD CONSTRAINT CK_Salary_Positive CHECK (Salary > 0);
With this constraint in place, any INSERT or UPDATE that would set Salary to zero or a negative value is rejected outright, with an error naming the constraint, before the bad value ever reaches the table. This is worth building directly into the table rather than relying solely on application code to validate the value first, since a constraint is enforced no matter which application, script, or person is doing the modifying, while an application-level check only guards the paths that application actually controls.
Example: Foreign Key Constraint
ALTER TABLE Employees
ADD CONSTRAINT FK_Employees_Department
FOREIGN KEY (DepartmentID) REFERENCES Departments (DepartmentID);
Once this constraint exists, an INSERT or UPDATE that would set Employees.DepartmentID to a value not present in Departments fails before it is stored, and a DELETE against Departments that would orphan existing employee rows fails as well, unless the foreign key was defined with ON DELETE CASCADE or a similar referential action telling SQL Server what to do with the dependent rows instead. Deciding whether a given relationship should cascade, set the foreign key to NULL, or simply block the delete outright is a modeling decision worth making deliberately, table by table, rather than defaulting to cascading delete everywhere out of convenience; a cascade that was never intended can delete far more data than the person running the original statement realized.
A view can also be the target of an INSERT, UPDATE, or DELETE, not just a SELECT, provided it meets a short list of conditions: it must reference exactly one base table (a view joining several tables cannot be modified directly unless an INSTEAD OF trigger is defined to handle the modification explicitly), it cannot use DISTINCT, GROUP BY, or an aggregate function, and the columns being modified must map directly to real columns in that base table rather than to an expression or a computed value.
CREATE VIEW ActiveEmployees AS
SELECT EmployeeID, FirstName, LastName, Salary, Status
FROM Employees
WHERE Status = 'Active';
UPDATE ActiveEmployees
SET Salary = Salary * 1.05
WHERE EmployeeID = 101;
That UPDATE succeeds, and it modifies the underlying Employees row directly through the view. What it does not automatically do is prevent the update from moving that same row out of the view's own definition, for instance by setting Status to something other than 'Active' through this same view, since nothing about the view's definition stops a value from being written that would then no longer satisfy the view's own WHERE clause. Adding WITH CHECK OPTION to the view's definition closes exactly this gap:
ALTER VIEW ActiveEmployees AS
SELECT EmployeeID, FirstName, LastName, Salary, Status
FROM Employees
WHERE Status = 'Active'
WITH CHECK OPTION;
With WITH CHECK OPTION in place, any INSERT or UPDATE issued through ActiveEmployees that would produce a row Status values other than 'Active', a row the view itself would no longer be able to see, is rejected rather than silently allowed to disappear from the view's own results.
A handful of mistakes account for a disproportionate share of data modification incidents, and all of them are avoidable with the same few habits.
The single most common and most damaging mistake is an UPDATE or DELETE run without a WHERE clause at all, or with a WHERE clause that does not actually narrow the statement the way the person running it assumed. SQL Server will not stop DELETE FROM Employees; from deleting every row in the table; there is no confirmation prompt built into the engine itself. The habit introduced earlier in this lesson for cross-table updates, running the equivalent SELECT with the same WHERE clause first and checking the row count it returns, applies just as directly to a single-table UPDATE or DELETE, and costs only a few seconds.
For anything run interactively rather than inside a tested, deployed script, wrapping the statement in an explicit transaction that is not committed until the result has been checked adds a second layer of protection:
BEGIN TRANSACTION;
DELETE FROM Employees
WHERE DepartmentID = 4;
SELECT @@ROWCOUNT AS RowsDeleted;
-- Review RowsDeleted; if it looks right:
COMMIT TRANSACTION;
-- if it does not:
-- ROLLBACK TRANSACTION;
Nothing about this pattern is special to DELETE; the same explicit BEGIN TRANSACTION, check, then COMMIT or ROLLBACK habit works identically for an UPDATE whose scope needs confirming before it becomes permanent. The next lesson covers transactions in full, including TRY/CATCH error handling around them; this is the same mechanism, used here purely as a safety net rather than as the multi-statement coordination tool it is designed for.
Every statement in this lesson runs as its own implicit transaction by default: it either fully commits or fully rolls back on its own, with no explicit BEGIN TRANSACTION needed. The moment a task needs several modification statements to succeed or fail together, an INSERT into one table paired with an UPDATE to a related table, for instance, that guarantee has to be requested explicitly rather than assumed. The next lesson picks this up directly: wrapping multiple statements in an explicit transaction, handling errors with TRY/CATCH so a failure partway through rolls back everything rather than leaving the data half-changed, and the locking behavior that a multi-statement transaction holds for longer than any single statement in this lesson does on its own.
By applying these principles, you can create robust, efficient, and secure modification queries that scale well in SQL Server 2025 environments. The next lesson introduces transactions and advanced multi-table modification techniques.