Michael Paycer (@MichaelPaycer) header
Michael Paycer (@MichaelPaycer) profile picture

Michael Paycer | SQL Server DBA & Database Developer | 20+ Years Supporting Production Systems | Performance Tuning, HA/DR, Azure SQL & T-SQL

St Cloud, MN
Joined January 2019
Photo by Michael Paycer (@MichaelPaycer)
A hash index on a memory-optimized table has a fixed number of buckets. Too few and distinct keys share buckets, chains grow, and equality lookups slow down. Too many and empty buckets slow full index scans and use memory, 8 bytes each. SELECT OBJECT_NAME(h.object_id) AS tbl, i.name AS idx, h.total_bucket_count, h.empty_bucket_count, h.avg_chain_length, h.max_chain_length FROM sys.dm_db_xtp_hash_index_stats AS h JOIN sys.indexes AS i ON i.object_id = h.object_id AND i.index_id = h.index_id JOIN sys.memory_optimized_tables_internal_attributes AS ia ON ia.xtp_object_id = h.xtp_object_id WHERE ia.type = 1; → Few empty buckets, similar avg and max chains: BUCKET_COUNT is too low → Many empty buckets, max chain far above avg: duplicate keys. Consider a nonclustered index → Aim for 1 to 2 times the distinct key count The DMV scans the whole table. Run it off-peak. #SQLServer #Internals #InMemoryOLTP
3
Which indexes were built with a fill factor below 100, leaving free space on every leaf page? Biggest first: SELECT OBJECT_NAME(i.object_id) AS tbl, i.name AS index_name, i.fill_factor, SUM(ps.used_page_count) * 8 / 1024 AS used_mb FROM sys.indexes AS i JOIN sys.dm_db_partition_stats AS ps ON ps.object_id = i.object_id AND ps.index_id = i.index_id WHERE i.fill_factor NOT IN (0, 100) AND OBJECTPROPERTY(i.object_id, 'IsUserTable') = 1 GROUP BY i.object_id, i.name, i.fill_factor ORDER BY used_mb DESC; Fill factor 0 and 100 are the same in all respects, so every row here is deliberate free space. It's applied when the index is created or rebuilt. The cost lands on reads: per Learn, fill factor 50 doubles the disk I/O and memory to read and cache the same data. Make each low setting earn its keep. Docs: learn.microsoft.com/en-us/sq… #SQLServer #Indexing #TSQL #PerformanceTuning
1
Columnstore loads have a number worth memorizing: 102,400 rows. A bulk load batch of at least 102,400 rows goes straight into compressed rowgroups. Smaller batches, and leftovers at the end, land in delta rowgroups for the tuple mover. BULK INSERT dbo.FactSales FROM 'D:\load\sales.dat' WITH (BATCHSIZE = 1048576); → Direct-to-compressed loads get reduced logging; delta rowgroup rows are fully logged → A rowgroup holds up to 1,048,576 rows → INSERT ... SELECT from staging follows the same rule as one batch Exception: with a nonclustered columnstore index, rows always go into the base table first. Docs: learn.microsoft.com/en-us/sq… #SQLServer #Columnstore #ETL #PerformanceTuning
2
Python scripts that use pyodbc need an ODBC driver installed first. Microsoft's mssql-python driver skips that step. pip install mssql-python from os import getenv from mssql_python import connect conn = connect(getenv("SQL_CONNECTION_STRING")) cursor = conn.cursor() cursor.execute("SELECT name, state_desc FROM sys.databases;") for row in cursor.fetchall(): print(row) conn.close() → Generally available, and follows the Python DB API 2.0 spec (PEP 249). → Uses Direct Database Connectivity (DDBC), so there's no external driver manager to install. On Windows, one pip install brings everything it needs. → Python 3.10 or later, on Windows, macOS, and Linux. → Supports Microsoft Entra ID authentication, including managed identities and interactive sign-in. Docs: learn.microsoft.com/en-us/sq… #SQLServer #Python #DevOps #DBA
18
Deleting a row from a compressed columnstore rowgroup doesn't remove it. SQL Server marks it logically deleted and keeps the physical row until the index is rebuilt. An UPDATE is a delete plus an insert into the deltastore. Update-heavy columnstore tables collect these dead rows. Measure them: SELECT OBJECT_NAME(object_id) AS tbl, row_group_id, total_rows, deleted_rows, 100 * deleted_rows / NULLIF(total_rows, 0) AS pct_deleted FROM sys.dm_db_column_store_row_group_physical_stats WHERE state_desc = 'COMPRESSED' ORDER BY pct_deleted DESC; → Microsoft's guidance: at 20% deleted rows or more, reorganize or rebuild → Since SQL Server 2019, a background merge task also merges compressed rowgroups that have lost many rows → Rows still in the deltastore are deleted and updated in place; this only affects compressed rowgroups #SQLServer #Internals #Columnstore #Indexing
3
Query Store hints change a query without touching the code, so nobody sees them in the code. Audit them: SELECT h.query_id, h.query_hint_text, h.source_desc, h.query_hint_failure_count, h.last_query_hint_failure_reason_desc, LEFT(qt.query_sql_text, 200) AS query_text FROM sys.query_store_query_hints AS h JOIN sys.query_store_query AS q ON q.query_id = h.query_id JOIN sys.query_store_query_text AS qt ON qt.query_text_id = q.query_text_id ORDER BY h.query_hint_failure_count DESC; query_hint_text is stored as N'OPTION (...)'. A non-zero failure count means the hint didn't apply; the reason column says why. source_desc separates user hints from system-generated ones. Set with sys.sp_query_store_set_hints, removed with sys.sp_query_store_clear_hints. SQL Server 2022+. Docs: learn.microsoft.com/en-us/sq… #SQLServer #QueryStore #TSQL #QueryTuning
6
Non-parameterized apps hide their most expensive query in plain sight. Each literal variation is its own query in Query Store, so each looks cheap. Group by query_hash to see the family: SELECT TOP 10 q.query_hash, COUNT(DISTINCT q.query_id) AS variants, SUM(rs.avg_cpu_time * rs.count_executions) AS cpu_us FROM sys.query_store_query AS q JOIN sys.query_store_plan AS p ON p.query_id = q.query_id JOIN sys.query_store_runtime_stats AS rs ON rs.plan_id = p.plan_id GROUP BY q.query_hash ORDER BY cpu_us DESC; query_hash is computed over the query's shape, so statements that differ only by literals share it. Many variants plus high total CPU is your case for parameterization. Caveat: with QUERY_CAPTURE_MODE = AUTO (the 2019+ default), rare variants may not be captured, so treat totals as a floor. Docs: learn.microsoft.com/en-us/sq… #SQLServer #QueryStore #Parameterization #PerformanceTuning
3
A full columnstore rowgroup holds 1,048,576 rows. When a COMPRESSED rowgroup holds fewer, SQL Server records the reason in trim_reason_desc. SELECT OBJECT_NAME(object_id) AS tbl, trim_reason_desc, COUNT(*) AS rowgroups, AVG(total_rows) AS avg_rows FROM sys.dm_db_column_store_row_group_physical_stats WHERE state_desc = 'COMPRESSED' GROUP BY object_id, trim_reason_desc; What the common values mean: → NO_TRIM: full rowgroup → BULKLOAD: the load's batch size limited the rows. Load bigger batches → MEMORY_LIMITATION: not enough memory to compress all rows. Check the memory available to the build → DICTIONARY_SIZE: the dictionary grew too large → REORG: compression forced by REORGANIZE → RESIDUAL_ROW_GROUP: closed under 1 million rows during an index build Lots of small rowgroups mean weaker compression and more segments to read. #SQLServer #Internals #Columnstore
5
Granted Lock Pages in Memory to the service account? Confirm SQL Server is actually using it, no error log digging: SELECT si.sql_memory_model_desc, pm.locked_page_allocations_kb / 1024 AS locked_mb, pm.large_page_allocations_kb / 1024 AS large_page_mb, pm.physical_memory_in_use_kb / 1024 AS in_use_mb FROM sys.dm_os_sys_info AS si CROSS JOIN sys.dm_os_process_memory AS pm; → CONVENTIONAL: not using locked pages → LOCK_PAGES: locked pages in use → LARGE_PAGES: Enterprise edition, LPIM plus trace flag 834 The model is picked at service startup, so a freshly granted privilege shows CONVENTIONAL until you restart. sql_memory_model_desc needs SQL Server 2016 SP1+ (or 2012 SP4). Docs: learn.microsoft.com/en-us/sq… #SQLServer #Memory #TSQL #DBA
7
Azure SQL Database can create and drop indexes for you, and undo its own changes when they don't help. Automatic tuning options: → CREATE_INDEX: creates indexes that might improve the workload, then verifies the gain → DROP_INDEX: drops unused (last 90 days) and duplicate indexes; unique indexes are never dropped → FORCE_LAST_GOOD_PLAN: automatic plan correction Azure defaults: FORCE_LAST_GOOD_PLAN on, CREATE_INDEX and DROP_INDEX off. SQL Managed Instance supports only FORCE_LAST_GOOD_PLAN. ALTER DATABASE CURRENT SET AUTOMATIC_TUNING (CREATE_INDEX = ON); The catch: validation (30 minutes to 72 hours) and automatic revert only apply when the system makes the change. Apply a recommendation via T-SQL yourself and there's no automatic validation or reversal. Check the current state in sys.database_automatic_tuning_options. Docs: learn.microsoft.com/en-us/az… #SQLServer #AzureSQL #Indexing #PerformanceTuning
7
Load 50,000 rows into a clustered columnstore index and none of them get compressed. Bulk loads under 102,400 rows go to the deltastore, a set of clustered B-tree indexes, and are fully logged. Loads of 102,400 rows or more go straight into compressed rowgroups with reduced logging. A delta rowgroup stays OPEN until it reaches 1,048,576 rows, then turns CLOSED. The tuple mover, a background process, compresses CLOSED rowgroups. SELECT OBJECT_NAME(object_id) AS tbl, state_desc, COUNT(*) AS rowgroups, SUM(total_rows) AS total_rows FROM sys.dm_db_column_store_row_group_physical_stats GROUP BY object_id, state_desc; → Lots of rows in OPEN rowgroups: batch loads at 102,400 rows or more → To compress OPEN rowgroups now: ALTER INDEX ... REORGANIZE WITH (COMPRESS_ALL_ROW_GROUPS = ON) #SQLServer #Internals #Columnstore
3
Which tables have no primary key? A clustered index doesn't count: SELECT SCHEMA_NAME(t.schema_id) AS sch, t.name AS tbl, OBJECTPROPERTY(t.object_id, 'TableHasClustIndex') AS has_clustered FROM sys.tables AS t WHERE OBJECTPROPERTY(t.object_id, 'TableHasPrimaryKey') = 0 AND t.is_ms_shipped = 0 ORDER BY sch, tbl; → has_clustered = 1 means it isn't a heap, but it still has no primary key constraint. → Tables published for transactional replication must have a primary key. → A table with only a UNIQUE constraint still shows up here. Decide case by case whether to promote it. Docs: learn.microsoft.com/en-us/sq… #SQLServer #TSQL #DBA #Replication
1
10
GROUP BY runs as a Stream Aggregate or a Hash Match, and your indexes decide which is cheap. Aggregate is a logical operator, implemented as Stream Aggregate, Hash Match, Window Aggregate, or a CLR UserDefinedAggregate. → Stream Aggregate requires input ordered by the group columns. An ordered index seek or scan provides that; otherwise the optimizer adds a Sort. → Hash Match builds a hash table from its input. When that doesn't fit in available memory, you get hash recursion or bailout (Hash Warning), which means spilling to disk. In the plan, a Sort feeding a Stream Aggregate or a Hash Match with a spill warning is where the cost sits. Fix: an index keyed on the GROUP BY columns, covering the aggregated columns, lets it stream in order with no Sort and no hash table. It's still a cost-based choice, and indexes add write overhead. Docs: learn.microsoft.com/en-us/sq… #SQLServer #ExecutionPlans #Indexing
4
When a new row has to go onto a full index page, SQL Server moves about half the rows to a new page. That page split is resource-intensive, and the fragmentation it leaves reduces read-ahead efficiency during large scans. Fill factor leaves free space on leaf pages, but only when you create or rebuild the index. SQL Server doesn't keep that space open afterward. 0 and 100 are equivalent: full pages. ALTER INDEX IX_Orders_CustomerID ON dbo.Orders REBUILD WITH (FILLFACTOR = 90); → Helps when new keys land throughout the index → Wasted on ever-increasing keys: new rows go to the end, so the free space might never fill → Fill factor 50 doubles the I/O and memory to read the same data Measure before you change it. leaf_allocation_count in sys.dm_db_index_operational_stats counts leaf page allocations, which for an index correspond to page splits. #SQLServer #Internals #Indexing
2
Which bookings overlap another booking for the same room? A self-join with two comparisons finds every clashing pair. SELECT a.RoomId, a.BookingId, a.StartAt, a.EndAt, b.BookingId AS OverlapId, b.StartAt AS OverlapStart, b.EndAt AS OverlapEnd FROM dbo.Booking AS a JOIN dbo.Booking AS b ON b.RoomId = a.RoomId AND a.BookingId < b.BookingId AND a.StartAt < b.EndAt AND b.StartAt < a.EndAt ORDER BY a.RoomId, a.StartAt; → Two ranges overlap when each one starts before the other ends. That one test covers partial overlap, containment and identical ranges. → a.BookingId < b.BookingId skips self-matches and reports each pair once. → Strict < treats ranges as half-open: a booking ending at 10:00 doesn't clash with one starting at 10:00. Use <= if your end times are inclusive. Docs: learn.microsoft.com/en-us/sq… #SQLServer #TSQL #SQLTips
3
IO_COMPLETION and PAGEIOLATCH_* both mean waiting on I/O, but not the same I/O. Per the docs, data-page I/O completions show up as PAGEIOLATCH_* waits. IO_COMPLETION generally represents non-data-page I/O. So a high IO_COMPLETION number isn't, by itself, a sign the buffer pool is too small. Compare the two: SELECT wait_type, waiting_tasks_count, wait_time_ms, wait_time_ms / NULLIF(waiting_tasks_count, 0) AS avg_ms FROM sys.dm_os_wait_stats WHERE wait_type = 'IO_COMPLETION' OR wait_type LIKE 'PAGEIOLATCH%'; If IO_COMPLETION dominates, check latency for every file with sys.dm_io_virtual_file_stats, log and tempdb included, and look at what was running when it climbed. Learn doesn't list which operations produce it, so correlate rather than guess. Docs: learn.microsoft.com/en-us/sq… #SQLServer #WaitStats #Storage #PerformanceTuning
4
A clustered index on an IDENTITY or GETDATE() column sends every insert to the same last page until it fills. Under high concurrency, sessions stack up on PAGELATCH_EX waits for that one page. SQL Server 2019 added an index option for this pattern: ALTER INDEX PK_OrderLines ON dbo.OrderLines SET (OPTIMIZE_FOR_SEQUENTIAL_KEY = ON); → Default is OFF → Designed for sequential keys, and it may help other B-tree hot spots → It improves throughput for high-concurrency inserts without changing the key or the table design Find candidates first. sys.dm_db_index_operational_stats reports page_latch_wait_count and page_latch_wait_in_ms per index. High numbers on the clustered index of an insert-heavy table point at the last page. #SQLServer #Internals #Latches #Indexing
2
Need one JSON document per row, not FOR JSON over the whole result? Build it inline (SQL Server 2022+): SELECT o.OrderId, JSON_OBJECT( 'id': o.OrderId, 'customer': o.CustomerName, 'shippedAt': o.ShippedDate, 'tags': JSON_ARRAY(o.Region, o.Channel) ) AS order_json FROM dbo.Orders AS o; The NULL defaults differ between the two: → JSON_OBJECT: NULL ON NULL. A NULL ShippedDate becomes "shippedAt":null → JSON_ARRAY: ABSENT ON NULL. A NULL Region is left out of the array Add NULL ON NULL or ABSENT ON NULL inside the call to choose explicitly. Docs: learn.microsoft.com/en-us/sq… #SQLServer #JSON #TSQL #SQLServer2022
3
In Azure SQL Database Hyperscale, a page can come from three places, and the I/O numbers read differently. → Buffer pool (memory) → Local RBPEX SSD cache on the compute replica, sized proportionally to compute → Remote page servers, which are slower In sys.dm_io_virtual_file_stats, rows with database_id 0 are the local SSD cache. Rows for your database with file_id other than 2 are page servers; file_id 2 is the log. SELECT database_id, file_id, num_of_reads, io_stall_read_ms FROM sys.dm_io_virtual_file_stats(NULL, NULL) WHERE database_id IN (0, DB_ID()); A read from a page server shows up as a PAGEIOLATCH_* wait, and that time includes the page server catching up to the requested LSN. Actual plans carry ActualPageServerReads. RBIO_RG_* waits mean the log rate was reduced because a component fell behind. Docs: learn.microsoft.com/en-us/az… #SQLServer #AzureSQL #Hyperscale #PerformanceTuning
8
DBCC HELP is the command that tells you about every other DBCC command. DBCC HELP('?'); DBCC HELP('CHECKDB'); Running it with '?' lists every DBCC statement for which help is available; running it with a specific command name prints that command's syntax. Faster than tabbing to the docs when you're mid-incident and just need a syntax reminder. #SQLServer #Commands #DBCC #DBA
3