There is absolutely nothing new about what I’m writing here, this is a really old trick back from the SQL 2000 days but there are quite a few people who are not aware of the powers of partitioning your data and this is why I’m posting. Unfortunately, native partitioning is for large corporations and companies with thick wallets where Enterprise version is the only way there is, while the rest of us will have to tweak that standard version until our eyes pop out. Well…for those of you that are not aware: there is a way to partition even with standard version and I’m gonna show you how. It will take a bit more effort than the native way and it doesn’t do everything you would hope for but it’s still pretty darn powerful.
And this little script here illustrates the whole concept; you create a few tables with some check constraints, you create a union all view and VOILA! There is your partitioning! Before you run the script make sure to turn on “Show actual execution plan” in your Management studio.
CREATE TABLE part_table1 ( ID INT NOT NULL PRIMARY KEY CLUSTERED, SomeValue VARCHAR(20) ) GO CREATE TABLE part_table2 ( ID INT NOT NULL PRIMARY KEY CLUSTERED, SomeValue VARCHAR(20) ) GO CREATE TABLE part_table3 ( ID INT NOT NULL PRIMARY KEY CLUSTERED, SomeValue VARCHAR(20) ) GO ALTER TABLE part_table1 WITH CHECK ADD CONSTRAINT CK_part_table1 CHECK (ID >= 0 AND ID <= 10) ALTER TABLE part_table1 CHECK CONSTRAINT CK_part_table1 ALTER TABLE part_table2 WITH CHECK ADD CONSTRAINT CK_part_table2 CHECK (ID >= 11 AND ID <= 100) ALTER TABLE part_table2 CHECK CONSTRAINT CK_part_table2 ALTER TABLE part_table3 WITH CHECK ADD CONSTRAINT CK_part_table3 CHECK (ID >= 101) ALTER TABLE part_table3 CHECK CONSTRAINT CK_part_table3 GO CREATE VIEW part_table AS SELECT * FROM part_table1 UNION ALL SELECT * FROM part_table2 UNION ALL SELECT * FROM part_table3 GO INSERT INTO part_table SELECT 9, 'sqlteam' INSERT INTO part_table SELECT 24, 'sqlteam' INSERT INTO part_table2 SELECT 25, 'sqlteam' SELECT * FROM part_table WHERE ID = 25
Notice in the execution plan when you do the inserts and the select. The insert is a clustered insert but as you can see it scans all the tables to find the right one which is somewhat annoying. But when you look at the final select you see where the “magic” is happening: when you do a select based on the “partitioning column” the query optimizer actually knows which data is where so it only has to search one of the tables! Pretty cool stuff…at least somewhat cool hehe. Using this method you can utilize quite a few of the partitioning techniques that are built in the native partitioning. You can for example have each partition on a different disk and you can add and remove partitions from the view as you like, just remember to do changes in the view first before you delete or rename any tables permanently…