Sweetness, Shortness
Recently I blogged about last page contention solutions, and one thing I mentioned is that turning on OPTIMIZE_FOR_SEQUENTIAL_KEY doesn’t require you to rebuild an index. That’s awesome, because a whole lot of changes to indexes require you to rebuild them.
So how exactly do you do that?
Either when you create the table:
CREATE TABLE dbo.Votes_Insert
(
Id INT IDENTITY(1, 1) NOT NULL,
PostId INT NOT NULL,
UserId INT NULL,
BountyAmount INT NULL,
VoteTypeId INT NOT NULL,
CreationDate DATETIME NOT NULL,
CONSTRAINT PK_Votes_Insert_Id
PRIMARY KEY CLUSTERED (Id ASC)
WITH (OPTIMIZE_FOR_SEQUENTIAL_KEY = ON)
);
When you create the index:
CREATE INDEX so_optimized
ON dbo.Votes_Insert (Id) WITH (OPTIMIZE_FOR_SEQUENTIAL_KEY = ON);
Or if you need to alter an existing index:
ALTER INDEX so_optimized
ON dbo.Votes_Insert SET(OPTIMIZE_FOR_SEQUENTIAL_KEY = ON);
Get Back To Work
You’ll find this post again in a few years when you finally migrate to SQL Server 2019.
Thanks for reading!
Going Further
If this is the kind of SQL Server stuff you love learning about: these days I have AI do the annoying stuff for me. My new video course teaches you to work the same way, and I teach whole teams in a one-day workshop. Someone still has to know enough SQL Server to keep the robots in check, and that’s what my training is for.
Related Posts
- How SQL Server 2019 Helps You Find Queries That Have Missing Index Requests
- How SQL Server 2019 Helps You Link Queries To Missing Index Requests
- An Overlooked Benefit Of Batch Mode With Windowing Functions In SQL Server
- Batch Mode On Row Store vs Batch Mode Tricks For Performance Tuning SQL Server Queries
if promised throughput improvement is just 20-30%,
https://techcommunity.microsoft.com/t5/sql-server/behind-the-scenes-on-optimize-for-sequential-key/ba-p/806888
https://milossql.wordpress.com/2019/11/13/optimize_for_sequential_keys-miracle/
I’m wondering if we still need to combine OPTIMIZE_FOR_SEQUENTIAL_KEY feature with different solutions.
Most probably hash partitioning (Method #5)
or sequence + bit reversal + clr function (not T-SQL)
Resources:
https://erikdarling.com/sql-server/pros-and-cons-of-last-page-contention-solutions/
https://docs.microsoft.com/en-us/sql/relational-databases/diagnose-resolve-latch-contention?view=sql-server-ver15
https://docs.microsoft.com/en-us/archive/blogs/blogdoezequiel/pagelatch_ex-waits-and-heavy-inserts
handy query:
select concat(‘alter index ‘,quotename(i.name),’ on ‘, quotename(schema_name(t.schema_id)),’.’,quotename(t.name),’ SET(OPTIMIZE_FOR_SEQUENTIAL_KEY = ON);’)
from sys.indexes i
join sys.tables t
on i.object_id = t.object_id
where i.optimize_for_sequential_key= 0
and i.type > 0
and i.is_disabled = 0
and t.is_memory_optimized = 0;