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
4
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
3
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
2
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
5
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
3
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
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
6
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
8
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
12
