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

📚 Interview question

When would you denormalise a SQL Server schema, and how? Compare persisted computed columns, indexed views and reporting tables, and explain what denormalisation costs you in writes and consistency.

Covers when denormalisation is justified and the SQL Server tools for it (persisted computed columns, indexed views, summary and reporting tables, read models), with their write, consistency and operational costs.

Mid-Level Theory Intermediate computed-columns database-design denormalisation indexed-views reporting sql-server

🎯 Key points

  • Denormalise only for a measured read problem an index cannot fix
  • Persisted computed column: same-row derived value, deterministic, indexable
  • Indexed view: SCHEMABINDING, COUNT_BIG(*), unique clustered index, maintained on every write
  • Indexed views on hot groups serialise concurrent writes (lock hot spots)
  • NOEXPAND needed for view matching outside Enterprise and Azure SQL
  • Summary or reporting table: refreshed by job, trigger or events; can be stale
  • Every copy needs an owner that keeps it in sync and a drift check
  • Read replicas or columnstore may beat denormalising the OLTP schema

⏱ 30-second 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.

🗣 Full answer (senior)

How I would answer this in an interview

"Denormalising means storing a derived or duplicated fact so a read doesn't have to compute or join it. I only do it once I've measured the read, looked at the actual plan and logical reads, and confirmed an index or a better query doesn't fix it, because every copy is a promise that something will keep it in sync.

SQL Server gives me a ladder. The lightest step is a persisted computed column: a value derived from the same row, like a line total or a normalised search key. The engine keeps it correct and I can index it. Next is an indexed view: a view with SCHEMABINDING and a unique clustered index, which SQL Server maintains inside the same transaction as the base-table write. It's great for pre-aggregating, say, daily sales per product, but each insert into OrderLines now also updates the view's index, and hot aggregate rows become lock contention points. Outside Enterprise edition and Azure SQL I also need the NOEXPAND hint for the optimiser to use it. The heaviest step is a separate reporting table or read model, refreshed by a job or from domain events through an outbox. It's cheapest to read but it's eventually consistent, so the UI has to tolerate staleness.

The mistake I see is copying columns 'for performance' into OLTP tables, like a customer name on every order, with nothing keeping them in sync. For example, at [company] a dashboard query took [8] seconds because it aggregated [N million] order lines on every load; an indexed view grouped by day and product brought it to [40 ms], and we accepted about [5]% extra insert latency. Denormalise deliberately, with a named owner for the copy."


The options

Technique Consistency Read gain Write cost Good for
Persisted computed column Always (same row) Small to medium Tiny Derived values, search keys, JSON property extraction
Indexed view Always (synchronous) Large for aggregates/joins Medium to high, contention on hot groups Dashboards, counters, pre-joins with few writes per group
Trigger-maintained column Always if correct Medium Medium, hidden Legacy cases; prefer the above
Reporting table / read model Eventual Large Low on the write path Analytics, search, cross-service views
Columnstore or read replica Always / near real time Large for scans Low Analytical queries without schema copies

Indexed view requirements (the ones that bite)

Requirement Why
WITH SCHEMABINDING, two-part names Base tables cannot change under the view
COUNT_BIG(*) when using GROUP BY The engine maintains aggregates incrementally
Deterministic expressions, no outer joins, no DISTINCT, no subqueries Incremental maintenance must be possible
SUM over a non-nullable expression Wrap with ISNULL
Correct SET options (ANSI_NULLS, QUOTED_IDENTIFIER ON) for writers Writes to base tables fail otherwise

Production example

A product dashboard [in a system you know] aggregated order lines on every page load: [8] s and [400k] logical reads. A persisted LineTotal column plus an indexed view by (ProductId, OrderDate) cut it to about [40] ms and [120] reads; insert latency on OrderLines rose from [2.1] to [2.3] ms, which the team accepted.

🔍 What the interviewer is checking

Checks whether the candidate treats denormalisation as a measured trade-off and knows SQL Server's specific tools and their limits.

Green flags

  • Measures first and tries indexes before copying data
  • Knows indexed view rules (SCHEMABINDING, COUNT_BIG, NOEXPAND)
  • Talks about write cost and lock contention
  • Names an owner and a reconciliation for every copy

Red flags

  • "Joins are slow, so denormalise"
  • No awareness of staleness or drift
  • Uses triggers as the default tool

📚 Learn in depth

1. Why denormalise at all

Normalised OLTP schemas optimise for correct, cheap writes. Some reads repeat expensive work on every call: aggregating millions of rows, joining six tables for a list page. Denormalising moves that work from read time to write time (or to a background process).

Read-time work                 Write-time work              Background work
(normalised query)             (indexed view, computed col) (reporting table, read model)
  every read pays                every write pays             nobody waits, data may lag

2. Persisted computed columns

ALTER TABLE OrderLines ADD LineTotal AS (Quantity * UnitPrice) PERSISTED; stores the value on the row and keeps it in step with its inputs. The expression must be deterministic to be persisted or indexed (GETDATE() is not). Non-persisted computed columns can still be indexed if deterministic and precise; the index stores the value. A common pattern is extracting a JSON property: ADD CustomerRef AS JSON_VALUE(Payload, '$.customerRef') then indexing it.

3. Indexed views: how maintenance works

When you insert into a base table, the query processor adds operators to the plan that compute the delta for the view and apply it to the view's clustered index within the same transaction. For an aggregate view, that means updating the group's row: many concurrent inserts for the same product and day serialise on that row's lock.

INSERT OrderLines ─► Clustered index insert (base)
                   └► Compute delta ─► Update vDailySales row (ProductId, OrderDate)
                                         └ X lock on that row: hot spot for popular products

The optimiser can match a query to an indexed view automatically in Enterprise edition and Azure SQL Database; in other editions you query the view WITH (NOEXPAND). Even in Enterprise, NOEXPAND also makes the optimiser use statistics on the view, which often improves estimates.

4. Reporting tables and read models

A nightly or near-real-time process writes a flattened table (or a separate store such as Azure AI Search). Options to feed it: a scheduled MERGE/INSERT ... SELECT job, Change Tracking or CDC, or domain events published through the outbox pattern. It decouples read and write load, but you must show freshness ("updated 2 min ago") and have a rebuild path.

5. Hidden costs

  • Write amplification and longer transactions (more locks held).
  • Schema changes touch more objects; indexed views block ALTER on base columns because of schema binding.
  • Drift: a missed code path updates the source but not the copy. Plan a reconciliation query.
  • Storage and backup size.

6. Alternatives to try first

A covering index, a filtered index, rewriting the query, a non-clustered columnstore index for analytic scans on an OLTP table, a readable secondary (Azure SQL Business Critical read scale-out or a geo-replica) for reporting.

Try it yourself

  1. Create OrderLines with 1 million rows and time a daily-sales aggregate with SET STATISTICS IO, TIME ON.
  2. Add an indexed view for the same aggregate and compare reads; then insert 10,000 rows and compare insert time before and after.
  3. Run two sessions inserting lines for the same product and day and watch the blocking in sys.dm_exec_requests.
  4. Add a persisted computed column over a JSON property, index it, and check the plan uses a seek.
  5. Try the same query on a Standard-edition-style setup with and without WITH (NOEXPAND).

💻 Code

A persisted computed column and an indexed view for a dashboard aggregate.

-- Same-row derived value: kept in step by the engine, indexable.
ALTER TABLE dbo.OrderLines
    ADD LineTotal AS (Quantity * UnitPrice) PERSISTED;
GO

-- Pre-aggregated daily sales, maintained on every write to OrderLines/Orders.
CREATE VIEW dbo.vDailyProductSales
WITH SCHEMABINDING
AS
SELECT  o.OrderDate,
        ol.ProductId,
        SUM(ol.LineTotal)  AS Revenue,   -- LineTotal is NOT NULL because both inputs are NOT NULL
        SUM(ol.Quantity)   AS Units,
        COUNT_BIG(*)       AS LineCount  -- required with GROUP BY
FROM dbo.OrderLines AS ol
JOIN dbo.Orders     AS o ON o.OrderId = ol.OrderId
GROUP BY o.OrderDate, ol.ProductId;
GO

CREATE UNIQUE CLUSTERED INDEX UX_vDailyProductSales
    ON dbo.vDailyProductSales (OrderDate, ProductId);
GO

-- Outside Enterprise / Azure SQL, ask for the view's index explicitly.
SELECT OrderDate, SUM(Revenue) AS Revenue
FROM dbo.vDailyProductSales WITH (NOEXPAND)
WHERE OrderDate >= DATEADD(day, -30, CAST(SYSUTCDATETIME() AS date))
GROUP BY OrderDate;

Reading it from .NET with Dapper; the query is the contract, so keep it in one place.

namespace Shop.Reporting;

using Dapper;
using Microsoft.Data.SqlClient;

public sealed record DailyRevenue(DateOnly OrderDate, decimal Revenue);

public sealed class SalesDashboard(SqlConnection connection)
{
    public async Task<IReadOnlyList<DailyRevenue>> Last30DaysAsync(CancellationToken ct)
    {
        const string sql = """
            SELECT OrderDate, SUM(Revenue) AS Revenue
            FROM dbo.vDailyProductSales WITH (NOEXPAND)
            WHERE OrderDate >= DATEADD(day, -30, CAST(SYSUTCDATETIME() AS date))
            GROUP BY OrderDate
            ORDER BY OrderDate;
            """;
        var rows = await connection.QueryAsync<DailyRevenue>(new CommandDefinition(sql, cancellationToken: ct));
        return rows.AsList();
    }
}

⚠ Common mistakes

  • Mistake: Denormalising before measuring. Why it is wrong: you pay the consistency cost for a problem an index might have fixed. Instead: capture the plan and logical reads, try indexes and rewrites first.
  • Mistake: Copying columns (customer name on every order) with no owner keeping them in sync. Why it is wrong: the copies drift and reports disagree. Instead: a computed column, indexed view, or a read model with a defined refresh and reconciliation.
  • Mistake: Putting an aggregate indexed view on a table with heavy concurrent inserts to the same group. Why it is wrong: every insert updates the same view row, causing blocking. Instead: a finer grain, a background summary table, or columnstore.
  • Mistake: Expecting Standard edition to use an indexed view automatically. Why it is wrong: automatic view matching is an Enterprise / Azure SQL feature. Instead: query the view WITH (NOEXPAND).
  • Mistake: Forgetting the SET options indexed views require. Why it is wrong: writes from a client with ARITHABORT or ANSI_NULLS off fail. Instead: keep default SqlClient settings and test writes after creating the view.
  • Mistake: Using triggers to maintain copies by default. Why it is wrong: hidden logic, row-by-row bugs, longer transactions. Instead: computed columns or indexed views where possible.

🏛 Senior insight: trade-offs

Denormalisation is moving work, not removing it. The senior question is where the work goes: to every read (normalised), to every write (computed columns, indexed views), or to a background process (reporting tables, read models), and who is accountable for consistency.

Option When it fits Cost When not to
Index or query rewrite Most slow reads Small write cost When the join or aggregate itself is the work
Indexed view Hot aggregate read, modest write rate per group Synchronous write overhead, locking on groups High-contention inserts into the same group
Reporting table / read model Analytics, search, cross-service screens Staleness, a pipeline to run Data that must be exact on read
Columnstore / read replica Large scans for reporting Licence tier, replica lag Point lookups

Measure with actual plans, SET STATISTICS IO, TIME ON and Query Store before and after, including the write path.

🔗 Follow-ups the interviewer may ask

  1. When: Candidate is vague about what the normalised design was. Why: Checks the foundation: which redundancy denormalising reintroduces.
    How to answer

    Normalisation is organising tables so that each fact is stored once, in the table whose key it depends on, so the data cannot contradict itself. Redundant copies cause anomalies: an update anomaly (change a customer's email in one row but not the other 40), an insert anomaly (cannot record a product until someone orders it) and a delete anomaly (deleting the last order loses the customer).

    • 1NF: atomic values, no repeating groups, every row identified by a key.
    • 2NF: every non-key column depends on the whole key, not part of a composite key.
    • 3NF: no transitive dependencies: non-key columns depend on the key, not on other non-key columns.

    A price on an order line is not a copy: it is the price charged on that day, a different fact from today's list price. For OLTP I design to 3NF and only denormalise where a measured read cost justifies the extra write and consistency cost.

🛠 Real-world problems: how you handle them

Dashboard aggregate replaced by an indexed view, then contention on Black Friday
Situation
A retail API on Azure SQL [tier] served a sales dashboard that aggregated [N million] order lines per request. An indexed view by product and day fixed the dashboard, then caused blocking during a [Black Friday] sale.
Signals
Dashboard p95 of [8] s before the change; after it, checkout insert latency spiked to [400] ms during the sale, with LCK_M_X waits in Query Store and Application Insights dependency timeouts on `INSERT OrderLines`.
Investigation
Actual plans showed the insert plan updating `vDailyProductSales`. `sys.dm_exec_requests` and sp_WhoIsActive showed sessions blocked on the same view key (the top-selling product for today). Query Store wait statistics confirmed lock waits on the insert query.
Resolution
Immediate: dropped the indexed view during the sale and served the dashboard from a cached 60-second result. Long-term: replaced the view with a summary table updated every minute by a background job reading new order lines by a rowversion high-water mark.
Prevention
Load test writes, not just reads, after any indexed view change; added an ADR listing when indexed views are allowed (low per-group write rates); alert on LCK_M_X waits for checkout queries.

How to tell it (STAR)

**S:** Our sales dashboard at [company] took [8] seconds because it aggregated [N million] order lines on every load. **T:** I was asked to make it fast without a separate warehouse. **A:** I added a persisted line total and an indexed view by product and day, which cut the dashboard to [40] ms. During [the next big sale] checkout inserts started blocking on the view row for the best-selling product; I found it with sp_WhoIsActive and Query Store waits, dropped the view, and replaced it with a one-minute summary job. **R:** The dashboard stayed under [100] ms, checkout p95 went back to [30] ms, and we wrote down when indexed views are safe to use.

↩ Usually asked after

More in Database Design

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me