How to get COUNT(*) from one partition of a table in SQL Server 2012?

Masoomian picture Masoomian · Oct 31, 2014 · Viewed 7.6k times · Source

My table have 7 million records and I do split table in 14 part according to ID, each partition include 5 million record and size of partition is 40G. I want to run a query to get count in one partition but it scan all partitions and time of Query become very large.

SELECT COUNT(*) 
FROM Item 
WHERE IsComplated = 0 
  AND ID Between 1 AND 5000000

How can I run my query on one partition only without scan other partition?

Answer

HaveNoDisplayName picture HaveNoDisplayName · Oct 31, 2014

Refer http://msdn.microsoft.com/en-us/library/ms188071.aspx

B. Getting the number of rows in each nonempty partition of a partitioned table or index The following example returns the number of rows in each partition of table TransactionHistory that contains data. The TransactionHistory table uses partition function TransactionRangePF1 and is partitioned on the TransactionDate column. To execute this example, you must first run the PartitionAW.sql script against the AdventureWorks2012 sample database. For more information, see PartitioningScript.

USE AdventureWorks2012;
GO
SELECT $PARTITION.TransactionRangePF1(TransactionDate) AS Partition, 
COUNT(*) AS [COUNT] FROM Production.TransactionHistory 
GROUP BY $PARTITION.TransactionRangePF1(TransactionDate)
ORDER BY Partition ;
GO

C. Returning all rows from one partition of a partitioned table or index The following example returns all rows that are in partition 5 of the table TransactionHistory. Note Note To execute this example, you must first run the PartitionAW.sql script against the AdventureWorks2012 sample database. For more information, see PartitioningScript.

SELECT * FROM Production.TransactionHistory
WHERE $PARTITION.TransactionRangePF1(TransactionDate) = 5 ;