How to Delete Data from a Specific Partition in MS SQL 2012

partitioningperformancequery-performancesql serversql-server-2012

I would like to delete data from a specific partition using the partition ID. I got queries to truncate data from specific partition for SQL 2016 but did not find any query for lower versions.

I tried below query to delete only data from partitions with partition id 14 and 15.

delete from  partitiontable1 WITH (PARTITIONS (14 to 15))

Will the delete statement remove the partition itself along with data?

I want to keep the partition intact and remove data from specific partitions. Say, I have created partitions on a table, it has 5 partitions (1,2,3,4,5) and I want to remove data only from 2nd and 3rd partition.

Best Answer

This delete statement is invalid SQL Server 2012 syntax so it will do nothing but raise an error.

Removing a partition and it's associated boundary is done with MERGE DDL; DML statements like DELETE never remove partitions.

The most efficient way to remove all rows from a partition in SQL 2014 and earlier versions is with SWITCH (SQL 2016 allows specific partitions to be specified with a TRUNCATE). To use SWITCH, create a similarly partitioned staging table with identical schema and indexes. You can then switch data between tables as a meta-data operation and then TRUNCATE the staging table.

ALTER TABLE dbo.YourTable
    SWITCH PARTITION 1 TO dbo.YourTable_Staging PARTITION 1;
ALTER TABLE dbo.YourTable
    SWITCH PARTITION 2 TO dbo.YourTable_Staging PARTITION 2;
ALTER TABLE dbo.YourTable
    SWITCH PARTITION 3 TO dbo.YourTable_Staging PARTITION 3;
ALTER TABLE dbo.YourTable
    SWITCH PARTITION 4 TO dbo.YourTable_Staging PARTITION 4;
ALTER TABLE dbo.YourTable
    SWITCH PARTITION 5 TO dbo.YourTable_Staging PARTITION 5;
TRUNCATE TABLE dbo.YourTable_Staging;