Naar de inhoud

Deze pagina is nog niet beschikbaar in het Nederlands en wordt daarom in het Engels getoond.

SQL Table Synchronisation

How table-level synchronisation works in SQL Server: matching rows by key, applying inserts, updates and deletes, using row hashes, batching large tables and verifying the result.

Table synchronisation means making a target table match a source table: the same rows, with the same values. It sounds simple, and for a small table it is. For a table with hundreds of millions of rows, an identity column, foreign keys and a busy application writing to it, it needs more care.

This guide covers how table synchronisation works underneath: matching rows by key, applying the three kinds of change, using hashes to find changed rows cheaply, batching large tables and checking the result. For the wider choice of synchronisation methods, see our [SQL data synchronisation guide](/guides/sql-data-synchronisation-guide).

Match rows by key

Everything starts with a reliable way to match a row in the source with the same row in the target. That means a key that is unique and doesn't change: usually the primary key. With a key in place, every source row falls into one of three groups:

  • **In the source but not the target:** it needs inserting.
  • **In both, but with different values:** it needs updating.
  • **In the target but not the source:** it needs deleting, if deletes are part of the sync.

Tables without a reliable key are much harder to synchronise correctly. If a table has no primary key, find or add one before you start.

Apply inserts, updates and deletes

The three operations can be written as separate statements, which is usually clearer and easier to control than a single MERGE:

```sql

-- Update rows that changed

UPDATE t SET t.Status = s.Status, t.Amount = s.Amount, t.ModifiedAt = s.ModifiedAt

FROM target.dbo.Orders t

JOIN staging.dbo.Orders s ON s.OrderId = t.OrderId

WHERE EXISTS (SELECT s.Status, s.Amount, s.ModifiedAt EXCEPT SELECT t.Status, t.Amount, t.ModifiedAt);

-- Insert new rows

INSERT INTO target.dbo.Orders (OrderId, Status, Amount, ModifiedAt)

SELECT s.OrderId, s.Status, s.Amount, s.ModifiedAt

FROM staging.dbo.Orders s

WHERE NOT EXISTS (SELECT 1 FROM target.dbo.Orders t WHERE t.OrderId = s.OrderId);

-- Delete rows that no longer exist in the source

DELETE t

FROM target.dbo.Orders t

WHERE NOT EXISTS (SELECT 1 FROM staging.dbo.Orders s WHERE s.OrderId = t.OrderId);

```

The `EXISTS ... EXCEPT` pattern in the update compares the columns while treating NULLs as equal to each other, which a simple `<>` comparison doesn't. Only rows that genuinely differ are updated, which saves log and avoids firing triggers needlessly.

The `MERGE` statement can do all three in one go, but it has a history of edge cases and bugs, particularly under concurrency, and many teams prefer separate statements for anything important.

Use row hashes to find changes cheaply

Comparing every column of every row can be expensive on wide tables. A common shortcut is to calculate a hash of each row's values and compare hashes instead:

```sql

SELECT OrderId,

HASHBYTES('SHA2_256', CONCAT(Status, '|', Amount, '|', CONVERT(varchar(27), ModifiedAt, 126))) AS row_hash

FROM dbo.Orders;

```

Compute the hash on both sides, or store it in a column that is updated with the row, and only compare full values for rows whose hashes differ. Put a separator between every column, as here, so values running into each other can't produce false matches, and convert dates to a fixed format so both sides hash the same text. Avoid `CONCAT_WS` for this: it skips NULL values entirely, so different rows can produce the same string. `CONCAT` treats NULL as an empty string, so if a column can hold both NULL and empty strings, wrap it in something like `ISNULL(col, '<null>')`. Avoid `CHECKSUM` for this purpose; it is fast but far more likely to produce collisions, where different rows give the same value.

Batch large tables

Running a sync of a large table in one statement creates one enormous transaction. It holds locks for a long time, grows the transaction log and, if it fails, rolls everything back. Instead, process the table in batches by key range, for example 50,000 rows at a time, each in its own transaction. Batching keeps locks short, lets log backups clear the log as you go and means a failure only loses the current batch. Record which batches have completed, so a failed run can resume rather than starting again.

Watch for the awkward details

A few things trip up table synchronisation regularly:

  • **Identity columns.** Inserting explicit values needs `SET IDENTITY_INSERT ON` for that table, and the identity seed may need reseeding afterwards. See [handling identity columns during synchronisation](/guides/handling-identity-columns-during-sql-server-synchronisation).
  • **Foreign keys.** Parent tables need inserting before children, and children deleting before parents. Sync tables in dependency order, or disable and re-check constraints with care.
  • **Triggers.** Triggers on the target fire for every change unless you deal with them. Decide whether they should.
  • **Concurrent changes.** If the source keeps changing during the sync, the result is a mix of before and after. Sync from a snapshot, a staging copy or a consistent point in time where it matters.
  • **Incremental runs.** For repeated syncs, copying only changed rows using a watermark or Change Tracking is far cheaper than comparing everything each time. See [incremental synchronisation using watermarks](/guides/incremental-sql-table-synchronisation-using-watermarks).

Verify the result

After a sync, check that the tables really match. Start with row counts on both sides. Then compare an aggregate of the row hashes, or totals of key numeric columns, which catches differences counts can't. For critical tables, sample a set of rows by key and compare them in full. Record the results with each run, so you have evidence the sync worked and a history to look back on if a problem appears later.

Troubleshooting Scenarios

Every row is updated on every run

The comparison is treating NULLs as different. Use the EXISTS and EXCEPT pattern, or compare row hashes.

The sync fills the transaction log

It is running as one large transaction. Process the table in batches by key range, each in its own transaction.

Inserts fail with foreign key errors

Tables are being synchronised in the wrong order. Sync parent tables before child tables, and delete in the reverse order.

Row counts match but some values differ

Counts don't show changed values. Compare row hashes or totals of key columns as well.

Where SQL Cockpit fits

Table synchronisation involves configuring source and target, running the sync, often in batches, and checking each outcome. SQL Cockpit includes table synchronisation workflows for SQL Server, with configuration, progress and results kept together, and its MCP Server can inspect table metadata and recommend batch sizes. The principles in this guide, keys, batching and verification, apply however you run the sync.

FAQ

What is SQL table synchronisation?

It is making a target table match a source table by applying the inserts, updates and deletes needed, matched by a reliable key.

Should I use MERGE for table synchronisation?

It works, but it has known edge cases, especially under concurrency. Many teams prefer separate INSERT, UPDATE and DELETE statements.

How do I find changed rows efficiently?

Compare a hash of each row's values, such as HASHBYTES with SHA2_256, instead of comparing every column.

How do I synchronise a very large table?

Process it in batches by key range, each in its own transaction, and record progress so a failed run can resume.

How do I check that two tables match?

Compare row counts, then aggregates of row hashes or key column totals, and sample rows by key for critical tables.

Semantic Keywords

  • SQL table synchronisation
  • schema drift
  • table synchronisation
  • environment comparison
  • migration orchestration
  • SQL Server monitoring
  • SQL Agent monitoring
  • runtime analysis
  • runtime baselines
  • runtime variance
  • SQL Server operations
  • database telemetry
  • historical analysis
  • operational dashboards
  • cross-server monitoring

Suggested Related Articles