📁 Sangam Dhakal - Portfolio v2.0 - Netscape Navigator 4.0
_
□
×

📚 Interview question

What are columnstore indexes in SQL Server? Explain rowgroups, segments, the delta store and batch mode, when you would put a non-clustered columnstore index on an OLTP table, and what it costs.

Covers columnstore storage (rowgroups, column segments, compression, segment elimination), the delta store and tuple mover, batch mode execution, clustered versus non-clustered columnstore, real-time operational analytics and the trade-offs.

Mid-Level Theory Intermediate analytics batch-mode columnstore data-warehouse indexes sql-server

🎯 Key points

  • Stores data by column in rowgroups of up to 1,048,576 rows, each column a compressed segment
  • Typical 5-10x compression; reads only the referenced columns
  • Segment elimination via per-segment min/max metadata
  • Delta store (rowstore) takes trickle inserts; tuple mover compresses closed rowgroups
  • Bulk loads of 102,400+ rows go straight to compressed rowgroups
  • Batch mode processes about 900 rows per operator call; batch mode on rowstore since SQL Server 2019
  • Updatable non-clustered columnstore on an OLTP table for real-time operational analytics
  • Costs: deletes are logical (delete bitmap), singleton lookups and updates are slow, maintenance via REORGANIZE

⏱ 30-second answer

A columnstore index stores data by column instead of by row. Rows are grouped into rowgroups of up to about a million rows, and each column in a rowgroup is a compressed segment (often 5–10x smaller). Queries read only the columns they need, skip segments using min/max metadata (segment elimination), and run in batch mode, processing about 900 rows per operator call instead of one.

  • Clustered columnstore: the table itself; ideal for fact tables and large history.
  • Non-clustered columnstore on an OLTP rowstore table: run aggregations on live data without a separate warehouse (real-time operational analytics).

Small inserts land in a rowstore delta store until compressed. Trade-off: huge scans become cheap, but point lookups, updates and deletes are more expensive.

🗣 Full answer (senior)

How I would answer this in an interview

"A columnstore index flips the storage model. Instead of pages full of whole rows, SQL Server takes up to about a million rows at a time, a rowgroup, and stores each column of that rowgroup separately as a compressed segment. Because values in one column are similar, compression is typically five to ten times better than rowstore. A query that sums Total by month over 500 million rows reads only the Total and OrderDate segments, and each segment has min and max metadata, so whole rowgroups outside the date range are skipped without reading them. On top of that it runs in batch mode, where each operator processes a batch of around 900 rows using vectorised code instead of one row at a time. That's how a scan of hundreds of millions of rows goes from minutes to a second or two.

There are two flavours. A clustered columnstore is the table: the right choice for a fact table or a large append-mostly history table. A non-clustered columnstore sits on an ordinary rowstore OLTP table, which keeps its B-tree indexes for the application, while reports and dashboards aggregate the live data through the columnstore. That's real-time operational analytics, and it can remove the need for a nightly copy to a reporting database.

The mistake I see is treating it as a free speed-up. Trickle inserts go into a rowstore delta store first, deletes only mark rows in a delete bitmap, and updates are delete plus insert, so a heavily updated columnstore fills up with deleted rows and open delta stores and gets slower. Singleton lookups are poor too. For example, at [company] we [added a non-clustered columnstore to the orders table for the operations dashboard, and the dashboard query went from about [40] seconds to under [2], with a [small] increase in insert latency]. Columnstore is for reading many rows and few columns; B-trees are for finding a few rows."


Rowstore vs columnstore

Rowstore B-tree Columnstore
Unit 8 KB page of rows Rowgroup (up to 1,048,576 rows) of column segments
Best for Seeks, singleton reads, updates Scans and aggregations over many rows
Compression Optional row/page compression Columnstore compression, typically 5-10x
Execution Row mode (batch mode on rowstore possible since 2019) Batch mode
Deletes Physical Logical (delete bitmap) until rebuilt

Clustered vs non-clustered columnstore

Clustered columnstore (CCI) Non-clustered columnstore (NCCI)
What it is The table Secondary index on a rowstore table
Fits Fact tables, history, logs OLTP table with analytic queries on live data
Extra B-trees Allowed (for seeks and unique keys) The table's own indexes remain
Write cost Delta store, bulk load path Each write also maintains the NCCI

Production example

A sales table with 300 million rows took 38 seconds and 2.1 million logical reads for a monthly revenue report. A clustered columnstore cut storage from 60 GB to 9 GB, and the same query ran in 1.4 seconds in batch mode, reading segments for 3 columns and eliminating about 90% of rowgroups by date.

🔍 What the interviewer is checking

Checks whether the candidate understands columnstore internals well enough to know when it transforms performance and when it hurts.

Green flags

  • Explains rowgroups, segments, compression and segment elimination
  • Knows the delta store, tuple mover and 102,400-row bulk threshold
  • Describes batch mode and real-time operational analytics with an NCCI
  • Names write and maintenance costs

Red flags

  • "Columnstore makes every query faster"
  • Unaware of delete bitmaps and delta stores
  • Suggests it for singleton OLTP lookups

📚 Learn in depth

1. Storage layout

Rowgroup 1 (1,048,576 rows)      Rowgroup 2 ...        Delta store (rowstore B-tree)
 ├─ segment: OrderId                                  open: receives trickle inserts
 ├─ segment: OrderDate  min=2026-01-01 max=2026-01-09
 ├─ segment: CustomerId
 └─ segment: Total

Each segment is encoded (dictionary or value encoding) then compressed. Metadata in sys.column_store_segments holds min/max values per segment; sys.dm_db_column_store_row_group_physical_stats shows each rowgroup's state, row count and deleted rows.

2. Getting data in

  • Bulk insert of 102,400 rows or more per batch: goes straight into a compressed rowgroup.
  • Smaller inserts: go to a delta store (a rowstore). When it reaches the rowgroup size it is CLOSED, and the background tuple mover compresses it.
  • Deletes: compressed rows are marked in a delete bitmap; delta-store rows are deleted physically.
  • Updates: delete plus insert.

Too many small loads produce many small, poorly compressed rowgroups (trimmed rowgroups). ALTER INDEX ... REORGANIZE compresses closed delta stores and merges small rowgroups; REBUILD recreates everything and removes deleted rows.

3. Segment elimination and ordering

If data is loaded roughly in date order, each rowgroup covers a narrow date range and a date filter skips most of them. SQL Server 2022 adds ordered clustered columnstore (ORDER (col)) to sort data on build; earlier versions relied on loading order or building from a clustered rowstore index.

4. Batch mode

Row mode calls each operator once per row. Batch mode passes a batch of about 900 rows with column vectors, reducing per-row CPU dramatically for scans, filters, aggregates, hash joins and window functions. Since SQL Server 2019 (compatibility level 150) and in Azure SQL, batch mode on rowstore lets analytic queries use batch mode even without a columnstore.

5. Real-time operational analytics

A non-clustered columnstore on an OLTP table is updatable (since SQL Server 2016). Options to limit its write cost:

  • A filtered NCCI (WHERE Status = 'Closed') so hot rows stay out.
  • COMPRESSION_DELAY so rows stay in the delta store for N minutes while they are still being updated.

6. Licensing and editions

Since SQL Server 2016 SP1 columnstore is available in all editions, though Standard limits batch mode parallelism (DOP 2) and memory; Azure SQL supports it on all purchasing models except the smallest Basic and S0-S2 tiers.

Try it yourself

  1. Load 20 million rows into a rowstore table and a clustered columnstore copy; compare sizes in sys.dm_db_partition_stats.
  2. Run a GROUP BY month aggregate on both with SET STATISTICS IO, TIME ON; note segment reads and "segments skipped" in the messages.
  3. Insert 1,000 rows at a time into the columnstore and inspect rowgroup states in sys.dm_db_column_store_row_group_physical_stats.
  4. Delete 10% of rows and look at deleted_rows; then REORGANIZE and REBUILD and compare.
  5. Add an NCCI with COMPRESSION_DELAY = 30 to an OLTP-style table and measure insert latency before and after.

💻 Code

A clustered columnstore for history, and a non-clustered columnstore on a live OLTP table.

-- Fact table: the columnstore is the table
CREATE TABLE dbo.SalesHistory
(
    SaleId      bigint        NOT NULL,
    SaleDate    date          NOT NULL,
    StoreId     int           NOT NULL,
    ProductId   int           NOT NULL,
    Quantity    int           NOT NULL,
    Amount      decimal(12,2) NOT NULL,
    INDEX CCI_SalesHistory CLUSTERED COLUMNSTORE
);
-- SQL Server 2022+: ORDER (SaleDate) on the CCI improves segment elimination by date

-- OLTP table keeps its B-trees; analytics use the NCCI.
-- Rows stay in the delta store for 30 minutes while they are still being updated.
CREATE NONCLUSTERED COLUMNSTORE INDEX NCCI_Orders_Analytics
    ON dbo.Orders (OrderDate, CustomerId, Status, Total)
    WITH (COMPRESSION_DELAY = 30);

SET STATISTICS IO, TIME ON;
SELECT DATEFROMPARTS(YEAR(OrderDate), MONTH(OrderDate), 1) AS month_start,
       SUM(Total) AS revenue
FROM dbo.Orders
WHERE OrderDate >= '2026-01-01'
GROUP BY DATEFROMPARTS(YEAR(OrderDate), MONTH(OrderDate), 1);
-- Look for "segment reads" and "segment skipped" and Actual Execution Mode = Batch

-- Health check: open delta stores, trimmed rowgroups, deleted rows
SELECT OBJECT_NAME(object_id) AS table_name, row_group_id, state_desc,
       total_rows, deleted_rows, trim_reason_desc
FROM sys.dm_db_column_store_row_group_physical_stats
WHERE object_id = OBJECT_ID(N'dbo.SalesHistory')
ORDER BY row_group_id;

ALTER INDEX CCI_SalesHistory ON dbo.SalesHistory REORGANIZE WITH (COMPRESS_ALL_ROW_GROUPS = ON);

Loading in batches of at least 102,400 rows from .NET sends data straight to compressed rowgroups.

namespace Sales.Loading;

using System.Data;
using Microsoft.Data.SqlClient;

public sealed class SalesLoader(string connectionString)
{
    public async Task LoadAsync(IDataReader rows, CancellationToken ct)
    {
        await using var conn = new SqlConnection(connectionString);
        await conn.OpenAsync(ct);

        using var bulk = new SqlBulkCopy(conn, SqlBulkCopyOptions.TableLock, null)
        {
            DestinationTableName = "dbo.SalesHistory",
            BatchSize = 1_048_576,   // >= 102,400 avoids the delta store; a full rowgroup compresses best
            BulkCopyTimeout = 0
        };
        await bulk.WriteToServerAsync(rows, ct);
    }
}

⚠ Common mistakes

  • Mistake: Putting a clustered columnstore on a table that serves singleton lookups and frequent updates. Why it is wrong: point reads decompress segments and updates become delete plus insert. Instead: rowstore for OLTP, with an NCCI for analytics if needed.
  • Mistake: Loading in small batches. Why it is wrong: rows sit in delta stores and produce small, poorly compressed rowgroups. Instead: batch 102,400+ rows, ideally about a million.
  • Mistake: Never maintaining it. Why it is wrong: deleted rows stay in the delete bitmap and are still read and filtered out, open delta stores are scanned in row mode, and small rowgroups compress poorly, so queries slow down month by month. Instead: monitor deleted_rows and rowgroup states in sys.dm_db_column_store_row_group_physical_stats; REORGANIZE (online) compresses delta stores and merges small or heavily deleted rowgroups, REBUILD (or rebuild one partition) when deletes are widespread.
  • Mistake: Deleting large date ranges row by row from a columnstore. Why it is wrong: every deleted row is only marked in the delete bitmap and logged, so the rowgroups stay full size and the delete is slow. Instead: partition by date and TRUNCATE TABLE ... WITH (PARTITIONS (...)) or switch the partition out.
  • Mistake: Expecting segment elimination on unordered data. Why it is wrong: every rowgroup's min/max spans the whole range. Instead: load in date order or use an ordered CCI (SQL Server 2022+).
  • Mistake: Adding an NCCI to a hot OLTP table without compression delay or a filter. Why it is wrong: rows still being updated churn the columnstore and add write cost to every transaction. Instead: COMPRESSION_DELAY or a filtered NCCI on closed rows, and load-test the write path.
  • Mistake: Thinking columnstore is Enterprise-only. Why it is wrong: since SQL Server 2016 SP1 it is in all editions, with limits on Standard. Instead: check the edition limits, not availability.
  • Mistake: Assuming batch mode needs a columnstore. Why it is wrong: since SQL Server 2019 (compatibility level 150) and in Azure SQL, batch mode on rowstore can apply to analytic queries. Instead: check Actual Execution Mode before adding an index just for batch mode.

🏛 Senior insight: trade-offs

Columnstore lets you run analytics on the operational database, which is often simpler than building a pipeline to a warehouse. The decision is about workload shape: if the hot queries aggregate millions of rows over a few columns, columnstore wins by an order of magnitude; if they fetch single orders, it hurts. I measure with batch-mode plans, segment reads and skipped counts, and insert latency on the write path.

Option When it fits Cost When not to
Clustered columnstore Fact and history tables, append-mostly Slow singleton updates, maintenance OLTP tables with point lookups
NCCI on OLTP table Live dashboards on operational data Extra write cost per row Very write-heavy tables with no analytics
Batch mode on rowstore (2019+) Analytic queries on rowstore without new indexes Nothing to maintain When I/O, not CPU, is the bottleneck
Separate reporting database or Fabric Heavy, wide reporting across systems Pipeline, latency, cost One or two dashboard queries

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions large history tables or partitioning. Why: Checks how columnstore fits into a wider scaling and archiving design.
    How to answer

    I start with numbers: data size and growth, hot versus cold data, read/write ratio and tenant distribution. Then:

    • Partitioning (by date) is mainly a manageability tool: SWITCH makes archiving and purging metadata-only and enables partition-level index rebuilds. It is not an automatic speed-up and needs queries that allow partition elimination.
    • Archive cold data to cheaper storage or a history database.
    • Tenant layout: shared schema for many small tenants, database per tenant in an elastic pool for isolation, a hybrid for large tenants.
    • Hyperscale for one large database (up to 128 TB, fast scaling, read replicas); elastic pools for many small databases sharing compute.

    Shard only when scale-up, read scale-out and archiving are exhausted: it moves complexity into the application.

  2. When: Candidate mentions replacing a reporting database. Why: Checks how columnstore compares with reporting tables and indexed views.
    How to answer

    I denormalise only when a measured read cost cannot be fixed with an index or query rewrite, and only with a named owner that keeps the copy consistent. SQL Server gives three levels:

    • Persisted computed column: a derived value from the same row (e.g. LineTotal = Quantity * UnitPrice), always consistent and indexable.
    • Indexed view: a pre-joined or pre-aggregated result with a unique clustered index, maintained synchronously on every write, which can create lock hot spots on popular groups.
    • Summary / reporting table or read model: refreshed by a job or events, cheapest to read but can be stale.

    The trade-off: reads get cheaper, but writes get slower and lock more, data flows get more complex, and every copy needs reconciliation.

🛠 Real-world problems: how you handle them

Operations dashboard timing out on the live orders table
Situation
A [retail] platform's operations dashboard aggregated the last 90 days of a [200-million-row] orders table on Azure SQL (Business Critical, [8] vCores) every minute for [40] users.
Signals
Dashboard tiles timed out at 30 seconds during the morning peak; Query Store showed the aggregate queries using [70]% of CPU; order checkout p95 rose from [80] ms to [400] ms because they competed for the same CPU.
Investigation
Actual plans showed parallel clustered index scans in row mode reading [2.5 million] pages per run. `sys.dm_exec_query_stats` confirmed the dashboard queries dominated logical reads. Checked that the compatibility level was 160, so batch mode on rowstore was available but the optimiser had not chosen it for these queries.
Resolution
Immediate: cached dashboard results for 60 seconds in the API to cut execution count by [40]x. Real fix: added a non-clustered columnstore index on the reporting columns with `COMPRESSION_DELAY = 60` so rows still being updated during fulfilment stayed in the delta store. Dashboard queries switched to batch mode columnstore scans.
Prevention
Load test of checkout with the NCCI in place before release; a weekly job checks rowgroup health and runs REORGANIZE; a Query Store alert on the dashboard queries' duration; an ADR recording why analytics run on the primary instead of a replica.

How to tell it (STAR)

**S:** At [company] our operations dashboard was timing out every morning and dragging checkout latency up with it. **T:** I needed to make the dashboard fast without hurting order writes. **A:** I used Query Store and the actual plans to show the aggregates were row-mode scans of [2.5 million] pages a minute, added a short API cache as a stopgap, then a non-clustered columnstore on the reporting columns with a compression delay so active orders didn't churn it, and load-tested checkout before release. **R:** Dashboard queries went from timeouts to about [1.5] seconds, database CPU dropped from [90]% to [35]%, and checkout p95 returned to [80] ms.

More in Indexes

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me