When an application must copy changes from a primary SQL Server database to another system, the first solution is often a trigger, a last-modified column, or a custom audit table. These approaches can work in a small application, but they become difficult to maintain when deleted rows must be detected, failed synchronization must be retried, and retention rules must be enforced.
SQL Server provides two built-in features for this problem: Change Tracking and Change Data Capture (CDC). They are related but not interchangeable. Change Tracking answers the question “which rows changed?” with relatively small metadata. CDC records insert, update, and delete activity with captured column values, making it more suitable for detailed data pipelines.
Start with the synchronization requirement
The key design question is whether the consumer needs only the identity of changed rows or also the old and new values involved in each operation.
- Change Tracking: Useful for mobile synchronization, cache invalidation, search-index refreshes, and applications that can read the latest row from the source table.
- CDC: Useful for incremental data-warehouse loads, integration pipelines, audit-oriented processing, and consumers that need the details of each data change.
Change Tracking stores the primary key of affected rows together with change metadata. The consumer normally joins those keys back to the source table to obtain current values. CDC stores captured column values in change tables and exposes log sequence number metadata for ordering and range-based consumption.
How Change Tracking works
Change Tracking is enabled at the database level and then for each table that should be tracked. This example keeps change metadata for seven days:
ALTER DATABASE SalesDb
SET CHANGE_TRACKING = ON
(
CHANGE_RETENTION = 7 DAYS,
AUTO_CLEANUP = ON
);
GO
USE SalesDb;
GO
ALTER TABLE dbo.Customer
ENABLE CHANGE_TRACKING
WITH (TRACK_COLUMNS_UPDATED = ON);
GOChange Tracking does not add triggers to the source table or require application-managed tracking columns. The engine maintains the tracking information internally, and applications read it with CHANGETABLE.
A synchronization process should persist a successful checkpoint. The following query reads changes after a previously stored version:
DECLARE @last_sync_version bigint = 1250;
DECLARE @current_version bigint = CHANGE_TRACKING_CURRENT_VERSION();
SELECT
ct.SYS_CHANGE_VERSION,
ct.SYS_CHANGE_OPERATION,
ct.CustomerId,
c.CustomerName,
c.EmailAddress
FROM CHANGETABLE(CHANGES dbo.Customer, @last_sync_version) AS ct
LEFT JOIN dbo.Customer AS c
ON c.CustomerId = ct.CustomerId;
SELECT @current_version AS next_sync_version;The change operation identifies whether the row was inserted, updated, or deleted. The LEFT JOIN matters because a deleted row no longer exists in the source table. Only after the destination has been updated successfully should the application save the next synchronization version.
The retention-period trap
Change Tracking metadata is removed after the configured retention period. If a consumer is offline longer than that interval, its saved version may no longer be valid. Check the minimum valid version before processing:
DECLARE @last_sync_version bigint = 1250;
SELECT CHANGE_TRACKING_MIN_VALID_VERSION
(
OBJECT_ID(N'dbo.Customer')
) AS min_valid_version;If the saved version is lower than the minimum valid version, do not guess which changes were missed. Perform a full reload or run a deliberate re-synchronization workflow. Continuing with an invalid checkpoint can create silent data loss.
When CDC is the better choice
CDC reads committed DML activity and places it in change tables. The records include metadata such as the commit LSN, sequence information, and operation type. An update can appear as a before-image row and an after-image row, allowing downstream processing to understand the transition.
CDC is enabled first for the database and then for the source table:
USE SalesDb;
GO
EXEC sys.sp_cdc_enable_db;
GO
EXEC sys.sp_cdc_enable_table
@source_schema = N'dbo',
@source_name = N'Customer',
@role_name = NULL,
@supports_net_changes = 1;
GOThe capture instance name is commonly based on the source schema and table, but it should be verified with sys.sp_cdc_help_change_data_capture. A typical query over the generated change function looks like this:
DECLARE @from_lsn binary(10) = sys.fn_cdc_get_min_lsn(N'dbo_Customer');
DECLARE @to_lsn binary(10) = sys.fn_cdc_get_max_lsn();
SELECT
__$start_lsn,
__$seqval,
__$operation,
CustomerId,
CustomerName,
EmailAddress
FROM cdc.fn_cdc_get_all_changes_dbo_Customer
(
@from_lsn,
@to_lsn,
N'all'
)
ORDER BY __$start_lsn, __$seqval;In a CDC change table, operation code 1 normally represents delete, 2 insert, 3 update before-image, and 4 update after-image. The integration process should persist the final successfully processed LSN range and use it as the starting point for the next batch.
Change Tracking and CDC compared
| Criterion | Change Tracking | CDC |
|---|---|---|
| Stored information | Changed row key and metadata | Captured column values and metadata |
| Typical use | Synchronization and cache refresh | ETL, warehousing, and detailed integration |
| Old and new values | Read separately from the source table | Available in the change table for captured columns |
| Operational overhead | Usually lighter | Capture and cleanup jobs require monitoring |
| Primary failure mode | Expired retention requires a reload | Delayed cleanup can increase change-table storage |
A reliable synchronization workflow
- Persist a checkpoint. Store the last successful Change Tracking version or CDC LSN range in durable application storage.
- Advance it only after success. Do not mark a batch complete before all destination writes have committed.
- Make retries idempotent. Use a source key, event identity, or deterministic upsert so that a repeated batch does not corrupt the destination.
- Handle deletes explicitly. With Change Tracking, a missing source row may represent a delete. With CDC, inspect the operation metadata.
- Monitor the validity window. Alert on the minimum valid Change Tracking version, CDC LSN availability, cleanup delays, and failed consumer runs.
- Rebuild after excessive downtime. If the consumer falls outside the retention window, perform a full reload instead of trying to reconstruct missing events.
Which feature should you choose?
Choose Change Tracking when the consumer needs to identify affected rows and can read current values from the source database. It is a good fit for synchronization and cache invalidation where intermediate states are not important.
Choose CDC when downstream processing needs insert, update, and delete details, historical transition values, or an incremental feed for a warehouse. CDC also requires operational attention: SQL Server Agent capture and cleanup jobs, permissions, storage growth, and the validity of the LSN range must be monitored.
Neither feature should automatically be treated as a long-term audit archive, backup strategy, or disaster-recovery mechanism. If regulatory history is required, copy the consumed changes into a separately managed archive with its own retention, access control, and recovery policy.
Sources
- https://learn.microsoft.com/en-us/sql/relational-databases/track-changes/about-change-tracking-sql-server/
- https://learn.microsoft.com/en-us/sql/relational-databases/track-changes/enable-and-disable-change-tracking-sql-server/
- https://learn.microsoft.com/en-us/sql/relational-databases/track-changes/about-change-data-capture-sql-server/
- https://learn.microsoft.com/en-us/sql/relational-databases/track-changes/enable-and-disable-change-data-capture-sql-server/
- https://learn.microsoft.com/en-us/sql/relational-databases/system-functions/change-data-capture-functions-transact-sql
0 Comments