Developer Guides, Cheat Sheets & Tools

SQL course - Part 10: PERFORMANCE

Part index Prerequisites Previous Next Full course

⚡ PART 10 — PERFORMANCE


46. Indexes, the complete guide

🎚️ Level ⏱️ Time 🎯 After this chapter you can…
🟡🔴 Intermediate–Expert 45 min Explain how an index speeds up searches · Design multi-column and covering indexes · Choose what to index · Find missing and unused indexes

[!NOTE] 📌 In plain words: An index is a sorted lookup structure that lets the database find rows without reading the whole table. It is the single biggest performance lever you have.

🌍 Analogy: A textbook index. To find every mention of “photosynthesis” you could read all 900 pages (a table scan), or flip to the index at the back, find the word in alphabetical order, and jump straight to pages 145 and 302 (an index seek). The index costs a few extra pages and some effort to keep current — exactly like a database index.

46.1 🌳 How an index actually works

Data is stored in fixed-size blocks called pages (8 KB in SQL Server, 16 KB in MySQL). Both engines organize an index as a B-tree (balanced tree) of pages:

                    ┌─────────────┐
                    │   Root: M   │              ← 1 page read
                    └──┬───────┬──┘
              ┌────────┘       └────────┐
        ┌─────▼─────┐             ┌─────▼─────┐  ← 1 page read
        │  D    H   │             │  R    W   │
        └──┬──┬──┬──┘             └──┬──┬──┬──┘
     ┌─────┘  │  └─────┐              ...
  ┌──▼──┐ ┌───▼──┐ ┌───▼──┐                      ← 1 page read
  │A..C │ │ D..G │ │ H..L │  ← LEAF pages hold the keys (and pointers to rows)
  └─────┘ └──────┘ └──────┘

Why this is fast: with 3 levels you can locate any row among millions in 3 or 4 page reads. A table scan of the same data might be 100,000 page reads. That is the difference between 1 millisecond and 4 seconds.

[!NOTE] 📌 The cost side of the bargain: every INSERT, UPDATE, and DELETE must also update every index on that table. Ten indexes means ten extra structures to maintain on every write. Indexes make reads fast and writes slower. That trade-off is the whole art of indexing.

46.2 🗂️ Clustered vs non-clustered

  Clustered index Non-clustered index
What it is The table itself, physically sorted by the key A separate structure pointing back to the table
How many per table One (the data can only be sorted one way) Many (up to 999 in MSSQL, 64 in MySQL)
Leaf level contains The entire row The key + a pointer to the row
🟥 MSSQL default Created automatically on the PRIMARY KEY Created by CREATE INDEX
🟦 MySQL/InnoDB The PRIMARY KEY is the clustered index, always Secondary indexes store the PK as the pointer

🌍 Analogy: A dictionary is clustered — the words are physically in alphabetical order, and the definition is right there. A book index is non-clustered — it lists the term and a page number; you then have to turn to that page.

[!WARNING] ⚠️ A critical InnoDB consequence: because every secondary index stores the primary key as its row pointer, a wide primary key is duplicated inside every other index. A VARCHAR(200) primary key on a table with 6 indexes wastes an enormous amount of space and memory. Keep your primary key narrow — an INT or BIGINT.

-- 🟥 MSSQL: control the clustered index explicitly
CREATE TABLE events (
    event_id   BIGINT      NOT NULL,
    event_time DATETIME2(0) NOT NULL,
    payload    NVARCHAR(500),
    CONSTRAINT pk_events PRIMARY KEY NONCLUSTERED (event_id)   -- PK, but not clustered
);
CREATE CLUSTERED INDEX ix_events_time ON events(event_time);   -- cluster by time instead

[!TIP] 💡 Why you might do that: in a log table you almost always query by time range. Clustering by event_time means a month’s events are physically adjacent on disk — one sequential read instead of thousands of random ones.

46.3 🛠️ Creating indexes

-- ✅ Works in BOTH

-- Single column
CREATE INDEX ix_orders_order_date ON orders(order_date);

-- Composite (multi-column) — column ORDER IS CRITICAL, see below
CREATE INDEX ix_orders_customer_date ON orders(customer_id, order_date);

-- Unique index (also enforces a rule)
CREATE UNIQUE INDEX uq_suppliers_company_name ON suppliers(company_name);

-- Descending
CREATE INDEX ix_orders_date_desc ON orders(order_date DESC);

-- Drop — identical syntax in both engines
DROP INDEX ix_orders_order_date ON orders;
-- 🟦 MySQL also accepts the ALTER TABLE form
ALTER TABLE orders DROP INDEX ix_orders_date_desc;

46.4 🔑 Composite indexes and the left-prefix rule

[!WARNING] ⚠️ This is the most important indexing concept, and the one most people get wrong.

CREATE INDEX ix_orders_cust_date_status ON orders(customer_id, order_date, status);

🌍 Analogy — a phone book sorted by (last name, first name). You can find “all the Silvas” instantly. You can find “Silva, Amara” instantly. But you cannot find “everyone called Amara” without reading the whole book, because first names are only sorted within each last name.

Which filters support a direct left-prefix seek? The table describes search shape, not a guarantee of the chosen physical plan; the optimizer can still scan a covering index.

Query filter Uses the index? Why
WHERE customer_id = 1 ✅ Fully Left-most column
WHERE customer_id = 1 AND order_date >= '2026-01-01' ✅ Fully Left two columns
WHERE customer_id = 1 AND order_date = X AND status = 'Paid' ✅ Fully All three
WHERE customer_id = 1 AND status = 'Paid' ⚠️ Partly Jumps to customer_id via the index, then checks status row by row
WHERE order_date >= '2026-01-01' ⚠️ No ordinary left-prefix seek An index scan or engine-specific skip-scan strategy may still be chosen
WHERE status = 'Paid' ⚠️ No ordinary left-prefix seek An index scan may still cover the query

[!TIP] 💡 The rule for ordering columns in a composite index:

  1. Columns tested with = first — start with the one that narrows the rows down the most
  2. Range columns next (>, <, BETWEEN)
  3. Columns only used for ORDER BY after that
  4. INCLUDEd columns (MSSQL) last — see below

A range predicate (a >, <, or BETWEEN condition) “stops” the usefulness of everything after it, so a range column should be the last one that matters for seeking.

46.5 🎯 Covering indexes — the biggest single win

[!NOTE] 📌 In plain words: If an index contains every column the query needs, the engine never touches the table at all. This is called a covering index, and it is often a 10x improvement.

-- The query
SELECT customer_id, order_date, status
FROM orders
WHERE customer_id = 3 AND order_date >= '2026-01-01';
-- 🟥 MSSQL: INCLUDE stores extra columns in the index WITHOUT sorting by them
CREATE INDEX ix_orders_covering
    ON orders(customer_id, order_date)      -- key columns: used for seeking
    INCLUDE (status, employee_id);          -- payload: available without a lookup
-- 🟦 MySQL has no INCLUDE — add the columns to the key instead
CREATE INDEX ix_orders_covering
    ON orders(customer_id, order_date, status, employee_id);

[!TIP] 💡 Why INCLUDE is better than adding key columns (MSSQL): included columns are stored only in the bottom level of the tree, not in the pages above it. The index is smaller, the tree is shallower, and there is no sort-order overhead for those columns. Put columns you filter or sort on in the key; put columns you only select in INCLUDE.

How to spot the win: in an MSSQL plan, a “Key Lookup” (or “RID Lookup”) operator means the index found the rows but had to go back to the table for extra columns. Adding those columns to INCLUDE removes it. In MySQL EXPLAIN, Extra: Using index means the query was covered.

46.6 🎚️ Filtered and partial indexes

-- 🟥 MSSQL: index only the rows you actually query
CREATE INDEX ix_orders_pending
    ON orders(order_date)
    WHERE status = 'Pending';

[!IMPORTANT] 🎯 When this is brilliant: 5 million orders, of which 200 are pending. A full index has 5 million entries; the filtered index has 200. It is tiny, it stays in memory, and it is updated far less often.

Other great uses: WHERE is_deleted = 0 (soft-delete tables), WHERE tax_id IS NOT NULL (with a UNIQUE index: every real value must be unique, while many rows can still be NULL).

🔀 MySQL has no filtered indexes. The closest approach is a generated column plus an index on it, or simply accepting the full index.

46.7 📚 Other index types

Type 🟥 MSSQL 🟦 MySQL Use for
B-tree ✅ Default ✅ Default Almost everything
Full-text ✅ CREATE FULLTEXT INDEX ✅ FULLTEXT index Word/phrase search in long text
Spatial ✅ Spatial index ✅ SPATIAL index Maps, distances
Columnstore ✅ Clustered/nonclustered columnstore ❌ Reports over tables with many millions of rows
Hash ✅ Memory-optimized tables ✅ MEMORY engine only Exact-match lookups
Functional/expression ⚠️ via computed column ✅ 8.0.13+ ((LOWER(email))) Indexing an expression
Descending ✅ ✅ 8.0+ (honoured) Matching ORDER BY … DESC
-- 🟥 MSSQL: full-text search
CREATE FULLTEXT CATALOG ft_catalog AS DEFAULT;
GO

-- ⚠️ KEY INDEX must name a UNIQUE, single-column, NOT NULL index that
--    actually exists. ShopDB's primary keys were declared inline, so
--    SQL Server auto-generated names like PK__products__47027DF5E820107F.
--    Look yours up first:
SELECT name, is_unique, is_primary_key
FROM sys.indexes
WHERE object_id = OBJECT_ID('products') AND is_unique = 1;
GO

-- Simplest: create your own named unique index and point at that
CREATE UNIQUE INDEX ux_products_ftkey ON products(product_id);
GO

CREATE FULLTEXT INDEX ON products(product_name)
    KEY INDEX ux_products_ftkey ON ft_catalog;
GO

SELECT * FROM products WHERE CONTAINS(product_name, '"Ultra*" OR "Vision*"');

[!WARNING] ⚠️ Two things that stop this working. First, KEY INDEX must name a real unique, single-column, non-nullable index — passing a name that does not exist gives “‘pk_products’ is not a valid index to enforce a full-text search key.” Second, Full-Text Search is a separate installable component. If it was not selected during setup you get “Full-Text Search is not installed, or a full-text component cannot be loaded” (error 7609), and you must add the feature before any of this works. Check with:

-- 🟥 MSSQL
SELECT SERVERPROPERTY('IsFullTextInstalled') AS fulltext_installed;   -- 1 = yes
-- 🟦 MySQL: full-text search
ALTER TABLE products ADD FULLTEXT INDEX ft_product_name (product_name);

SELECT * FROM products
WHERE MATCH(product_name) AGAINST('Ultra* Vision*' IN BOOLEAN MODE);

[!TIP] 💡 Full-text search implements token/word search, not arbitrary substring matching. The examples use explicit word prefixes so Ultra* can match a token such as UltraBook; searching for Book does not necessarily match inside that token. Tokenization, stopwords and minimum token lengths affect results. A leading-wildcard LIKE normally prevents a B-tree range seek, although a covering index can still be scanned. Choose the search semantics first; see MySQL full-text documentation.

46.8 🧭 What to index — the practical checklist

✅ Index these ❌ Do not index these
Primary keys (automatic) Columns with very few distinct values (a gender or is_active flag alone)
Every foreign key column Columns you never filter, join, or sort on
Columns in WHERE that narrow the results down to few rows Very wide columns (long VARCHAR)
Columns in JOIN ... ON Tables that are tiny (under a few hundred rows)
Columns in ORDER BY / GROUP BY Tables that are written far more than read
Columns in UNIQUE business rules Every column “just in case”

[!WARNING] ⚠️ MSSQL does NOT automatically index foreign key columns. MySQL does. This means the same schema can perform completely differently on the two engines. On SQL Server, indexing your FK columns is often the single highest-value tuning action available — it speeds up joins and prevents table scans when a parent row is deleted.

-- ✅ 🟥 MSSQL: do this on day one of any project (MySQL indexes foreign keys automatically)
CREATE INDEX ix_orders_customer_id   ON orders(customer_id);
CREATE INDEX ix_orders_employee_id   ON orders(employee_id);
CREATE INDEX ix_order_items_product  ON order_items(product_id);
CREATE INDEX ix_products_category_id ON products(category_id);
CREATE INDEX ix_products_supplier_id ON products(supplier_id);
CREATE INDEX ix_payments_order_id    ON payments(order_id);
CREATE INDEX ix_employees_manager_id ON employees(manager_id);

46.9 🔍 Finding missing and unused indexes

-- 🟥 MSSQL: what the optimizer wished it had (treat as a HINT, not an order)
SELECT
    ROUND(s.avg_total_user_cost * s.avg_user_impact * (s.user_seeks + s.user_scans), 0) AS improvement_score,
    d.statement AS table_name,
    d.equality_columns,
    d.inequality_columns,
    d.included_columns,
    s.user_seeks, s.user_scans
FROM sys.dm_db_missing_index_group_stats s
JOIN sys.dm_db_missing_index_groups   g ON g.index_group_handle = s.group_handle
JOIN sys.dm_db_missing_index_details  d ON d.index_handle = g.index_handle
ORDER BY improvement_score DESC;

[!WARNING] ⚠️ Never blindly create every “missing index” the DMV (a built-in system view that reports what the server has seen) suggests. It reports each query in isolation, so you can end up with 15 overlapping indexes on one table, each slowing down every write. Consolidate them: if it wants (a, b) and (a, b, c), create only (a, b, c).

-- 🟥 MSSQL: indexes nobody is using (candidates for deletion)
SELECT
    OBJECT_NAME(i.object_id) AS table_name,
    i.name AS index_name,
    s.user_seeks, s.user_scans, s.user_lookups,
    s.user_updates                      -- ← maintenance cost with no read benefit
FROM sys.indexes i
LEFT JOIN sys.dm_db_index_usage_stats s
       ON s.object_id = i.object_id AND s.index_id = i.index_id
       AND s.database_id = DB_ID()
WHERE i.type_desc = 'NONCLUSTERED'
  AND OBJECTPROPERTY(i.object_id, 'IsUserTable') = 1
  AND ISNULL(s.user_seeks,0) + ISNULL(s.user_scans,0) + ISNULL(s.user_lookups,0) = 0
ORDER BY s.user_updates DESC;
-- 🟦 MySQL: index usage and redundancy (sys schema)
SELECT * FROM sys.schema_unused_indexes;
SELECT * FROM sys.schema_redundant_indexes;
SELECT * FROM sys.schema_index_statistics WHERE table_schema = 'ShopDB';

SHOW INDEX FROM orders;

[!TIP] 💡 An unused index is pure cost: disk space, server memory, backup size, and slower writes — with zero read benefit. Auditing for them is one of the easiest wins available to a DBA. Just be sure your usage stats cover a full business cycle (including month-end reports) before you drop anything.

46.10 🧹 Index maintenance

Over time, indexes become fragmented: as rows are added and removed, pages end up half-empty and out of order, so reading them takes more work.

-- 🟥 MSSQL: check fragmentation
SELECT
    OBJECT_NAME(ips.object_id) AS table_name,
    i.name AS index_name,
    ips.avg_fragmentation_in_percent,
    ips.page_count
FROM sys.dm_db_index_physical_stats(DB_ID(), NULL, NULL, NULL, 'LIMITED') ips
JOIN sys.indexes i ON i.object_id = ips.object_id AND i.index_id = ips.index_id
WHERE ips.page_count > 1000
ORDER BY ips.avg_fragmentation_in_percent DESC;

-- The standard rule of thumb
ALTER INDEX ix_orders_customer_date ON orders REORGANIZE;     -- 5% to 30% fragmented
ALTER INDEX ix_orders_customer_date ON orders REBUILD;        -- over 30%
ALTER INDEX ALL ON orders REBUILD WITH (ONLINE = ON);         -- Enterprise and Developer editions only
-- 🟦 MySQL
ANALYZE TABLE orders;         -- refresh statistics
OPTIMIZE TABLE orders;        -- rebuild/reorganize; lock behavior depends on engine/table/DDL path

[!WARNING] ⚠️ InnoDB OPTIMIZE TABLE normally uses online DDL, allowing concurrent DML during the main rebuild with brief exclusive metadata-lock phases. Some configurations/features require a table-copy path and block writes; a long-running transaction can also delay metadata locking. Plan storage, I/O and lock impact for the actual table rather than promising zero blocking. See MySQL OPTIMIZE TABLE behavior.

[!TIP] 💡 Modern advice: fragmentation matters far less on SSDs than it did on spinning disks. Chasing 5% fragmentation nightly is usually wasted effort — updating statistics is more valuable than rebuilding indexes in most systems today.

46.11 🧪 Try it yourself

  1. Run a query filtering orders by customer_id and look at the plan. Add an index. Look again.
  2. Create a covering index for a three-column query and confirm the Key Lookup disappears (MSSQL) or Using index appears (MySQL).
  3. Create a composite index on (customer_id, order_date), then query filtering only on order_date. Explain why it is not used.
  4. Find all unused indexes in your database.
  5. Add 8 indexes to order_items, time a bulk insert, drop them, and time it again.

🧭 In practice — indexes

How to use it. CREATE INDEX ix_name ON table (columns). A clustered index (SQL Server) or the InnoDB primary key defines the physical row order — there is only one. Every other index is a separate sorted structure pointing back at the row. Add INCLUDE columns (SQL Server) to make an index covering. Expected result: the engine seeks directly to the rows instead of scanning the table, which you confirm in the execution plan — not by timing one run.

When to use it. When a query filters, joins, or sorts on a column and the plan shows a scan over a large table. Index foreign-key columns as a matter of course.

Where to use it. Any table that grows. Scenario: WHERE email = ? on a million-row customers table reads every row without an index and one row with it. The same index also makes the unique constraint on email cheap to enforce.

When not to use it. Do not index everything. Every index must be updated on every INSERT, UPDATE, and DELETE, so indexes are a direct tax on write speed and on storage. Do not index tiny tables — scanning 18 products is faster than traversing a tree. Do not create an index that duplicates the leading columns of an existing one; consolidate instead.

Best practices. Column order in a composite index is what decides whether it can be used: an index on (customer_id, order_date) serves a filter on customer_id alone, but an index on (order_date, customer_id) does not. Put the equality-filtered column first. Review unused indexes periodically — they cost writes and give nothing back — and always measure with the execution plan rather than a stopwatch, because a single timing mostly measures the cache.


47. Execution plans

🎚️ Level ⏱️ Time 🎯 After this chapter you can…
🔴 Expert 40 min Show how the database ran your query · Spot the warning signs of a slow query · Fix a slow query step by step · Use Query Store to catch plans that got worse

[!NOTE] 📌 In plain words: An execution plan is the database showing you exactly how it ran your query. Learning to read one turns performance tuning from guesswork into diagnosis.

🌍 Analogy: A route map from a satnav. You asked to get to the airport; the plan shows which roads it chose, how long each leg took, and where the traffic jam was.

47.1 🟥 Getting a plan in MSSQL

-- Estimated plan (does not run the query): Ctrl+L in SSMS
-- ⚠️ SET SHOWPLAN_ALL must be the ONLY statement in its batch, hence the GOs.
SET SHOWPLAN_ALL ON;
GO
    SELECT * FROM orders WHERE customer_id = 3;
GO
SET SHOWPLAN_ALL OFF;
GO

-- Actual plan (runs it and reports real row counts): Ctrl+M in SSMS
-- ✅ This is the one you want — estimates can be wrong, actuals never lie.

-- The numbers that matter most
SET STATISTICS IO ON;      -- how many pages were read
SET STATISTICS TIME ON;    -- CPU and elapsed time

SELECT c.full_name, COUNT(*) AS orders
FROM customers c
JOIN orders o ON o.customer_id = c.customer_id
GROUP BY c.full_name;

SET STATISTICS IO OFF;
SET STATISTICS TIME OFF;

Reading STATISTICS IO output:

Table 'orders'. Scan count 1, logical reads 145, physical reads 0, read-ahead reads 0.
                    │                  │                  │
                    │                  │                  └─ reads that hit DISK (slow)
                    │                  └─ pages read from MEMORY (the number to reduce)
                    └─ how many times the table was accessed

[!TIP] 💡 “Logical reads” is the best single number to tune. Unlike elapsed time, it does not change with server load or caching. Tune to reduce logical reads. If you halve them, you have genuinely halved the work.

47.2 🟦 Getting a plan in MySQL

-- Basic plan
EXPLAIN
SELECT c.full_name, COUNT(*) AS orders
FROM customers c
JOIN orders o ON o.customer_id = c.customer_id
GROUP BY c.full_name;

-- Richer output
EXPLAIN FORMAT=JSON
SELECT c.full_name, COUNT(*) AS orders
FROM customers c
JOIN orders o ON o.customer_id = c.customer_id
GROUP BY c.full_name;

-- 🌟 The best one (MySQL 8.0.18+): actually runs it and shows real timings
EXPLAIN ANALYZE
SELECT c.full_name, COUNT(*) AS orders
FROM customers c
JOIN orders o ON o.customer_id = c.customer_id
GROUP BY c.full_name;

The EXPLAIN columns that matter:

Column What it tells you
type The most important column. How rows are accessed — see the table below
key Which index was actually used (NULL = none!)
rows Estimated rows examined
filtered Percentage of those rows that survive the WHERE
Extra Warnings and extras — see below

type, from best to worst:

type Meaning Verdict
system / const One row, via a primary key 🟢 Perfect
eq_ref One row per join, via a unique index 🟢 Excellent
ref Several rows via a non-unique index 🟢 Good
range Index range scan (BETWEEN, >, IN) 🟡 Fine
index Full index scan 🟠 Reads everything, but only the index
ALL Full table scan 🔴 Investigate — usually a missing index

Extra values worth knowing:

Value Meaning
Using index 🟢 Covering index — the table was never touched
Using where Rows were filtered after reading. Normal
Using filesort 🟠 A sort was needed. An index could remove it
Using temporary 🟠 A temp table was built (common with GROUP BY)
Using join buffer 🔴 Joining without an index. Add one
Impossible WHERE The condition can never be true

47.3 🔍 The operators to recognize (MSSQL)

Operator What it means Good or bad?
Clustered/Index Seek Jumped directly to the rows via the tree 🟢 What you want
Index Scan Read the whole index 🟡 OK on small tables, bad on large
Table Scan Read every row of a heap (a table with no clustered index) 🔴 Usually a missing index
Key Lookup / RID Lookup Found rows in an index, went back to the table for more columns 🟠 Fix with INCLUDE
Nested Loops For each outer row, probe the inner 🟢 Good when the outer set is small
Hash Match Built a temporary lookup table in memory 🟡 Fine for large joins; bad if it overflows to disk
Merge Join Both inputs sorted, merged 🟢 Efficient when inputs are already ordered
Sort An explicit sort 🟠 Expensive; an index may remove it
Spool Saved an in-between result to reuse 🟠 Often a sign the query can be rewritten
Parallelism Split across CPU threads 🟡 Good for big queries, overhead for small ones

[!TIP] 💡 Read a graphical plan RIGHT TO LEFT, TOP TO BOTTOM — that is the direction data actually flows. The thickness of the arrows shows the row count; a thin arrow suddenly becoming very thick is where your query went wrong.

47.4 🚩 The five warning signs

① A huge gap between estimated and actual rows

Estimated: 1 row      Actual: 2,400,000 rows

The optimizer built a plan for one row (row-by-row lookups, very little memory) and then processed millions. Cause: out-of-date statistics, a condition that cannot use an index (non-SARGable, Chapter 48), a table variable, or a multi-statement TVF. Fix: update statistics; see Chapter 49.

② A scan where you expected a seek

Missing index, or the query is not SARGable. See Chapter 48.

③ Key Lookups running millions of times

The index found the rows but not all the columns. Add the missing columns to INCLUDE.

④ A warning triangle on an operator

MSSQL flags implicit conversions, missing statistics, and memory-grant spills right on the operator. Hover over it and read what it says — it usually names the exact problem.

⑤ Sort or Hash spilling to tempdb

The engine asked for too little memory and had to use disk. Caused by bad estimates; fixed by fixing the estimates.

47.5 🧪 A worked tuning example

-- 😱 THE SLOW VERSION
SELECT
    c.full_name,
    o.order_id,
    o.order_date
FROM customers c
JOIN orders o ON o.customer_id = c.customer_id
WHERE YEAR(o.order_date) = 2026
  AND c.country = 'Singapore'
ORDER BY o.order_date DESC;

What to inspect: look for scans, sorts and logical reads in your actual plan. The 145-read output earlier is illustrative, not a measurement from the 23-row ShopDB seed. A small table may reasonably scan even when an index exists.

Diagnosis:

  1. YEAR(o.order_date) wraps the column in a function → not SARGable → no index can be used.
  2. There is no index on orders.customer_id (in MSSQL) → the join scans.
  3. ORDER BY o.order_date requires an explicit sort.
-- ✅ 🟥 MSSQL — THE FIXED VERSION (MySQL has no INCLUDE: put those columns in the index key)
CREATE INDEX ix_orders_date_customer
    ON orders(order_date DESC, customer_id)
    INCLUDE (order_id);                       -- 🟥 MSSQL; MySQL: add to the key
CREATE INDEX ix_customers_country ON customers(country) INCLUDE (full_name);

SELECT
    c.full_name,
    o.order_id,
    o.order_date
FROM customers c
JOIN orders o ON o.customer_id = c.customer_id
WHERE o.order_date >= '2026-01-01'            -- ✅ SARGable range
  AND o.order_date <  '2027-01-01'
  AND c.country = 'Singapore'
ORDER BY o.order_date DESC;                   -- ✅ satisfied by the index order

Expected opportunity: an index seek or covering scan may reduce reads and sorting. The optimizer chooses the final plan; measure elapsed time and I/O before claiming an improvement.

47.6 🧰 Plan caching and parameter sniffing

[!NOTE] 📌 In plain words: The engine caches the plan it built so the next execution does not have to re-plan. Usually good. Occasionally disastrous.

Parameter sniffing: the plan is built for the first parameter value it sees. If that value was unusual, every later execution reuses a plan tuned for the wrong shape of data.

-- First call: @country = 'Vatican City' → 1 customer → nested loops plan cached
-- Later call: @country = 'USA'          → 2 million customers → still nested loops 😱

Fixes (MSSQL):

-- 🟥 MSSQL
DECLARE @country NVARCHAR(60) = 'Singapore';

-- Recompile this statement every time (small cost, always the right plan)
SELECT customer_id, full_name FROM customers WHERE country = @country
OPTION (RECOMPILE);

-- Optimize for a typical value
SELECT customer_id, full_name FROM customers WHERE country = @country
OPTION (OPTIMIZE FOR (@country = 'UK'));

-- Optimize for the average, ignoring the sniffed value
SELECT customer_id, full_name FROM customers WHERE country = @country
OPTION (OPTIMIZE FOR UNKNOWN);
GO

-- Clear one cached plan (or all — do NOT do this on a busy production server)
-- DBCC FREEPROCCACHE;
-- 🟦 MySQL: much less prone to this, but you can inspect the cache
SELECT * FROM performance_schema.events_statements_summary_by_digest
ORDER BY sum_timer_wait DESC LIMIT 10;

47.7 🐢 Finding your slowest queries

-- 🟥 MSSQL: the top 20 by total time
SELECT TOP 20
    qs.execution_count,
    qs.total_worker_time / 1000 AS total_cpu_ms,
    qs.total_elapsed_time / qs.execution_count / 1000 AS avg_elapsed_ms,
    qs.total_logical_reads,
    SUBSTRING(st.text, (qs.statement_start_offset/2)+1,
        ((CASE qs.statement_end_offset WHEN -1 THEN DATALENGTH(st.text)
          ELSE qs.statement_end_offset END - qs.statement_start_offset)/2)+1) AS query_text
FROM sys.dm_exec_query_stats qs
CROSS APPLY sys.dm_exec_sql_text(qs.sql_handle) st
ORDER BY qs.total_elapsed_time DESC;
-- 🟦 MySQL: enable and read the slow query log
SET GLOBAL slow_query_log = 'ON';
SET GLOBAL long_query_time = 1;               -- log anything over 1 second

-- Or use performance_schema / sys
SELECT * FROM sys.statements_with_runtimes_in_95th_percentile LIMIT 20;
SELECT * FROM sys.statements_with_full_table_scans LIMIT 20;
SELECT * FROM sys.statements_with_temp_tables LIMIT 20;

[!TIP] 💡 sys.statements_with_full_table_scans is the fastest way to find missing indexes in MySQL. It goes straight to the queries reading whole tables.

47.8 📼 Query Store — the flight recorder

[!NOTE] 📌 In plain words: The DMVs in 47.7 only know what is in the plan cache right now. Restart the server, or let a plan age out, and the evidence is gone. Query Store writes every query, every plan, and every runtime statistic to disk, inside the database — so you can answer “what changed at 4 a.m. on Tuesday?” on Wednesday morning.

🌍 Analogy: An aircraft’s black box. You do not read it while flying. You read it after something went wrong, and it tells you exactly what the plane was doing at the moment it did.

-- 🟥 MSSQL 2016+ (all editions, including Express): turn it on
ALTER DATABASE ShopDB SET QUERY_STORE = ON
    (OPERATION_MODE             = READ_WRITE,
     DATA_FLUSH_INTERVAL_SECONDS = 60,
     INTERVAL_LENGTH_MINUTES     = 5,       -- how finely runtime stats are bucketed
     MAX_STORAGE_SIZE_MB         = 1024,
     QUERY_CAPTURE_MODE          = AUTO,    -- AUTO skips trivial queries; ALL captures everything
     SIZE_BASED_CLEANUP_MODE     = AUTO);

-- Confirm it is actually recording
SELECT actual_state_desc, readonly_reason,
       current_storage_size_mb, max_storage_size_mb
FROM sys.database_query_store_options;

Result:

actual_state_desc readonly_reason current_storage_size_mb max_storage_size_mb
READ_WRITE 0 0 1024

[!WARNING] ⚠️ Check actual_state_desc, not just that the ALTER succeeded. If Query Store fills its quota it silently flips to READ_ONLY and stops recording — exactly when you need it most. A non-zero readonly_reason tells you why. Monitor it like any other disk.

-- 🟥 The slowest queries, with real history behind them
SELECT TOP 10
    LEFT(qt.query_sql_text, 80)                     AS query_text,
    rs.count_executions,
    CAST(rs.avg_duration / 1000.0 AS DECIMAL(10,2)) AS avg_ms,
    CAST(rs.avg_logical_io_reads AS INT)            AS avg_reads
FROM sys.query_store_query_text        qt
JOIN sys.query_store_query             q  ON q.query_text_id = qt.query_text_id
JOIN sys.query_store_plan              p  ON p.query_id      = q.query_id
JOIN sys.query_store_runtime_stats     rs ON rs.plan_id      = p.plan_id
ORDER BY rs.avg_duration DESC;

Result:

query_text count_executions avg_ms avg_reads
SELECT c.country, COUNT(*) AS orders FROM orders o JOIN cust… 1 0.24 27

[!WARNING] ⚠️ Two reasons a freshly enabled Query Store looks empty. First, QUERY_CAPTURE_MODE = AUTO deliberately ignores cheap, rarely-run queries — set it to ALL while testing. Second, runtime statistics are written asynchronously; call EXEC sys.sp_query_store_flush_db; to force a flush instead of waiting for DATA_FLUSH_INTERVAL_SECONDS.

The reason Query Store exists — catching a plan regression:

-- 🟥 Queries that have more than one plan are your regression candidates
SELECT q.query_id, COUNT(DISTINCT p.plan_id) AS plan_count
FROM sys.query_store_query q
JOIN sys.query_store_plan  p ON p.query_id = q.query_id
GROUP BY q.query_id
HAVING COUNT(DISTINCT p.plan_id) > 1;
-- 🟥 Pin the plan that was good, and release it again
-- (in real life, use the query_id / plan_id pair you picked from the regression query above)
DECLARE @query_id BIGINT, @plan_id BIGINT;
SELECT TOP (1) @query_id = query_id, @plan_id = plan_id
FROM sys.query_store_plan
ORDER BY plan_id;

IF @plan_id IS NOT NULL
BEGIN
    EXEC sys.sp_query_store_force_plan   @query_id = @query_id, @plan_id = @plan_id;

    SELECT plan_id, is_forced_plan FROM sys.query_store_plan WHERE plan_id = @plan_id;   -- 1 = forced

    EXEC sys.sp_query_store_unforce_plan @query_id = @query_id, @plan_id = @plan_id;
END;

[!IMPORTANT] 🎯 This is the cure for parameter sniffing (47.6) that does not require touching the query. A query that was fast for six months and is suddenly slow usually has a new, worse plan. Query Store lets you see both plans side by side, compare their runtime statistics, and force the good one — in seconds, in production, with no deployment.

[!WARNING] ⚠️ Forcing a plan is a tourniquet, not a cure. It stops the bleeding, and it also stops the optimizer ever improving that query — including after you add the index that would have fixed it properly. Record every forced plan, and review the list regularly. A forced plan can also silently stop being usable (if an index it depends on is dropped), so check sys.query_store_plan.force_failure_count.

Query Store gives you The DMVs in 47.7 give you
History that survives restarts and cache eviction Only what is cached right now
Multiple plans per query, with statistics for each One current plan
Plan forcing Hints and plan guides, which are harder to manage
Per-database, per-interval buckets you can graph A single running total since restart
A small write overhead None

🔀 MySQL has no direct equivalent. The closest combination is the performance_schema digest tables plus the sys schema views from 47.7 — persisted by scraping them into your own history table on a schedule, or by a monitoring tool (Percona PMM, MySQL Enterprise Monitor). The slow_query_log gives you the raw material but no plan history.

47.9 🎯 When to look at an execution plan

Trigger Do this
A query “feels slow” Get the actual plan, and SET STATISTICS IO ON
A query was fast yesterday, slow today Compare plans; suspect stale statistics or parameter sniffing
Before deploying any new query touching a big table Read the plan once — it takes 30 seconds
Adding an index Check the plan before and after to prove it was used
Estimated rows ≠ actual rows by 10x or more Fix the estimate before anything else
Everything is slow, not one query ❌ Not a plan problem — check waits, memory, disk (Ch 57)

[!TIP] 💡 What to look at, in order: ① Is there a scan where a seek was possible? ② Is estimated vs actual wildly different? ③ Is there a Key Lookup running thousands of times? ④ Is there a Sort that an index could remove? ⑤ Are there warning triangles? That order finds the problem roughly 90% of the time.

[!CAUTION] 🐛 Common mistake: tuning by stopwatch. Elapsed time changes with server load and caching, so you “fix” things that were never broken. Tune to reduce logical reads — that number stays the same from run to run and directly reflects the work done.

47.10 🧪 Try it yourself

  1. Run a SELECT * on orders with STATISTICS IO ON (or EXPLAIN) and note the reads.
  2. Add a WHERE customer_id = 3 and compare, before and after adding an index.
  3. Write a non-SARGable query with YEAR(), look at the plan, rewrite it as a range, and compare.
  4. Build a query that produces a Key Lookup, then eliminate it with INCLUDE.
  5. Find the top 5 slowest queries currently running on your server.

🧭 In practice — execution plans

How to use it. Ask the engine what it intends to do: SET SHOWPLAN_ALL ON or the graphical Include Actual Execution Plan in SSMS; EXPLAIN / EXPLAIN ANALYZE in MySQL. Read it right to left, looking for scans where you expected seeks, and for a large gap between estimated and actual row counts. Expected result: evidence about why a query is slow, instead of a guess.

When to use it. Before changing anything for performance, and again afterwards to confirm the change did what you thought.

Where to use it. Performance work and code review. Scenario: a report “got slow”. The plan shows the optimiser expected 1 row and got 400,000 — a statistics problem (Chapter 49), not a missing index. Adding an index would have cost a day and fixed nothing.

When not to use it. Do not tune without one. “It feels faster” after a change usually measures a warm cache, not your work. Also treat the plan’s index suggestions with suspicion — SQL Server’s missing-index hints are generated per query, ignore existing indexes, and following them mechanically produces a table with fifteen overlapping indexes and slow writes.

Best practices. Compare the estimated and actual row counts first; a large divergence explains most bad plans and points at statistics or a non-SARGable predicate. Capture a plan before you change anything so you can prove the improvement. Test on data of realistic size — plans chosen against 18 rows tell you nothing about behaviour at 18 million.


48. Query optimization and SARGability

🎚️ Level ⏱️ Time 🎯 After this chapter you can…
🟡🔴 Intermediate–Expert 35 min Write conditions that can use an index · Spot and fix the seven slow patterns · Rewrite a slow query step by step

[!NOTE] 📌 In plain words: SARGable means “Search ARGument able” — a condition the engine can answer by seeking (jumping straight to the matching rows through an index) instead of scanning (reading every row). Writing SARGable conditions is the most valuable habit in SQL performance.

🌍 Analogy: You are looking for “Silva” in a phone book. SARGable: flip straight to S. Non-SARGable: “find everyone whose surname UPPERCASED equals SILVA” — now you must read and transform every single name, because the book is not sorted by uppercased names.

48.1 🚫 The seven non-SARGable patterns (and their fixes)

In the examples below, ❌ SCAN marks the slow version and ✅ SEEK the fast one. On ShopDB’s tiny tables both run instantly — the difference shows up on tables with millions of rows.

① A function wrapped around the column

-- ❌ SCAN — the function hides the column from the index
SELECT order_id, order_date FROM orders
WHERE YEAR(order_date) = 2026;

-- ✅ SEEK — the column is bare on the left
SELECT order_id, order_date FROM orders
WHERE order_date >= '2026-01-01' AND order_date < '2027-01-01';

-- ❌ SCAN
SELECT customer_id, email FROM customers
WHERE UPPER(email) = 'AMARA.SILVA@EXAMPLE.COM';

-- ✅ SEEK (both engines are case-insensitive under the default collation)
SELECT customer_id, email FROM customers
WHERE email = 'amara.silva@example.com';
-- ✅ Case-sensitive collation? Add an indexed computed column (Chapter 41)

-- ❌ SCAN
SELECT customer_id FROM customers
WHERE CAST(customer_id AS CHAR(10)) = '3';

-- ✅ SEEK
SELECT customer_id FROM customers
WHERE customer_id = 3;

② Arithmetic on the column

-- ❌ SCAN
SELECT product_name, unit_price FROM products
WHERE unit_price * 1.15 > 1000;

-- ✅ SEEK — move the maths to the fixed-value side
SELECT product_name, unit_price FROM products
WHERE unit_price > 1000 / 1.15;

-- ❌ SCAN
SELECT product_name FROM products
WHERE units_in_stock - 10 > 0;

-- ✅ SEEK
SELECT product_name FROM products
WHERE units_in_stock > 10;

③ A leading wildcard in LIKE

-- ❌ No normal B-tree range seek for this leading-wildcard predicate; an index scan is still possible
SELECT product_name FROM products
WHERE product_name LIKE '%Book%';

-- ✅ SEEK — the engine jumps straight to the "Ultra" range
SELECT product_name FROM products
WHERE product_name LIKE 'Ultra%';

-- For token/word search, consider FULLTEXT (Chapter 46); it is not equivalent to arbitrary substring matching.

④ Implicit type conversion

-- ❌ phone is VARCHAR, so the COLUMN gets converted (scan — or an outright error)
SELECT customer_id, phone FROM customers
WHERE phone = 94775550101;

-- ✅ SEEK — literal typed to match the column
SELECT customer_id, phone FROM customers
WHERE phone = '+94-77-555-0101';

⑤ OR across different columns

-- ❌ Often scans — one index cannot serve both sides of the OR
SELECT order_id, customer_id, employee_id FROM orders
WHERE customer_id = 3 OR employee_id = 5;

-- ✅ Two seeks, combined
SELECT order_id, customer_id, employee_id FROM orders WHERE customer_id = 3
UNION
SELECT order_id, customer_id, employee_id FROM orders WHERE employee_id = 5;

⑥ NOT, <>, and NOT IN

-- ❌ "Everything except X" usually means reading everything anyway
SELECT order_id, status FROM orders
WHERE status <> 'Delivered';

-- ✅ If the alternatives are few, list them positively
SELECT order_id, status FROM orders
WHERE status IN ('Pending','Paid','Shipped','Cancelled','Refunded');

⑦ Comparing two columns of the same table

-- ⚠️ Works in BOTH: comparing two columns of the same row is inherently a scan
SELECT product_name, units_in_stock, reorder_level FROM products
WHERE units_in_stock <= reorder_level;
-- ✅ 🟥 MSSQL: if you run this constantly, store the answer in a column and index it
ALTER TABLE products
    ADD needs_reorder AS (CASE WHEN units_in_stock <= reorder_level THEN 1 ELSE 0 END) PERSISTED;
GO
CREATE INDEX ix_products_needs_reorder ON products(needs_reorder);
GO

-- Now this is an index seek
SELECT product_name FROM products WHERE needs_reorder = 1;
-- ✅ 🟦 MySQL: the same idea with a STORED generated column
ALTER TABLE products
    ADD COLUMN needs_reorder TINYINT
        AS (CASE WHEN units_in_stock <= reorder_level THEN 1 ELSE 0 END) STORED,
    ADD INDEX ix_products_needs_reorder (needs_reorder);

SELECT product_name FROM products WHERE needs_reorder = 1;

[!TIP] 💡 The universal principle: keep the indexed column bare (untouched) on one side of the comparison. Any calculation you can move onto the fixed value instead of the column, move it.

48.2 🎯 Ten more optimization rules

① Select only the columns you need

-- ❌ Stops covering indexes working, and sends data nobody reads
SELECT * FROM orders WHERE customer_id = 3;
-- ✅
SELECT order_id, order_date, status FROM orders WHERE customer_id = 3;

② Filter as early and as much as possible

Push conditions into WHERE, not HAVING. Filter inside subqueries and CTEs, not after them.

③ Use EXISTS instead of COUNT(*) > 0

-- 🟥 MSSQL
-- ❌ Counts every matching row before deciding
IF (SELECT COUNT(*) FROM orders WHERE customer_id = 3) > 0
    PRINT 'customer 3 has orders';

-- ✅ Stops at the very first match
IF EXISTS (SELECT 1 FROM orders WHERE customer_id = 3)
    PRINT 'customer 3 has orders';

④ Use UNION ALL unless you truly need deduplication (see Chapter 29).

⑤ Avoid DISTINCT as a bandage for a bad join — fix the join instead.

⑥ Do not join two “many” tables to the same parent without totalling them first — the fan-out problem from Chapter 28.

⑦ Batch large writes — 5000 rows at a time, not 5 million (Chapter 18).

⑧ Avoid scalar UDFs in SELECT and WHERE (Chapter 38).

⑨ Beware OFFSET on deep pages — use keyset pagination (Chapter 17).

⑩ Do not sort what you do not need sorted. An ORDER BY in a subquery or view is usually wasted work.

48.3 🔬 Before and after: a real rewrite

Result-shape change: the first query returns joined detail columns; the second deliberately produces one summary row per order. This is not a semantics-preserving performance rewrite. Confirm the required projection and aggregation first, and compare equivalent outputs before measuring speed. The country comparison also assumes the intended case-insensitive collation.

-- 😱 BEFORE: 4 problems in 12 lines
SELECT DISTINCT *
FROM orders o, customers c, order_items oi
WHERE o.customer_id = c.customer_id
  AND oi.order_id = o.order_id
  AND YEAR(o.order_date) = 2026
  AND UPPER(c.country) = 'SINGAPORE'
  AND (SELECT COUNT(*) FROM payments p WHERE p.order_id = o.order_id) > 0
ORDER BY o.order_date;

Problems: old comma joins; SELECT DISTINCT *; YEAR() and UPPER() on indexed columns; a correlated COUNT(*) that should be EXISTS.

-- ✅ AFTER
SELECT
    o.order_id,
    o.order_date,
    o.status,
    c.full_name,
    SUM(oi.quantity) AS total_units
FROM orders AS o
INNER JOIN customers   AS c  ON c.customer_id = o.customer_id
INNER JOIN order_items AS oi ON oi.order_id = o.order_id
WHERE o.order_date >= '2026-01-01'
  AND o.order_date <  '2027-01-01'
  AND c.country = 'Singapore'
  AND EXISTS (SELECT 1 FROM payments p WHERE p.order_id = o.order_id)
GROUP BY o.order_id, o.order_date, o.status, c.full_name
ORDER BY o.order_date;

Every condition is now SARGable, the joins are written out clearly, DISTINCT is replaced by a proper GROUP BY, and the payment check stops at the first payment it finds.

48.4 🎛️ Query hints — the last resort

-- 🟥 MSSQL (ix_orders_customer_id is the foreign-key index from Chapter 46.8)
IF NOT EXISTS (SELECT 1 FROM sys.indexes
               WHERE name = 'ix_orders_customer_id' AND object_id = OBJECT_ID('orders'))
    CREATE INDEX ix_orders_customer_id ON orders(customer_id);
GO

SELECT * FROM orders WITH (INDEX(ix_orders_customer_id)) WHERE customer_id = 3;

SELECT order_id FROM orders WHERE customer_id = 3 OPTION (RECOMPILE);
SELECT order_id FROM orders WHERE customer_id = 3 OPTION (MAXDOP 1);       -- use one CPU core only
SELECT o.order_id
FROM orders o JOIN customers c ON c.customer_id = o.customer_id
OPTION (FORCE ORDER);                                                      -- join as written
-- 🟦 MySQL (InnoDB already indexed the foreign key, under the constraint's name)
SELECT * FROM orders USE INDEX (fk_orders_customer) WHERE customer_id = 3;
SELECT * FROM orders FORCE INDEX (fk_orders_customer) WHERE customer_id = 3;
SELECT * FROM orders IGNORE INDEX (fk_orders_customer) WHERE customer_id = 3;
SELECT /*+ MAX_EXECUTION_TIME(1000) */ * FROM orders;    -- 8.0 optimizer hint: stop after 1000 ms

[!WARNING] ⚠️ Hints freeze a decision that should stay flexible. The plan you force today becomes wrong when the data grows, the statistics change, or you upgrade the engine — and nobody remembers the hint is there. Fix the root cause instead: the index, the condition, or the statistics. Use hints only as a temporary bridge, with a comment explaining why and a date to revisit.

48.5 🧪 Try it yourself

  1. Take each of the seven non-SARGable patterns, run both versions on ShopDB, and compare the plans.
  2. Rewrite the “before” query in 48.3 yourself before reading the “after”.
  3. Find a query in your own work that uses a function on a column and fix it.
  4. Force a bad index with a hint and observe the damage in the plan.

🧭 In practice — query optimization and SARGability

How to use it. A predicate is SARGable (Search-ARGument-able) when the engine can use an index to satisfy it. That requires the indexed column to appear bare on one side of the comparison. Rewrite WHERE YEAR(order_date) = 2026 as WHERE order_date >= '2026-01-01' AND order_date < '2027-01-01'. Expected result: the plan changes from a scan to a seek, usually by orders of magnitude on a large table.

When to use it. Whenever a query filters on a column that is indexed but the plan still shows a scan. This one idea accounts for a large share of all real-world slow queries.

Where to use it. Application queries and reports. Scenario: a dashboard filters WHERE UPPER(email) = ?. The function around the column disables the index. Storing a normalised column (or using a case-insensitive collation) restores the seek and takes the query from seconds to milliseconds.

When not to use it. SARGability is not the answer to every slow query — if the query genuinely needs most of the table, a scan is the correct plan and forcing a seek makes it worse. Do not rewrite for SARGability where the table is small or the column is not selective enough to benefit.

Best practices. Keep the column bare, compare it to a value of the same type (an implicit conversion disables the index just as effectively as a function), and avoid leading wildcards in LIKE. Avoid OR across different columns where you can — UNION ALL of two seekable queries is often much faster. And retire the myth that SELECT * is merely untidy: fetching unnecessary columns is what stops an index from being covering.


49. Statistics and the optimizer

🎚️ Level ⏱️ Time 🎯 After this chapter you can…
🔴 Expert 25 min Explain how the database guesses row counts · Keep statistics up to date · Recognize the symptoms of bad statistics

[!NOTE] 📌 In plain words: The optimizer does not look at your data before planning — it looks at statistics, a small summary of how values are distributed. Good statistics mean good plans. Stale statistics mean bad plans, and the query that ran in 2 seconds yesterday takes 4 minutes today.

🌍 Analogy: A delivery driver planning a route uses a traffic forecast, not live cameras on every street. If the forecast says “the bridge is clear” but the bridge has been closed for a month, the route will be terrible — through no fault of the driver’s logic.

49.1 📊 What statistics contain

A statistics object holds:

  • Row count for the table
  • Density — how many distinct values a column has
  • A histogram — a bar-chart-style summary of which values are common and which are rare, in up to 200 buckets (MSSQL)
-- 🟥 MSSQL: look at real statistics
SELECT
    s.name AS stats_name,
    sp.last_updated,
    sp.rows,
    sp.rows_sampled,
    sp.modification_counter          -- ← how many changes since the last update
FROM sys.stats s
CROSS APPLY sys.dm_db_stats_properties(s.object_id, s.stats_id) sp
WHERE s.object_id = OBJECT_ID('orders');

-- See the actual histogram (of the index from Chapter 46 — created here if it is missing)
IF NOT EXISTS (SELECT 1 FROM sys.indexes
               WHERE name = 'ix_orders_order_date' AND object_id = OBJECT_ID('orders'))
    CREATE INDEX ix_orders_order_date ON orders(order_date);
GO
DBCC SHOW_STATISTICS('orders', 'ix_orders_order_date');
-- 🟦 MySQL
SELECT table_name, table_rows, avg_row_length, data_length, index_length
FROM information_schema.tables
WHERE table_schema = 'ShopDB';

SELECT * FROM information_schema.statistics WHERE table_schema = 'ShopDB';

-- Histograms (MySQL 8.0+) — must be created explicitly
ANALYZE TABLE orders UPDATE HISTOGRAM ON status, order_date WITH 100 BUCKETS;
SELECT * FROM information_schema.column_statistics WHERE schema_name = 'ShopDB';

49.2 🔄 Keeping statistics current

-- 🟥 MSSQL
UPDATE STATISTICS orders;                            -- all stats on the table
UPDATE STATISTICS orders ix_orders_order_date;       -- one specific index
UPDATE STATISTICS orders WITH FULLSCAN;              -- read every row (accurate, slow)
EXEC sp_updatestats;                                 -- the whole database

-- Check the auto-update settings (both should be ON)
SELECT name, is_auto_create_stats_on, is_auto_update_stats_on
FROM sys.databases WHERE name = 'ShopDB';
-- 🟦 MySQL
ANALYZE TABLE orders;
ANALYZE TABLE orders, order_items, products;

[!WARNING] ⚠️ The auto-update threshold used to be a real problem in MSSQL. Before 2016 (or without trace flag 2371, a special server switch), statistics only auto-updated after roughly 20% of the rows changed. On a 100-million-row table that meant 20 million changes before the optimizer noticed. Modern versions use a much better sliding formula that reacts sooner on big tables, but on a large, actively-loaded table you should still update statistics on a schedule.

[!TIP] 💡 Rebuilding an index updates its statistics with a full scan, for free. So ALTER INDEX ... REBUILD gives you fresh stats as a side effect — but REORGANIZE does not. If you reorganize, update statistics separately.

49.3 🎯 Symptoms of bad statistics

Symptom Likely cause
Estimated 1 row, actual 2 million Stale stats, or a non-SARGable predicate the optimizer cannot estimate
A query suddenly got slow with no code change Stats went stale after a bulk load
Nested loops chosen for two huge tables Underestimated row counts
Hash/Sort spilling to disk Too little memory was reserved for the query
Plan varies wildly between runs Parameter sniffing (47.6) plus unevenly spread data
-- 🟥 MSSQL: find tables whose stats are stale
SELECT
    OBJECT_NAME(s.object_id) AS table_name,
    s.name AS stat_name,
    sp.last_updated,
    sp.rows,
    sp.modification_counter,
    CAST(100.0 * sp.modification_counter / NULLIF(sp.rows,0) AS DECIMAL(5,2)) AS pct_changed
FROM sys.stats s
CROSS APPLY sys.dm_db_stats_properties(s.object_id, s.stats_id) sp
WHERE sp.rows > 1000
  AND sp.modification_counter > sp.rows * 0.10
ORDER BY pct_changed DESC;

49.4 🧮 How the optimizer chooses a plan

1. Check the query's grammar, and look up every table and column name
2. Generate candidate plans (join orders, join algorithms, index choices)
3. For each candidate, ESTIMATE the cost using STATISTICS:
       cost ≈ (estimated rows) × (CPU cost) + (estimated pages) × (I/O cost)
4. Pick the cheapest candidate found within its time budget
5. Cache it for reuse

[!NOTE] 📌 Two things follow from this that every professional should remember:

  1. The optimizer makes an educated guess; it is not a mind reader. It cannot try every plan — on a 10-table join there are millions. It uses rules of thumb and stops when it finds something “good enough”.
  2. Every input it uses comes from statistics. Garbage in, garbage out. Most “the optimizer chose a stupid plan” complaints are really “the optimizer was given stale or missing statistics.”

49.5 🧪 Try it yourself

  1. Look at the statistics on orders and note when they were last updated.
  2. Insert 1000 rows, then check modification_counter.
  3. Run UPDATE STATISTICS / ANALYZE TABLE and compare a query plan before and after.
  4. In MSSQL, use DBCC SHOW_STATISTICS and read the histogram. Find the most common value.

🧭 In practice — statistics and the optimizer

How to use it. The optimiser chooses a plan from statistics — sampled summaries of how values are distributed. Refresh them with UPDATE STATISTICS (SQL Server) or ANALYZE TABLE (MySQL) when a plan is wrong. Expected result: estimated row counts move close to actual, and the plan usually corrects itself without any query change.

When to use it. When a query that was fast becomes slow without the SQL or the indexes changing — the classic symptom of stale statistics after a large load or a big delete.

Where to use it. Operational troubleshooting. Scenario: an overnight import adds two million orders. Until statistics catch up, the optimiser still believes the table is small, picks a nested-loop plan suited to a few rows, and the morning reports crawl. Refreshing statistics fixes it in seconds.

When not to use it. Do not update statistics reflexively as a cure-all — on a large table it is expensive and it invalidates cached plans, which causes a recompilation storm. And do not disable auto-update to “save” that cost without understanding what you are trading away.

Best practices. Leave automatic statistics updates on, and add scheduled maintenance for large or rapidly changing tables rather than relying on the automatic threshold. Beware parameter sniffing: a plan compiled for one parameter value can be badly wrong for another, which is why the same procedure can be fast for one customer and slow for another. OPTION (RECOMPILE) and OPTIMIZE FOR are the deliberate remedies — each with its own cost.


50. Partitioning and very large tables

🎚️ Level ⏱️ Time 🎯 After this chapter you can…
🔴 Expert 30 min Split a huge table into manageable pieces · Delete a year of data in milliseconds · Decide honestly whether you need partitioning

[!NOTE] 📌 In plain words: Partitioning splits one enormous table into physically separate pieces, while it still looks and behaves like a single table to your queries.

🌍 Analogy: A filing cabinet with one drawer per year. It is still “the archive”, and you still ask for a document the same way — but when you need something from 2024, you open one drawer instead of tipping the entire cabinet onto the floor.

50.1 🎯 When partitioning genuinely helps

✅ Good reasons ❌ Bad reasons
Archiving: drop last year’s data instantly by switching out a partition “It will make all my queries faster” (it will not)
Maintenance: rebuild indexes one partition at a time The table is only 5 million rows (just index it properly)
Partition elimination (skipping pieces that cannot match): queries with a date filter skip 90% of the data You do not filter on the partition key
Fast loading: load into a staging table, then switch it in instantly You hope it replaces good index design

[!WARNING] ⚠️ Partitioning is a manageability feature first, a performance feature second. A well-indexed 100-million-row table usually beats a badly-indexed partitioned one. Partition when your problem is managing the data — loading, archiving, purging — or when partition elimination genuinely removes most of the work.

50.2 🟥 MSSQL table partitioning

-- STEP 1: a partition FUNCTION defines the boundaries
CREATE PARTITION FUNCTION pf_order_date (DATE)
AS RANGE RIGHT FOR VALUES
    ('2024-01-01', '2025-01-01', '2026-01-01', '2027-01-01');
-- Creates 5 partitions: <2024, 2024, 2025, 2026, >=2027

-- STEP 2: a partition SCHEME says where each partition is stored (a filegroup = a named set of data files)
CREATE PARTITION SCHEME ps_order_date
AS PARTITION pf_order_date
ALL TO ([PRIMARY]);          -- or spread across separate filegroups/disks

-- STEP 3: create the table ON the scheme
CREATE TABLE orders_partitioned (
    order_id    INT NOT NULL,
    customer_id INT NOT NULL,
    order_date  DATE NOT NULL,
    status      VARCHAR(20) NOT NULL,
    CONSTRAINT pk_orders_part PRIMARY KEY (order_id, order_date)   -- 🔑 PK must include the partition key
) ON ps_order_date(order_date);

Partition elimination in action:

-- ✅ Reads ONE partition. The plan shows "Actual Partition Count: 1".
SELECT * FROM orders_partitioned
WHERE order_date >= '2026-01-01' AND order_date < '2027-01-01';

-- ❌ Reads ALL partitions — the filter is not on the partition key
SELECT * FROM orders_partitioned WHERE customer_id = 3;

The killer feature — instant archiving with SWITCH:

-- Move an entire partition into another table in MILLISECONDS.
-- It only changes the table's bookkeeping (metadata): no rows are copied.
CREATE TABLE orders_archive_2024 (
    order_id    INT NOT NULL,
    customer_id INT NOT NULL,
    order_date  DATE NOT NULL,
    status      VARCHAR(20) NOT NULL,
    CONSTRAINT pk_orders_arch PRIMARY KEY (order_id, order_date)
) ON ps_order_date(order_date);

ALTER TABLE orders_partitioned SWITCH PARTITION 2
    TO orders_archive_2024 PARTITION 2;

-- Then simply drop the archive table. Millions of rows gone, instantly, no log growth.

[!TIP] 💡 Compare that to DELETE FROM orders WHERE order_date < '2025-01-01' on 50 million rows: hours of runtime, an enormous transaction log, table locks, and blocked users. SWITCH does it in milliseconds. This alone justifies partitioning for large time-series tables.

-- Inspect the partitions
SELECT
    p.partition_number,
    p.rows,
    prv.value AS boundary_value
FROM sys.partitions p
JOIN sys.indexes i ON i.object_id = p.object_id AND i.index_id = p.index_id
LEFT JOIN sys.partition_schemes ps ON ps.data_space_id = i.data_space_id
LEFT JOIN sys.partition_range_values prv
       ON prv.function_id = ps.function_id AND prv.boundary_id = p.partition_number
WHERE p.object_id = OBJECT_ID('orders_partitioned') AND i.index_id <= 1;

50.3 🟦 MySQL partitioning

-- RANGE partitioning by year
CREATE TABLE orders_partitioned (
    order_id    INT NOT NULL,
    customer_id INT NOT NULL,
    order_date  DATE NOT NULL,
    status      VARCHAR(20) NOT NULL,
    PRIMARY KEY (order_id, order_date)          -- 🔑 must include the partition key
) ENGINE=InnoDB
PARTITION BY RANGE (YEAR(order_date)) (
    PARTITION p2023 VALUES LESS THAN (2024),
    PARTITION p2024 VALUES LESS THAN (2025),
    PARTITION p2025 VALUES LESS THAN (2026),
    PARTITION p2026 VALUES LESS THAN (2027),
    PARTITION pmax  VALUES LESS THAN MAXVALUE
);
-- ✅ MySQL: the other partition types
CREATE TABLE orders_by_hash (
    order_id    INT NOT NULL,
    customer_id INT NOT NULL,
    PRIMARY KEY (order_id, customer_id)
) PARTITION BY HASH(customer_id) PARTITIONS 8;                  -- even spread

CREATE TABLE orders_by_key (
    order_id    INT NOT NULL,
    customer_id INT NOT NULL,
    PRIMARY KEY (order_id, customer_id)
) PARTITION BY KEY(customer_id) PARTITIONS 8;                   -- MySQL's own hash

CREATE TABLE customers_by_region (
    customer_id INT NOT NULL,
    region_id   INT NOT NULL,
    PRIMARY KEY (customer_id, region_id)
) PARTITION BY LIST (region_id) (                               -- explicit value lists
    PARTITION p_asia   VALUES IN (1,2,3),
    PARTITION p_europe VALUES IN (4,5,6)
);
-- Managing partitions
ALTER TABLE orders_partitioned DROP PARTITION p2023;             -- instant purge

-- ADD PARTITION only works while there is no MAXVALUE catch-all partition.
-- With pmax in place (as here), split pmax instead:
ALTER TABLE orders_partitioned REORGANIZE PARTITION pmax INTO (
    PARTITION p2027 VALUES LESS THAN (2028),
    PARTITION pmax  VALUES LESS THAN MAXVALUE
);

-- Query one partition explicitly
SELECT * FROM orders_partitioned PARTITION (p2026);

-- Check elimination
EXPLAIN SELECT * FROM orders_partitioned WHERE order_date >= '2026-01-01';
-- Look at the "partitions" column in the output

[!WARNING] ⚠️ The MySQL partitioning rule that surprises everyone: every unique key (including the primary key) must contain all columns of the partitioning expression. This is why PRIMARY KEY (order_id, order_date) above is not optional. It also means you cannot have a simple UNIQUE (email) on a table partitioned by signup_date. This constraint rules partitioning out for many designs.

50.4 🧱 Other big-table strategies

Strategy What it is When
Archiving Move old rows to a separate table or database Almost always the first thing to try
Sharding Split across separate servers by key When one machine cannot hold the data
Columnstore (MSSQL) Stores data column by column, heavily compressed Reports over tables with 10M+ rows
Compression ROW/PAGE compression (MSSQL), COMPRESSED row format (MySQL) Large tables where reading from disk is the slow part
Summary tables Pre-aggregated rollups refreshed nightly Dashboards over huge history
Read replicas Send reports to a read-only copy on another server Reports slowing down everyday work
-- 🟥 MSSQL: compression can cut a large table's size by 60-70%
ALTER TABLE orders REBUILD WITH (DATA_COMPRESSION = PAGE);

-- Estimate the savings first
EXEC sp_estimate_data_compression_savings 'dbo', 'orders', NULL, NULL, 'PAGE';
-- 🟥 MSSQL: columnstore for analytics
CREATE TABLE sales_fact (
    sale_id     BIGINT        NOT NULL,
    sale_date   DATE          NOT NULL,
    product_id  INT           NOT NULL,
    quantity    INT           NOT NULL,
    net_amount  DECIMAL(12,2) NOT NULL
);
CREATE CLUSTERED COLUMNSTORE INDEX cci_sales_fact ON sales_fact;
-- Typically 10x compression and 10-100x faster aggregate scans

[!TIP] 💡 Compression is an underused win. Less data on disk means fewer pages read, which means more of your table fits in memory. On systems limited by disk speed, page compression frequently makes queries faster despite the CPU cost of decompression.

50.5 🎯 When to partition — the honest decision tree

Is the table causing you actual pain?
  └─ No  → 🛑 Do not partition. It is not a performance feature.
  └─ Yes ↓

Is the pain "queries are slow"?
  └─ Yes → 🎯 Fix INDEXES first (Ch 46). This solves it ~80% of the time.
  └─ No  ↓

Is the pain "purging/archiving old data takes hours and blocks users"?
  └─ Yes → ✅ PARTITION. This is what it is for. (SWITCH / DROP PARTITION)
  └─ No  ↓

Is the pain "maintenance windows are too long"?
  └─ Yes → ✅ PARTITION — rebuild one partition at a time.
  └─ No  ↓

Do nearly all queries filter on ONE obvious column (usually a date)?
  └─ Yes → ✅ Partition on it; you get elimination as a bonus.
  └─ No  → 🛑 You will get all the cost and none of the benefit.

[!CAUTION] 🐛 Common mistake: partitioning on a column the queries do not filter on. You get zero partition elimination, every query still touches every partition, and you have added real complexity to your backups, indexes, and constraints. Partition on the column in your WHERE clause, or do not partition.

50.6 🧪 Try it yourself

  1. Create a partitioned copy of orders by year in your engine.
  2. Run a date-filtered query and confirm partition elimination in the plan.
  3. Run a customer_id query and confirm it reads all partitions. Explain why.
  4. In MSSQL, SWITCH a partition out to an archive table and time it.
  5. In MySQL, DROP PARTITION for an old year and time it against an equivalent DELETE.

🧭 In practice — partitioning and very large tables

How to use it. Split one logical table into physical partitions by a key — almost always a date. SQL Server uses a partition function and scheme; MySQL uses PARTITION BY RANGE. Expected result: the engine reads only the relevant partitions (partition elimination), and whole partitions can be switched in or out almost instantly.

When to use it. At genuinely large scale — hundreds of millions of rows — and above all for manageability: archiving last year’s data by switching out a partition rather than running a DELETE that takes hours and floods the transaction log.

Where to use it. Data warehouses and high-volume logging. Scenario: an orders table partitioned by month. The year-end archive becomes a metadata operation measured in milliseconds, instead of a DELETE of 50 million rows that blocks writers and doubles the log file.

When not to use it. Do not partition for performance on a table of a few million rows — a good index will beat it, and partitioning adds real operational complexity. Do not partition on a column your queries do not filter by, or you get no elimination and all of the cost. Note that partitioning is an Enterprise-edition feature on older SQL Server releases, and that MySQL partitioning carries restrictions — notably that every unique key must include the partitioning column.

Best practices. Choose the partition key from your query patterns and your archiving policy, not from what looks tidy. Verify elimination is actually happening by reading the plan; a partitioned table whose queries touch every partition is strictly worse than an unpartitioned one. Plan the boundary-maintenance job up front — partitioned tables that run out of future partitions fail in unpleasant ways.


Part index Prerequisites Previous Next Full course