How do you use the CREATE PARTITION SCHEME statement to create a partition scheme?
Posted by SamPetr
Last Updated: June 23, 2024
In SQL Server, a partition scheme is used to map the partitioning of a table or index to filegroups. The CREATE PARTITION SCHEME statement defines how the partitions are distributed across the specified filegroups. Here's the general syntax for creating a partition scheme:
CREATE PARTITION SCHEME partition_scheme_name
AS PARTITION partition_function_name
TO (filegroup1, filegroup2, filegroup3, ...);
Steps to Create a Partition Scheme
1. Create a Partition Function: Before creating a partition scheme, you need to have a partition function that defines how the data will be partitioned. Below is an example of a partition function that partitions data based on a range of values.
CREATE PARTITION FUNCTION partition_function_name (data_type)
    AS RANGE LEFT FOR VALUES (value1, value2, value3, ...);
For example, if you are partitioning based on an integer column:
CREATE PARTITION FUNCTION pf_sales (int)
    AS RANGE LEFT FOR VALUES (1000, 2000, 3000);
2. Create a Partition Scheme: Now you can create the partition scheme that maps the partitions defined by the partition function to specific filegroups.
CREATE PARTITION SCHEME ps_sales
    AS PARTITION pf_sales
    TO (fg1, fg2, fg3, fg4);
Here, fg1, fg2, fg3, and fg4 are the names of the filegroups in which the partitions will be stored.
Example
Here’s a complete example that creates a partition function and a corresponding partition scheme:
-- Step 1: Create filegroups (if not already created)
ALTER DATABASE YourDatabase
ADD FILEGROUP fg1 DEFAULT,
ADD FILEGROUP fg2,
ADD FILEGROUP fg3,
ADD FILEGROUP fg4;

-- Step 2: Create the Partition Function
CREATE PARTITION FUNCTION pf_sales (int)
AS RANGE LEFT FOR VALUES (1000, 2000, 3000);

-- Step 3: Create the Partition Scheme
CREATE PARTITION SCHEME ps_sales
AS PARTITION pf_sales
TO (fg1, fg2, fg3, fg4);
Important Notes
- Filegroups: Make sure the filegroups specified in the partition scheme are created in your database beforehand. - Partitioning Strategy: Depending on your data and query patterns, choose an appropriate strategy for partitioning the data. - Updating the Scheme: If you need to change the partition scheme later, you may have to drop and recreate the scheme or the associated objects, as modifications are not directly allowed. By following these steps and examples, you can successfully create a partition scheme in SQL Server to aid in managing large tables and improve query performance.
Related Content