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)
Where do read-intent connections actually go? Show each primary's read-only routing list: SELECT pr.replica_server_name AS when_primary, rl.routing_priority, rr.replica_server_name AS routes_to, rr.read_only_routing_url, rr.secondary_role_allow_connections_desc FROM sys.availability_read_only_routing_lists AS rl JOIN sys.availability_replicas AS pr ON pr.replica_id = rl.replica_id JOIN sys.availability_replicas AS rr ON rr.replica_id = rl.read_only_replica_id ORDER BY when_primary, rl.routing_priority; A replica with no rows here routes nothing while it is primary. Targets need a read_only_routing_url and must allow READ_ONLY or ALL connections. Routing also needs the client side right: TCP, ApplicationIntent=ReadOnly, the listener name, and a database in the AG. Docs: learn.microsoft.com/en-us/sq… #SQLServer #AlwaysOn #HADR #TSQL
4
Parallel queries need workers, and SQL Server tracks the headroom per NUMA node in sys.dm_exec_query_parallel_workers (SQL Server 2016+, Azure SQL Database, Managed Instance): SELECT node_id, scheduler_count, max_worker_count, reserved_worker_count, used_worker_count, free_worker_count FROM sys.dm_exec_query_parallel_workers; → reserved_worker_count: reserved by parallel queries, plus main workers used by all requests → used_worker_count: used by parallel queries → free_worker_count: available for tasks free_worker_count can go negative on a heavily loaded server: every incoming request consumes at least one worker and is subtracted from it. When a parallel plan can't get the workers its DOP needs, the engine lowers the DOP or runs the serial plan. Check this view when queries run at a lower DOP than expected. Docs: learn.microsoft.com/en-us/sq… #SQLServer #Parallelism #DMV #DBA
3
Page compression runs three steps on each leaf page, in order: row compression, prefix compression, dictionary compression. → Prefix: for each column, SQL Server picks a prefix value, stores it in the compression information (CI) structure after the page header, and replaces full or partial matches with references → Dictionary: it then finds repeated values anywhere on the page, across columns, and stores those in the CI area → Non-leaf index pages get row compression only Timing matters. A page gets page-compressed when it's full and the next row arrives. In a heap, new pages added by normal DML don't get PAGE compression until you rebuild: ALTER TABLE dbo.StagingHeap REBUILD WITH (DATA_COMPRESSION = PAGE); Heap pages are also page-compressed by bulk imports with bulk optimizations, and by INSERT ... WITH (TABLOCK) when the heap has no nonclustered index. #SQLServer #Internals #Compression #Storage
4
Which SQL logins skip the password policy, and when did each password last change? SELECT name, is_disabled, is_policy_checked, is_expiration_checked, LOGINPROPERTY(name, 'PasswordLastSetTime') AS pwd_last_set, LOGINPROPERTY(name, 'IsLocked') AS is_locked, LOGINPROPERTY(name, 'DaysUntilExpiration') AS days_left FROM sys.sql_logins WHERE name NOT LIKE N'##%' ORDER BY pwd_last_set; is_policy_checked = 0 means CHECK_POLICY is OFF, and CHECK_EXPIRATION can't be ON without it. PasswordLastSetTime works everywhere. Per Learn, IsLocked and the other policy properties need both CHECK_POLICY and CHECK_EXPIRATION on, and DaysUntilExpiration is NULL if either is OFF. Docs: learn.microsoft.com/en-us/sq… #SQLServer #Security #TSQL #DBA
1
Not every deadlock is two sessions grabbing rows in opposite order. The deadlocks guide lists parallel query execution as its own resource type. Coordinator, producer or consumer threads on an exchange port can block each other, usually with at least one process outside the parallel query in the cycle. A sudden workload change, like running short of worker threads after the query picked its degree of parallelism, can also cause one. To spot it: system_health captures xml_deadlock_report by default. Look for one session ID appearing as several processes with different ecid values. ecid 0 is the main thread; ecid > 0 are its sub-threads. If the cycle runs through one query's own threads, reordering transactions won't help. Look at that query's parallel plan and estimates first. Docs: learn.microsoft.com/en-us/sq… #SQLServer #Deadlocks #Parallelism #PerformanceTuning
3
Row compression changes how each record is stored. Four changes do the work: → Numeric types and types based on them (int, bigint, decimal, datetime, money) use only the bytes the value needs → Fixed-length char and nchar drop trailing padding → NULL and 0 take no bytes in any data type → Per-record metadata about columns, lengths, and offsets shrinks (in some cases it grows) So a bigint column full of small values shrinks a lot, and so does a char(100) column holding short strings. nvarchar(max) values aren't Unicode-compressed, and compression doesn't change the maximum row size. Estimate before you rebuild: EXEC sys.sp_estimate_data_compression_savings @schema_name = N'dbo', @object_name = N'Orders', @index_id = NULL, @partition_number = NULL, @data_compression = N'ROW'; It samples the object into tempdb and reports current vs requested size. #SQLServer #Internals #Compression #Storage
5
A job failed overnight. Which step, and what did the error say? Failed steps since yesterday: SELECT j.name AS job_name, h.step_id, h.step_name, DATETIMEFROMPARTS(h.run_date / 10000, h.run_date % 10000 / 100, h.run_date % 100, h.run_time / 10000, h.run_time % 10000 / 100, h.run_time % 100, 0) AS run_start, h.sql_message_id, h.message FROM msdb.dbo.sysjobhistory AS h JOIN msdb.dbo.sysjobs AS j ON j.job_id = h.job_id WHERE h.run_status = 0 AND h.step_id > 0 AND h.run_date >= CONVERT(int, CONVERT(char(8), DATEADD(DAY, -1, GETDATE()), 112)) ORDER BY run_start DESC; run_date (yyyyMMdd) and run_time (HHmmss) are ints; the DATETIMEFROMPARTS arithmetic is from Learn's sysjobhistory example. run_status 0 = Failed. step_id > 0 skips the job-level row (step 0) and keeps the step that broke. Docs: learn.microsoft.com/en-us/sq… #SQLServer #SQLAgent #DBA #TSQL
5
With Accelerated Database Recovery, row versions live in the persistent version store (PVS) inside the user database, not tempdb. A stuck cleanup shows up as your data file growing. sys.dm_tran_persistent_version_store_stats (SQL Server 2019+) shows size and what's holding cleanup: SELECT DB_NAME(p.database_id) AS db, p.persistent_version_store_size_kb / 1024 AS pvs_mb, dt.database_transaction_begin_time AS oldest_tx_start, p.current_aborted_transaction_count FROM sys.dm_tran_persistent_version_store_stats AS p LEFT JOIN sys.dm_tran_database_transactions AS dt ON dt.transaction_id = p.oldest_active_transaction_id AND dt.database_id = p.database_id; → Long-running transactions delay cleanup and grow PVS; oldest_tx_start shows how old the blocker is. → A high abort rate (deadlocks, timeouts, constraint violations) also pressures the PVS cleaner. Docs: learn.microsoft.com/en-us/sq… #SQLServer #ADR #TransactionLog #DBA
4
Changes to indexes on memory-optimized tables are never written to disk. Only the data rows and their changes go to the transaction log. When the database comes back online, SQL Server rebuilds the memory-optimized indexes. Durability is a per-table choice: CREATE TABLE dbo.SessionCache ( SessionID int NOT NULL PRIMARY KEY NONCLUSTERED, Payload nvarchar(4000) NULL ) WITH (MEMORY_OPTIMIZED = ON, DURABILITY = SCHEMA_ONLY); → SCHEMA_AND_DATA (default): schema and data are durable, same guarantees as disk-based tables → SCHEMA_ONLY: no transaction logging for the data. The table definition survives a restart, the rows don't → Every memory-optimized table needs at least one index, because the indexes connect the rows SCHEMA_ONLY suits ETL staging and session state you can repopulate after a restart. #SQLServer #Internals #InMemoryOLTP
tempdb filling up? See which temp tables are biggest at this moment: SELECT TOP (20) o.name, o.create_date, SUM(ps.reserved_page_count) * 8 / 1024 AS reserved_mb, SUM(IIF(ps.index_id IN (0, 1), ps.row_count, 0)) AS row_count FROM tempdb.sys.dm_db_partition_stats AS ps JOIN tempdb.sys.objects AS o ON o.object_id = ps.object_id WHERE o.name LIKE N'#%' GROUP BY o.object_id, o.name, o.create_date ORDER BY reserved_mb DESC; Temp tables live in tempdb and their names start with #. reserved_page_count is in 8-KB pages, across all indexes of the table. sys.objects has no session column, so this won't tell you who owns a table. Pair it with sys.dm_db_session_space_usage for per-session totals. User objects only: sorts, spools and the version store use tempdb too and won't show here. Docs: learn.microsoft.com/en-us/sq… #SQLServer #tempdb #TSQL #DBA
6
Max server memory still at 2,147,483,647 MB isn't a setting. It's the absence of one. The documented starting point: 75% of available system memory not consumed by other processes, including other instances. The longer method for one instance: from total OS memory, subtract thread stacks (stack size × calculated max worker threads), then subtract 25% for allocations outside max server memory (backup buffers, linked server providers, sp_OA). What remains is your setting. Since SQL Server 2019, Setup on Windows recommends a value at install time. Older builds may still sit at the default. Check where you stand: SELECT c.value_in_use AS max_server_memory_mb, m.total_physical_memory_kb / 1024 AS os_total_mb FROM sys.configurations AS c CROSS JOIN sys.dm_os_sys_memory AS m WHERE c.name = 'max server memory (MB)'; Then watch real usage under load and adjust. Docs: learn.microsoft.com/en-us/sq… #SQLServer #Memory #Configuration #DBA
6
ALTER DATABASE SCOPED CONFIGURATION SET MAXDOP overrides server-level MAXDOP for just one database. ALTER DATABASE SCOPED CONFIGURATION SET MAXDOP = 4; On a multi-tenant instance where one database needs different parallelism behavior than the rest, this beats changing the instance-wide sp_configure 'max degree of parallelism' setting. Available since SQL Server 2016 - check current value in sys.database_scoped_configurations. #SQLServer #Commands #Performance #MAXDOP
The SSMS Generate Scripts wizard has defaults that leave things out of your script. Right-click a database > Tasks > Generate Scripts, then review the Advanced Scripting Options before you finish. → Types of data to script: defaults to Schema only. Change it if you need the data too. → Script Triggers: defaults to False, so DML triggers on tables are skipped. → Script Object-Level Permissions: defaults to False, so your object GRANTs stay behind. → Script Indexes: True for "Script entire database", False when you select specific objects. → Script for Server Version: defaults to the source server's version. Set it to the target's version when scripting for an older instance. Output can go to a single file, one file per object, the clipboard, or a new query window. One file per object works well in source control. Minimum permission: db_ddladmin on the source database. Docs: learn.microsoft.com/en-us/ss… #SQLServer #SSMS #DBA #Scripting
1
6
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
4
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
3
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
3
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
21
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
9
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