SQL Server Point-in-Time Restore with STOPAT

A DELETE with no WHERE clause runs at 14:28, the mistake is noticed at 14:45, and the last scheduled backup is hours old. Restoring that backup alone throws away everything committed in between. RESTORE LOG ... WITH STOPAT replays the transaction log only up to a chosen time, and the script below lists the backups in msdb that the restore needs, runs the restore sequence and checks the result.

Purpose and Overview

Data loss rarely lands on a backup boundary. Accidental deletes, bad deployments and runaway updates happen between backups, so recovery has to stop at a moment of your choosing instead of at the end of a backup file.

A point-in-time restore needs a full database backup whose endpoint is earlier than the target time, optionally the last differential backup, and then every transaction log backup that follows, up to and including the one that contains the target time. The time itself is always applied from a log backup. The recovery point is the latest transaction commit at or before the time you give, not necessarily the exact second you typed.

The script has three steps. Step 1 queries msdb.dbo.backupset and msdb.dbo.backupmediafamily for the full, differential and log backups. Step 2 restores them with NORECOVERY and finishes with RECOVERY and STOPAT. Step 3 checks sys.databases. Point-in-time restore applies to databases in the full or bulk-logged recovery model.

Code Breakdown

The full script is below, followed by a walk through each block. Two changes were made to the original: the comments on the differential and log queries now say what those queries really filter on, and the first log restore now carries the same STOPAT clause as the final one.

 1-- =============================================
 2-- Step 1: Find the correct backup chain in msdb
 3-- for the target database and recovery time
 4-- =============================================
 5DECLARE @DatabaseName   SYSNAME  = N'YourDatabaseName';
 6DECLARE @TargetDateTime DATETIME = '2026-04-10 14:30:00'; -- Set your target recovery time
 7
 8-- Find the last Full backup that finished on or before the target time
 9SELECT TOP 1
10    'Full' AS backup_type,
11    bs.backup_start_date,
12    bs.backup_finish_date,
13    bs.first_lsn,
14    bs.last_lsn,
15    bmf.physical_device_name AS backup_file
16FROM msdb.dbo.backupset bs
17JOIN msdb.dbo.backupmediafamily bmf ON bs.media_set_id = bmf.media_set_id
18WHERE bs.database_name = @DatabaseName
19  AND bs.type = 'D'
20  AND bs.backup_finish_date <= @TargetDateTime
21ORDER BY bs.backup_finish_date DESC;
22
23-- Find the most recent Differential backup that finished on or before the target time.
24-- This query does not check which Full backup the differential is based on.
25SELECT TOP 1
26    'Differential' AS backup_type,
27    bs.backup_start_date,
28    bs.backup_finish_date,
29    bs.first_lsn,
30    bs.last_lsn,
31    bmf.physical_device_name AS backup_file
32FROM msdb.dbo.backupset bs
33JOIN msdb.dbo.backupmediafamily bmf ON bs.media_set_id = bmf.media_set_id
34WHERE bs.database_name = @DatabaseName
35  AND bs.type = 'I'
36  AND bs.backup_finish_date <= @TargetDateTime
37ORDER BY bs.backup_finish_date DESC;
38
39-- List Log backups that started on or before the target time, oldest first.
40-- The list reaches back before the Full backup; use only the ones that follow the
41-- backup you restore, through the log backup that contains the target time.
42SELECT
43    'Log' AS backup_type,
44    bs.backup_start_date,
45    bs.backup_finish_date,
46    bs.first_lsn,
47    bs.last_lsn,
48    bmf.physical_device_name AS backup_file
49FROM msdb.dbo.backupset bs
50JOIN msdb.dbo.backupmediafamily bmf ON bs.media_set_id = bmf.media_set_id
51WHERE bs.database_name = @DatabaseName
52  AND bs.type = 'L'
53  AND bs.backup_start_date <= @TargetDateTime
54ORDER BY bs.backup_start_date ASC;
55
56-- =============================================
57-- Step 2: Execute the point-in-time restore
58-- Replace file paths from the query results above.
59-- The database name and the STOPAT time are typed again here,
60-- so change them in every RESTORE statement as well as in Step 1.
61-- =============================================
62
63-- Restore Full backup with NORECOVERY
64RESTORE DATABASE [YourDatabaseName]
65FROM DISK = N'C:\Backups\YourDatabaseName_Full.bak'
66WITH NORECOVERY, STATS = 10;
67
68-- Restore Differential backup with NORECOVERY (if applicable)
69RESTORE DATABASE [YourDatabaseName]
70FROM DISK = N'C:\Backups\YourDatabaseName_Diff.bak'
71WITH NORECOVERY, STATS = 10;
72
73-- Apply log backups in order, using NORECOVERY until the last one
74RESTORE LOG [YourDatabaseName]
75FROM DISK = N'C:\Backups\YourDatabaseName_Log1.bak'
76WITH NORECOVERY, STOPAT = '2026-04-10 14:30:00';
77
78-- Final log: use STOPAT to recover to the target point in time
79RESTORE LOG [YourDatabaseName]
80FROM DISK = N'C:\Backups\YourDatabaseName_LogFinal.bak'
81WITH RECOVERY, STOPAT = '2026-04-10 14:30:00';
82
83-- =============================================
84-- Step 3: Verify the database is online
85-- =============================================
86SELECT name, state_desc, recovery_model_desc
87FROM sys.databases
88WHERE name = N'YourDatabaseName';

Step 1 Variables

@DatabaseName and @TargetDateTime drive the three discovery queries, so you change the database and the time once for the listing. They are not used in Step 2. The RESTORE statements hard-code the database name and the STOPAT literal, so the target time has to be edited there too. The RESTORE syntax accepts a @datetime_var for STOPAT, but the script keeps the literal so each statement can be read on its own.

Finding the Full Backup

The first SELECT TOP 1 filters msdb.dbo.backupset for type 'D' (Database) backups that finished on or before the target time, newest first. Microsoft defines type as D for a full database backup, I for a differential and L for a log backup. The result gives you physical_device_name and the first_lsn and last_lsn values. The query does not look at the is_copy_only column or at the recovery model, so check both before relying on the row.

Finding the Differential Backup

Type 'I' identifies differential backups. The query is the same shape as the full-backup query, and nothing in it ties the differential to the full backup it returned. It can return a differential based on an older full backup. The backupset table has a differential_base_lsn column for the base of a differential, and database_backup_lsn holds the checkpoint LSN of the full backup it is based on. Add those columns to the SELECT and compare them with the full backup's checkpoint_lsn before you restore the differential. If no differential matches, skip that step and go straight to the log backups.

Finding the Log Backups

The log query does not use TOP 1. It returns every log backup in msdb history for the database that started on or before the target time, oldest first, including those taken before the full backup you chose. You do not apply all of them. Microsoft's procedure is to restore the full backup, then the differential if any, then each log backup created after that, in the order they were created, up to and including the log backup that contains the target time. If a log backup in that chain is lost or damaged, you can restore only the log backups before the missing one.

Restoring Full and Differential with NORECOVERY

NORECOVERY leaves the database non-operational and does not roll back uncommitted transactions, so further backups can be applied. STATS = 10 reports the percentage complete at about every 10 percent, and the reported figure may be a little past the threshold. Never use RECOVERY on an intermediate step.

Applying Log Backups with STOPAT

Microsoft's guidance is that every RESTORE LOG statement in the sequence carries the same STOPAT clause, so the restore does not run past the target. That is why the first log restore above has STOPAT as well as NORECOVERY. Specifying STOPAT on RESTORE DATABASE is optional and raises an error if a data backup is too recent for the target time.

The Final Log Restore

The last statement uses WITH RECOVERY, STOPAT. RECOVERY brings the database online and rolls back uncommitted transactions. Once recovery has run, no more log backups can be applied. If the STOPAT time is after the end of the last log backup, SQL Server leaves the database unrecovered, as if NORECOVERY had been used, and raises a warning.

Verification Query

The sys.databases query shows state_desc and recovery_model_desc. If state_desc is RESTORING, the database was not recovered. One documented cause is a STOPAT time beyond the last log backup applied. Read the restore output before you decide what to do next.

Key Benefits and Use Cases

  • Undoing accidental data changes — recover to the minute before a DELETE or UPDATE ran without losing everything committed earlier.
  • Post-deployment rollback — return to the moment before a schema migration started instead of the last scheduled backup.
  • Finding an unknown recovery point — Microsoft suggests STANDBY for locating an unknown point in time, since it leaves the database read-only between restores.
  • Documented restore plan — the Step 1 listing gives a written list of files and times to attach to an incident ticket.
  • Works from msdb history — no need to open each backup file to see what exists.

Performance Considerations

  • Restore time follows the work involved: the full backup, any differential and each log backup in the chain are applied in turn, so a longer chain means more restore steps.
  • Recovery points are limited by log backups: STOPAT can only land in time covered by log backups. If the time is after the last log backup, the database stays unrecovered.
  • Bulk-logged recovery model: if a log backup contains bulk-logged changes, point-in-time recovery to a point inside that backup is not possible. The database must be recovered to the end of that log backup.
  • Tail-log backup for an online database: take a tail-log backup before restoring over it. For an online database you must use WITH NORECOVERY on the BACKUP LOG statement to avoid an error.
  • History is only in msdb: a backup taken on another server will not appear in this server's msdb history.

Practical Tips

  • Check the files before you start — run the Step 1 queries first and confirm each path exists. A missing file found mid-restore means starting the sequence over.
  • Compare LSNs for the differential — add differential_base_lsn and database_backup_lsn to the differential query and match them to the full backup's checkpoint_lsn.
  • Let SSMS pick the plan if you prefer — choosing a specific date and time on the Timeline dialog makes the Database Recovery Advisor select the backups needed for that point.
  • Restore a copy first — MOVE restores a logical file to a path you choose, which keeps a verification copy apart from the original's files.
  • SQL Server 2022 and later — backupset.last_valid_restore_time helps find the last log backup to restore when STOPAT is used.
  • Without msdb history — RESTORE HEADERONLY returns the backup header information for the backup sets on a device, and sp_delete_backuphistory is the procedure that removes history rows.
  • Rehearse the restore — run the sequence on a non-production server so the first run is not during an incident.

Conclusion

A point-in-time restore is a chain: a full backup, the differential if there is one, and the log backups in order, each carrying the same STOPAT. The msdb queries list the candidates, but the chain still has to be checked by you. The differential's base and the log backups that follow the restored backup are not selected by the queries as written.

References

Posts in this series