The goal
You have a large table partitioned by date. Each month you want to add an empty partition for the next period and archive or drop the oldest one, in seconds, with no long blocking and no log growth.
All of that is metadata-only if the partitions you split or merge are empty and you use SWITCH. If not, SQL Server physically moves rows under a schema modification lock and logs it fully. That is how a "two-second" job takes four hours and fills the transaction log.
Check the current layout
SELECT ps.name AS scheme, pf.name AS func, pf.boundary_value_on_right AS is_right,
p.partition_number, prv.value AS lower_or_upper_boundary,
fg.name AS filegroup, p.rows
FROM sys.partitions p
JOIN sys.indexes i ON i.object_id = p.object_id AND i.index_id = p.index_id
JOIN sys.partition_schemes ps ON ps.data_space_id = i.data_space_id
JOIN sys.partition_functions pf ON pf.function_id = ps.function_id
JOIN sys.destination_data_spaces dds
ON dds.partition_scheme_id = ps.data_space_id AND dds.destination_id = p.partition_number
JOIN sys.filegroups fg ON fg.data_space_id = dds.data_space_id
LEFT JOIN sys.partition_range_values prv
ON prv.function_id = pf.function_id
AND prv.boundary_id = p.partition_number - CASE WHEN pf.boundary_value_on_right = 1 THEN 1 ELSE 0 END
WHERE p.object_id = OBJECT_ID('dbo.Sales') AND i.index_id IN (0,1)
ORDER BY p.partition_number;
What you want to see:
RANGE RIGHTon a date column. Each boundary is the first instant of a period, which makes the window arithmetic simple.- An empty partition at both ends: one before the oldest period, one after the newest.
- Every index on the table aligned, that is built on the same partition scheme. A non-aligned index blocks
SWITCH.
-- Non-aligned indexes break SWITCH
SELECT i.name, ds.type_desc
FROM sys.indexes i JOIN sys.data_spaces ds ON ds.data_space_id = i.data_space_id
WHERE i.object_id = OBJECT_ID('dbo.Sales') AND ds.type <> 'PS';
Why SPLIT and MERGE move data
| Operation | Metadata-only when | Moves data when |
|---|---|---|
SPLIT RANGE (x) | The partition being split has no rows on the side that becomes the new partition | Rows exist that must go to the new partition |
MERGE RANGE (x) | At least one of the two partitions is empty | Both partitions contain rows |
SWITCH | Always (but structure and constraints must match) | Never. It fails instead |
Data movement during SPLIT/MERGE is fully logged and holds a Sch-M lock for the duration. Microsoft's guidance is to split and merge only empty partitions.
The monthly procedure
Example: partition function pf_SalesMonth (RANGE RIGHT on datetime2), scheme ps_SalesMonth, table dbo.Sales with clustered index on (SaleDate, SaleId).
1. Add next period's partition while it is still empty
Split the empty trailing partition, never the one receiving current inserts.
-- Tell the scheme which filegroup the new partition will use
ALTER PARTITION SCHEME ps_SalesMonth NEXT USED [FG_2027];
-- Current max boundary is 2026-12-01; rows at or after the new boundary would have to move
SELECT COUNT_BIG(*) FROM dbo.Sales WHERE SaleDate >= '2027-01-01'; -- must be 0
ALTER PARTITION FUNCTION pf_SalesMonth() SPLIT RANGE ('2027-01-01');
Keep at least one, preferably two or three, empty future partitions in place, so a late job never has to split a populated partition.
Caution
If the check returns rows (future-dated data, a bad clock, test rows), do not split. A split now moves those rows under Sch-M. Move or delete the stray rows first, or create a boundary beyond them.
2. Switch out the oldest populated partition
Build a staging table with an identical structure on the same filegroup as the source partition: same columns, types, nullability, collation, clustered index and aligned nonclustered indexes, and compression settings that match.
-- Partition number for the oldest month (e.g. 2024-11)
SELECT $PARTITION.pf_SalesMonth('2024-11-01') AS pnum; -- say it returns 2
CREATE TABLE dbo.Sales_Out (
SaleId bigint NOT NULL,
SaleDate datetime2(0) NOT NULL,
Amount decimal(18,2) NOT NULL,
CONSTRAINT PK_Sales_Out PRIMARY KEY CLUSTERED (SaleDate, SaleId)
) ON [FG_2024];
-- add the same nonclustered indexes here
ALTER TABLE dbo.Sales SWITCH PARTITION 2 TO dbo.Sales_Out
WITH (WAIT_AT_LOW_PRIORITY (MAX_DURATION = 1 MINUTES, ABORT_AFTER_WAIT = SELF));
WAIT_AT_LOW_PRIORITY keeps the Sch-M request from queuing ahead of user queries and creating a lock convoy. ABORT_AFTER_WAIT = SELF gives up rather than killing user sessions. Retry later.
If you only need to delete the data, skip the staging table:
TRUNCATE TABLE dbo.Sales WITH (PARTITIONS (2));
This needs aligned indexes too.
3. Merge the now-empty boundary
SELECT COUNT_BIG(*) FROM dbo.Sales WHERE $PARTITION.pf_SalesMonth(SaleDate) IN (1, 2); -- must be 0
ALTER PARTITION FUNCTION pf_SalesMonth() MERGE RANGE ('2024-11-01');
With RANGE RIGHT, merging the oldest boundary combines the empty leading partition with the now-empty partition 2. No rows move.
4. Archive or drop the staging table
Copy dbo.Sales_Out to the archive (bcp, a columnstore archive table, or SWITCH into an archive table that has a matching partition), then drop it.
Loading with SWITCH IN
For bulk loads, load a staging table and switch it in. The staging table needs a trusted CHECK constraint that proves every row fits the target partition:
ALTER TABLE dbo.Sales_In WITH CHECK ADD CONSTRAINT CK_Sales_In_Range
CHECK (SaleDate >= '2026-12-01' AND SaleDate < '2027-01-01' AND SaleDate IS NOT NULL);
ALTER TABLE dbo.Sales_In SWITCH TO dbo.Sales
PARTITION $PARTITION.pf_SalesMonth('2026-12-01');
The target partition must be empty. WITH NOCHECK leaves the constraint untrusted (sys.check_constraints.is_not_trusted = 1), and the switch fails.
Errors you will hit
| Error text (abridged) | Cause | Fix |
|---|---|---|
| "ALTER TABLE SWITCH statement failed... index ... is not partitioned" / non-aligned | A nonclustered index is on a filegroup, not the scheme | Rebuild it aligned, or disable it during the switch |
| "...the source and target tables have different ..." (column, nullability, index) | Staging table definition differs | Script the staging table from the source; compare sys.columns and sys.indexes |
| "...check constraints of source table ... allow values not allowed by range" | Missing or untrusted CHECK constraint | Add the constraint WITH CHECK |
| "...target partition ... must be empty" | SWITCH IN into a populated partition | Switch out first, or load a different period |
| "...partition scheme does not have any next used filegroup" | NEXT USED not set before SPLIT | ALTER PARTITION SCHEME ... NEXT USED |
| Indexed view references the table | Switching is blocked | Drop and recreate the view around the window, or redesign |
Operational notes
- Statistics: on large partitioned tables, set
STATISTICS_INCREMENTAL = ONand update only the changed partition:UPDATE STATISTICS dbo.Sales (stat_name) WITH RESAMPLE ON PARTITIONS (37); - Maintenance: rebuild per partition (
ALTER INDEX ... REBUILD PARTITION = 37 WITH (ONLINE = ON), online single-partition rebuild requires Enterprise or Azure SQL) instead of the whole index. - Partition count: the limit is 15,000 per table, but large counts slow plan compilation and metadata operations. Monthly or daily partitions for a few years are fine. Hourly forever is not.
- Azure SQL Database: you cannot add filegroups, so everything is on
PRIMARY(NEXT USED [PRIMARY]). The rest of the procedure is identical.
Tip
Wrap the whole window in a stored procedure that computes boundaries from the date, checks emptiness, and raises an error rather than splitting or merging a populated partition. Run it from an Agent job with a failure notification, and have it log the before and after row counts per partition.
Prevent it next time
- Keep two or more empty future partitions, and alert when fewer remain.
- Add a check for non-aligned indexes to your deployment pipeline, so a developer's new index doesn't silently break next month's switch.
- Test the procedure on a restored copy once after any schema change to the table.
Get the weekly HubDatAI email
One email a week with everything new: posts, learning sessions and videos. Free, no spam, unsubscribe in one click. What you get