SQL Server / Advanced / Lesson 21
Rehearse an online index operation
Evaluate edition support, locking, space, and query evidence before an index rollout.
On this page
Lesson goals
- Explain the scope and limits of ONLINE index creation.
- Inspect a disposable index definition and verify application behavior.
- Plan capacity, locking, and recovery for a real operation.
- Evaluate SQL Server online index support, locking and resource conditions for an exact operation.
- Rehearse index acceptance using equivalent results and representative workload measurements.
Define the performance hypothesis
An index on customer and order time may support a particular report, but it also adds storage and write maintenance. Capture the representative query, parameters, data distribution, current plan, and workload before proposing it. Define the expected improvement and correctness checks. An online operation is an execution option for an index change, not proof that the index is needed or that the application will experience no impact.
Create a disposable starting table
The following illustrative T-SQL is for a new isolated SQL Server 2019 lab. It creates a small synthetic table and two rows. Do not run it against a configured database. A real rehearsal needs representative data volume, concurrent activity, available disk and transaction-log capacity, the exact server edition, and a documented stopping and recovery procedure.
CREATE TABLE dbo.lab_order (
id int PRIMARY KEY, customer_id int NOT NULL, placed_at datetime2 NOT NULL
);
INSERT INTO dbo.lab_order (id, customer_id, placed_at) VALUES
(1, 10, '2026-01-01T09:00:00'), (2, 10, '2026-01-02T09:00:00');
Both orders belong to customer 10 on consecutive dates. This fixture establishes the table and data only; it is too small to establish a performance benefit.
Request online creation and inspect
The next example requests ONLINE=ON, then queries index metadata. Online index operations are not available in every SQL Server edition and have operation-specific restrictions. If the deployed edition or table does not support the request, the operation may fail. Review the official guidance for the exact version and edition before testing; the public course does not execute this DDL.
CREATE INDEX IX_lab_order_customer_placed
ON dbo.lab_order (customer_id, placed_at)
WITH (ONLINE = ON);
SELECT name, type_desc FROM sys.indexes
WHERE object_id = OBJECT_ID(N'dbo.lab_order') ORDER BY name;
If creation succeeds, the catalog query can show the new index alongside existing indexes. Actual support, metadata, duration, and locking depend on the environment and are not asserted.
Account for concurrent work
Online does not mean lock-free or resource-free. The operation can require schema locks at particular phases, temporary space, transaction-log capacity, and additional work while maintaining structures. Long transactions or concurrent operations can change the impact. Test with representative traffic and monitor waits, storage, log growth, and application latency. Do not assume that an online option is supported merely because another edition or version supports it.
Compare plans and recovery
After a successful lab change, inspect the index definition and compare the representative query’s results, plan, latency, and resource use with the baseline. Include insert and update costs and verify behavior if the operation is interrupted. Document how the team will stop, repair, or recover under the chosen procedure. A catalog entry alone does not prove the index improves the complete workload or that the rollout was safe.
Define the workload hypothesis
An index operation should start from a specific query and workload hypothesis, not a desire to create an index merely because a plan contains a scan. Record the query’s intended population, row grain, ordering and representative parameters. A candidate key such as (CustomerId, CreatedAt) may help equality on the customer followed by a date range, but its benefit depends on data distribution, existing indexes and the complete plan. Verify the same result keys before comparing performance.
The two-row training fixture can show syntax and compatibility but cannot establish production benefit. A representative isolated rehearsal should include common and rare parameter values, concurrent reads and writes, expected table size and resource limits. Record SQL Server version, edition, compatibility level and the exact table and index definition. The examples are synthetic and reasoned; no SQL Server or index operation was executed.
Interpret ONLINE and locking correctly
ONLINE=ON requests an online index operation where the specific SQL Server version, edition, object and operation support it. It does not mean the operation is free of locks or operational impact. SQL Server can require short-duration locks, including schema locks at phases of an online operation; long-running transactions can delay progress or later requests. Check the documented restrictions and actual environment before relying on an online option.
The operation can consume CPU, memory, storage and transaction-log capacity, and maintaining source and target structures can add work to concurrent writes. Monitor resource use, blocking and application latency during an authorized rehearsal. Define a stop threshold and responsible owner in advance. If an explicit option is unsupported, handle the failure under the plan rather than silently assuming an unreviewed offline fallback.
Plan resumability and recovery
Some SQL Server online index operations support RESUMABLE=ON under documented version and operation conditions. A resumable operation can be paused and resumed, but it introduces a distinct operational state that must be monitored and managed. Verify the supported syntax, permissions, duration settings and implications for the exact deployment; do not extrapolate one supported rebuild to every index operation. Record who can pause, resume or abort and what happens to resources while paused.
An index operation and its surrounding application rollout need a recovery plan. A rollback or abort is not instantaneous by assumption and may consume resources. Maintain appropriate backup and restore readiness, and do not confuse an index’s availability with a complete disaster-recovery strategy. Rehearse the decision to stop, the expected intermediate state and the path back to a known configuration in an isolated environment.
Compare reads and writes under the same contract
Capture a baseline for the same query text, parameters, data distribution and concurrency, then compare after the candidate index. Measure logical reads, elapsed and CPU time, plan shape and relevant waits, plus insert, update and delete cost, log growth and storage. A candidate that improves one selective read while harming a critical write may not satisfy the workload objective. Repeat trials and record cache conditions rather than attributing one timing difference to the index.
An estimated plan is not an actual execution, while collecting an actual plan runs the query and consumes resources. Inspect estimated versus observed rows and execution counts; skew and implicit conversions may explain a mismatch. A seek is not automatically cheaper than a scan when it qualifies many rows and triggers lookups. Test correctness, boundaries and tenant filtering before accepting any faster result.
Rehearse stop and acceptance criteria
Define measurable acceptance criteria before the operation: result correctness, representative read benefit, acceptable write and log impact, blocking duration and recovery readiness. Include a long-running transaction holding metadata or schema-related locks, an unsupported option and a resource threshold in the exercise. Verify that the team can identify the blocker and stop safely under an authorized runbook without assuming ONLINE removes every dependency.
After the operation, confirm index definition and state, query results and workload metrics. Check the effect on replicas and maintenance plans where applicable, and document any unexpected lock or resource consumption. Do not make production changes from these illustrative examples. A successful CREATE INDEX message is one event; the index is valuable only if the measured workload benefits within the agreed operational budget.
20 worked examples
1. Candidate key
Problem: Which index order is a plausible starting point?
- The leading key has an equality predicate.
- The next key supports the stated date range hypothesis.
-- Query: CustomerId=@id AND CreatedAt>=@start AND CreatedAt<@end.
-- Candidate: (CustomerId,CreatedAt).
A candidate, subject to actual workload validation.
The scenario and decision are reasoned; no index operation was executed.
Why this result follows: Key order must be measured with representative data and existing indexes.
2. Tiny fixture
Problem: Can two rows prove a production speedup?
- Two rows do not represent production distribution or concurrency.
- No before-and-after workload measurement is stated.
Lab table: 2 rows.
Candidate index creation succeeds.
No representative workload measured.
No; the fixture establishes syntax and logic only.
The scenario and decision are reasoned; no index operation was executed.
Why this result follows: Index benefit requires representative before-and-after workload evidence, not a tiny syntax fixture.
3. Online option
Problem: Does ONLINE=ON mean no locks?
- ONLINE requests a supported online operation.
- Schema and other locks can still be needed during phases.
-- Illustrative operation; support depends on exact SQL Server environment.
CREATE INDEX IX_Lab ON dbo.LabOrder(CustomerId,CreatedAt) WITH (ONLINE=ON);
No; online operations can still require locks.
The scenario and decision are reasoned; no index operation was executed.
Why this result follows: The option reduces certain blocking but does not eliminate operational dependencies.
4. Unsupported online operation
Problem: What if the requested online option is unsupported?
- The requested option is unsupported in this scenario.
- The team has not approved an alternative offline operation.
-- Exact SQL Server edition and operation do not support requested ONLINE=ON.
-- CREATE INDEX is attempted with ONLINE=ON.
Handle the failure under the reviewed plan.
The scenario and decision are reasoned; no index operation was executed.
Why this result follows: Do not assume an unreviewed fallback has equivalent impact.
5. Long transaction
Problem: Why can an online operation wait?
- The operation still needs locks during its phases.
- A retains the conflicting resource in the stated schedule.
Session A holds a long-running transaction with a conflicting schema-related lock.
Session B starts an online index operation.
B can wait for the incompatible resource.
The scenario and decision are reasoned; no index operation was executed.
Why this result follows: An online operation still needs locks, so incompatible resources can delay its progress.
6. Concurrent writes
Problem: Why can writes slow during an online index operation?
- The source and target structures both need maintenance.
- The same write workload competes for resources during the operation.
Online index build maintains source and target structures.
Application continues inserts and updates.
Concurrent writes can incur additional work.
The scenario and decision are reasoned; no index operation was executed.
Why this result follows: Online availability does not mean zero write overhead.
7. Log capacity
Problem: Why check transaction-log capacity before rehearsal?
- Index operations can generate significant log activity.
- The stated capacity may be insufficient.
Estimated operation requires substantial logged work.
Available log capacity is limited.
Establish a resource budget and stop threshold.
The scenario and decision are reasoned; no index operation was executed.
Why this result follows: Operational readiness includes storage and log resources.
8. Stop threshold
Problem: What happens when the agreed blocking threshold is exceeded?
- The observed duration exceeds the predefined limit.
- Continuing would violate the stated acceptance condition.
Stop criterion: blocking exceeds 30 seconds.
Observed blocking in rehearsal: 45 seconds.
Follow the reviewed stop procedure.
The scenario and decision are reasoned; no index operation was executed.
Why this result follows: A threshold makes the operational decision explicit before pressure arises.
9. Resumable eligibility
Problem: Can RESUMABLE=ON be assumed for every index change?
- Resumability applies only to supported operations and conditions.
- The scenario lacks the required environment evidence.
Requested operation: RESUMABLE=ON.
Exact version, edition and operation support not yet checked.
No; verify the documented support and prerequisites.
The scenario and decision are reasoned; no index operation was executed.
Why this result follows: A feature name is not proof that every target can use it.
10. Paused operation
Problem: Why monitor an operation after pausing it?
- Paused is a distinct operational state, not completion.
- A later decision is needed to resume or abort under the runbook.
A supported resumable index operation is paused.
The team has not decided whether to resume or abort.
Track its state, resource implications and owner.
The scenario and decision are reasoned; no index operation was executed.
Why this result follows: Resumability requires lifecycle management as well as syntax.
11. Result equivalence
Problem: Why compare exact query results before timing?
- The candidate includes an extra order.
- A timing comparison would answer a different business question.
Baseline returns order ids 10 and 11.
Candidate query accidentally returns 10, 11 and 12.
The candidate is not semantically equivalent.
The scenario and decision are reasoned; no index operation was executed.
Why this result follows: Correctness is a prerequisite for a valid performance comparison.
12. Read improvement
Problem: What is the read change in this synthetic test?
- Subtracting 400 from 1000 gives 600.
- The stated comparison uses the same query and inputs.
Before: 1000 logical reads per execution.
After: 400 logical reads per execution.
Same query and inputs.
600 fewer logical reads per execution.
The scenario and decision are reasoned; no index operation was executed.
Why this result follows: The reduction is evidence for this tested case, not every workload.
13. Write regression
Problem: Why can a read improvement be unacceptable?
- The read improves under the synthetic test.
- The update regression exceeds the allowed twenty percent.
Read latency improves 30%.
Critical update latency rises 80%.
Write budget allows at most 20% increase.
The candidate misses the stated write budget.
The scenario and decision are reasoned; no index operation was executed.
Why this result follows: Acceptance must include the complete workload tradeoff.
14. Parameter skew
Problem: Why test both customer values?
- Customer one selects many more rows.
- Customer two selects only two rows, making that parameter substantially more selective in this fixture.
Customer 1 has 900 orders.
Customer 2 has 2 orders.
Both use the same query shape.
The candidate may behave differently across the skew.
The scenario and decision are reasoned; no index operation was executed.
Why this result follows: Representative parameters expose tradeoffs hidden by one execution.
15. Scan versus seek
Problem: Is a seek always cheaper than a scan?
- The scan reads the small table required by the query.
- The seek also performs the stated lookup work.
Synthetic plan A: scan 3 rows.
Plan B: seek plus 3 lookups.
Query needs all 3 rows.
No; compare the complete work.
The scenario and decision are reasoned; no index operation was executed.
Why this result follows: An operator label alone does not establish total cost.
16. Estimated and actual
Problem: What does 100 estimated versus 100000 actual rows suggest?
- Actual rows are one thousand times the estimate.
- Several causes can produce that mismatch.
Synthetic operator: estimated rows 100; actual rows 100000.
Investigate skew, statistics and predicate behavior.
The scenario and decision are reasoned; no index operation was executed.
Why this result follows: The discrepancy is evidence to investigate, not proof of one remedy.
17. Cache difference
Problem: Can cold versus warm timings isolate the index effect?
- The cache state differs between runs.
- Other uncontrolled factors may also affect elapsed time.
Before: cold cache, 300 ms.
After: warm cache, 40 ms.
Other conditions uncontrolled.
No; repeat comparable tests and record conditions.
The scenario and decision are reasoned; no index operation was executed.
Why this result follows: One timing pair does not isolate the proposed change.
18. Actual plan cost
Problem: Does an actual plan collect runtime data without execution?
- Actual plan data accompanies the executed statement.
- The query can use CPU and I/O or wait on locks.
An isolated SELECT runs with actual execution plan collection.
No; the SELECT executes and consumes resources.
The scenario and decision are reasoned; no index operation was executed.
Why this result follows: Budget and authorize diagnostic execution because the query performs real resource-consuming work.
19. Final definition
Problem: What should be checked after CREATE INDEX succeeds?
- The success message indicates an operation completed.
- It does not establish the intended definition or workload benefit by itself.
Operation reports success.
Expected index key: CustomerId,CreatedAt.
Workload verification has not run.
Confirm the definition and test workload and results.
The scenario and decision are reasoned; no index operation was executed.
Why this result follows: Acceptance requires independent correctness and performance evidence.
20. Replica impact
Problem: Why inspect replicas during a large index operation?
- The operation produces work that must be processed downstream.
- The observed lag can affect recovery or read objectives.
Primary performs an index operation with substantial logged work.
Secondary apply lag rises in the rehearsal.
Assess replication impact against the agreed threshold.
The scenario and decision are reasoned; no index operation was executed.
Why this result follows: Operational acceptance includes effects beyond the primary query.
Common errors and fixes
ONLINE index creation is rejected.
- Why it happens
- The edition, operation, or table does not support the requested option.
- How to fix it
- Review the target-specific documentation and choose an approved alternative.
- Prevent it next time
- Test the exact version and edition in an isolated rehearsal.
Application requests wait during an online operation.
- Why it happens
- The plan assumed online meant no schema locks.
- How to fix it
- Inspect authorized wait evidence and follow the stopping procedure.
- Prevent it next time
- Rehearse with concurrent transactions and monitor locks.
The new index increases write cost without helping the report.
- Why it happens
- The index was added without a representative workload measurement.
- How to fix it
- Compare plans and workload costs, then use the approved change process.
- Prevent it next time
- Record a baseline and test reads and writes together.
20 practice exercises
1. Does ONLINE=ON guarantee that the operation has no locks?
Show hint
Distinguish online availability from lock-free execution.
Show worked solution
No. Online operations can require schema locks and consume space, log, and processing resources. Test the specific deployment and concurrency.
ONLINE=ON does not guarantee zero locks or impact. Supported operations can require schema locks and consume CPU, log and storage; test the exact version, operation and concurrent workload.
Check your solution
- Online operations can require locks.
- Measure resource and concurrency effects.
2. What evidence shows that the lab index is beneficial?
Show hint
Compare representative workload before and after with identical semantics.
Show worked solution
The tiny fixture cannot prove benefit. Compare the same representative query and write workload before and after, including correctness, plan, latency, and resource costs.
The tiny fixture cannot prove benefit. Compare the same representative read and write workload before and after, verify correct results and measure plan, latency and resource costs.
Check your solution
- Verify equivalent results.
- Measure both read benefit and write cost.
3. Does ONLINE=ON guarantee that an index operation takes no locks?
Show hint
Trace the supported operation, workload evidence and predefined operational threshold.
Show worked solution
No. A supported online operation can still require schema or other locks and consume resources. Test the exact operation and concurrency, and set blocking and resource stop thresholds.
Check your solution
- Online does not mean lock-free
- Test locks and resources
4. A two-row fixture successfully creates an index. Does that prove production benefit?
Show hint
Trace the supported operation, workload evidence and predefined operational threshold.
Show worked solution
No. It can demonstrate syntax and result behavior but not representative performance. Compare the same query and write workload on suitable data with measured reads, latency and resource costs.
Check your solution
- Two rows do not prove performance
- Measure representative read and write work
5. A query has CustomerId equality and CreatedAt range. What key is a reasonable hypothesis?
Show hint
Trace the supported operation, workload evidence and predefined operational threshold.
Show worked solution
Evaluate (CustomerId,CreatedAt) as a candidate because equality leads into the date range. Verify existing indexes, selectivity, ordering and write cost before deciding.
Check your solution
- CustomerId is a leading candidate
- CreatedAt follows for the range
6. A requested ONLINE=ON option is unsupported on the target. What should the team do?
Show hint
Trace the supported operation, workload evidence and predefined operational threshold.
Show worked solution
Stop and follow the reviewed change plan rather than silently assuming an offline alternative is equivalent. Verify the exact SQL Server version, edition, object and operation support.
Check your solution
- Treat unsupported option as failure
- Review any alternative separately
7. A long-running transaction holds a conflicting resource while an online index operation starts. Can it wait?
Show hint
Trace the supported operation, workload evidence and predefined operational threshold.
Show worked solution
Yes. Online operations can require locks during their phases, and an incompatible resource can delay progress. Inspect the blocker and follow the authorized stop and resolution procedure.
Check your solution
- Online operation can wait
- Investigate the blocking transaction
8. Why can concurrent inserts slow during an online index build?
Show hint
Trace the supported operation, workload evidence and predefined operational threshold.
Show worked solution
The operation can maintain source and target structures while competing for CPU, I/O and log resources. Measure application write latency and resource use during a representative rehearsal.
Check your solution
- Writes can incur extra maintenance
- Measure application impact
9. Available log capacity is limited before an index operation. What should be done?
Show hint
Trace the supported operation, workload evidence and predefined operational threshold.
Show worked solution
Estimate and monitor the logged work and establish an agreed capacity and stop threshold before proceeding. A successful online option does not remove transaction-log requirements.
Check your solution
- Check log capacity
- Define a stop threshold
10. A rehearsal stop threshold is 30 seconds blocking and observed blocking is 45 seconds. What follows?
Show hint
Trace the supported operation, workload evidence and predefined operational threshold.
Show worked solution
Follow the predefined stop procedure because the observed duration exceeds the limit. Record the blocker and outcome rather than changing acceptance criteria under pressure.
Check your solution
- Threshold is exceeded
- Execute the reviewed stop procedure
11. Does RESUMABLE=ON apply to every SQL Server index operation?
Show hint
Trace the supported operation, workload evidence and predefined operational threshold.
Show worked solution
No. Support depends on the exact operation, version, edition and documented prerequisites. Verify the deployed environment and rehearse pause, resume and abort decisions before relying on it.
Check your solution
- Check exact support
- Rehearse lifecycle operations
12. A resumable operation is paused. Is it completed and free of all management needs?
Show hint
Trace the supported operation, workload evidence and predefined operational threshold.
Show worked solution
No. Paused is a distinct state that needs an owner, monitoring and a decision to resume or abort. Review the documented resource implications for the actual version.
Check your solution
- Paused is not complete
- Assign lifecycle ownership
13. A candidate query is faster but returns an extra order. Is it a valid index comparison?
Show hint
Trace the supported operation, workload evidence and predefined operational threshold.
Show worked solution
No. The query answers a different population. Correct the predicate and verify exact identifiers and boundaries before comparing plans or timings.
Check your solution
- Result keys must match
- Do not accept the extra order
14. Logical reads fall from 1000 to 400 per execution in a controlled fixture. What is the reduction?
Show hint
Trace the supported operation, workload evidence and predefined operational threshold.
Show worked solution
The tested query uses 600 fewer logical reads per execution. Evaluate latency, write cost and representative parameters before generalizing that result to the workload.
Check your solution
- Reduction is 600 reads
- Assess broader workload impact
15. Read latency improves 30% but update latency rises 80% against a 20% write budget. Is the candidate acceptable?
Show hint
Trace the supported operation, workload evidence and predefined operational threshold.
Show worked solution
Not under the stated budget. The write regression exceeds the allowed increase even though reads improve; consider another design or an explicitly approved change to objectives.
Check your solution
- Read improvement is 30%
- Write budget is exceeded
16. A customer with 900 orders and another with 2 use the same query. Why test both?
Show hint
Trace the supported operation, workload evidence and predefined operational threshold.
Show worked solution
Their selectivity differs greatly, so a plan or index can behave differently for each. Include common and rare values and assess total workload rather than one favorable parameter.
Check your solution
- Data distribution is skewed
- Test both parameter cases
17. A plan scans three rows while another seeks and performs three lookups. Is the seek automatically better?
Show hint
Trace the supported operation, workload evidence and predefined operational threshold.
Show worked solution
No. The table is tiny and all rows are required, so the scan can be competitive. Compare the complete actual work and workload instead of relying on the operator label.
Check your solution
- Scan can be reasonable
- Compare total work
18. An operator estimates 100 rows and observes 100000. What should be investigated?
Show hint
Trace the supported operation, workload evidence and predefined operational threshold.
Show worked solution
Inspect statistics, parameter skew, predicate correlation and conversions, then relate the mismatch to plan choices. Do not force an index solely because the estimate is wrong.
Check your solution
- Investigate cardinality causes
- Inspect plan consequences
19. Before timing uses a cold cache and after timing uses a warm cache. What limits the result?
Show hint
Trace the supported operation, workload evidence and predefined operational threshold.
Show worked solution
Cache state differs, so the time difference cannot be attributed solely to the index. Repeat comparable trials and record data, parameters, concurrency and cache conditions.
Check your solution
- Cache conditions differ
- Repeat comparable measurements
20. An online index operation succeeds but replica apply lag exceeds the agreed limit. What decision follows?
Show hint
Trace the supported operation, workload evidence and predefined operational threshold.
Show worked solution
Follow the predefined stop or recovery procedure and assess the downstream impact. A success message on the primary does not override the agreed operational threshold.
Check your solution
- Replica threshold is exceeded
- Follow the reviewed response
Key takeaways
- Check online-index support for the exact edition and operation.
- Online work can still use locks, disk, log, and CPU.
- Measure the complete workload and rehearse recovery.
- ONLINE=ON does not mean lock-free or impact-free.
- A tiny fixture cannot prove workload benefit.
- Define stop criteria and evaluate write, log and replica effects as well as reads.