Skip to content

Instantly share code, notes, and snippets.

@elvishfiend
Created February 15, 2018 05:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save elvishfiend/5094f120b14f8ecfb325623edcb5f3eb to your computer and use it in GitHub Desktop.
Save elvishfiend/5094f120b14f8ecfb325623edcb5f3eb to your computer and use it in GitHub Desktop.
Indexed View ft. Count_Big - testing Index Substitution on Counts
IF (OBJECT_ID('Count_Test_View') IS NOT NULL)
DROP VIEW Count_Test_View
IF (OBJECT_ID('Count_Test') IS NOT NULL)
DROP TABLE Count_Test
CREATE TABLE Count_Test
(
Id int Identity(1,1) PRIMARY KEY NOT NULL,
value int
)
GO
CREATE VIEW Count_Test_View WITH SCHEMABINDING AS
(
SELECT COUNT_BIG(*) as count
FROM dbo.Count_Test
)
GO
CREATE UNIQUE CLUSTERED INDEX cuq ON Count_Test_View (count)
GO
-- Create some dummy data - takes approx 7 seconds for 1M rows
INSERT INTO Count_Test
SELECT TOP 1000000 RAND()*1000
FROM (SELECT 1 as n FROM sys.messages m1 CROSS JOIN sys.messages AS m2) as t
-- none of the following seem to use the Indexed View to speed up the Count
SELECT COUNT(*) FROM Count_Test
SELECT COUNT(*) FROM Count_Test NOEXPAND
SELECT COUNT_BIG(*) FROM Count_Test
SELECT COUNT_BIG(*) FROM Count_Test NOEXPAND
SELECT * FROM Count_Test_View
SELECT * FROM Count_Test_View NOEXPAND
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment