Building a Warehouse in SQL Server

How to Build a Data Warehouse in SQL Server

Learn how to build a data warehouse in SQL Server, from planning and star-schema tables to staged ETL loads, indexing, scheduling and testing the results.

On this page
  1. Plan what the warehouse must answer
  2. Create the database and schemas
  3. Design the dimension and fact tables
  4. Load through a staging area
  5. Handle changes to dimension data
  6. Index the large tables
  7. Schedule the loads
  8. Test and check the results
  9. Secure and back up the warehouse
  10. Choose where it runs
  11. Common mistakes
  12. Summary

A data warehouse in SQL Server is a separate database built for reporting and analysis. It collects data from business systems, arranges it in tables that are easy to query, and refreshes it on a schedule. You can build one with SQL Server and its companion tools: create the database and schemas, design dimension and fact tables, load them through a staging area, index the large tables, schedule the loads and check the results. The sections below follow that order.

Plan what the warehouse must answer

Start with the questions people will ask of the data, such as sales by region and month, or returns by product. For each question, note which source systems hold the answer, how fresh the data needs to be, and who will read the reports. Those answers decide which tables you need and how much history to keep.

Keep the first version narrow. One sales source with two or three dimensions is far easier to load and check than a design that combines every system in the company. You can add tables once the first set loads reliably.

Create the database and schemas

Create the warehouse as its own database, separate from any database your applications write to. Schemas group tables by their job. A common layout uses one schema for raw copies of source data and another for the tables that reports read from.

CREATE DATABASE SalesDW;
GO

USE SalesDW;
GO

CREATE SCHEMA stg;  -- raw copies of source data
GO

CREATE SCHEMA dw;   -- dimension and fact tables for reporting
GO

The names here are examples. Pick names your team will recognize, and use them consistently.

Design the dimension and fact tables

Most SQL Server warehouses use a star schema. A fact table holds measurable events, such as sales lines, and points to dimension tables that describe them, such as customers, products and dates. Drawn out, the fact table sits in the middle with the dimensions around it, like the points of a star. Microsoft’s documentation for Fabric Warehouse describes the same layout.

Before you create the fact table, write down its grain: what one row represents, such as one order line. Every column in the fact table has to match that grain.

Dimension tables usually get a surrogate key, an integer the warehouse controls, kept alongside the business key from the source system. Surrogate keys keep the warehouse steady when a source system changes its codes, and they make it possible to keep history.

CREATE TABLE dw.DimCustomer (
    CustomerKey   INT IDENTITY(1,1) NOT NULL PRIMARY KEY,  -- surrogate key
    CustomerID    NVARCHAR(20)      NOT NULL,              -- business key from the source
    CustomerName  NVARCHAR(100)     NOT NULL,
    Region        NVARCHAR(50)      NULL
);

CREATE TABLE dw.FactSales (
    DateKey      INT            NOT NULL,  -- yyyymmdd, for example 20261128
    CustomerKey  INT            NOT NULL REFERENCES dw.DimCustomer (CustomerKey),
    Quantity     INT            NOT NULL,
    SalesAmount  DECIMAL(12, 2) NOT NULL
);

This example leaves out a date dimension, which many designs add. A date key stored as a yyyymmdd integer, as shown, is a common approach because the key stays readable.

Foreign keys document the links between tables. Some teams skip them on large fact tables to reduce checks during loads, and test the links in the load steps instead.

Load through a staging area

Load source data into the staging schema first, as close to the original as you can. Then transform it and insert it into the dimension tables before the fact tables, because each fact row needs its dimension keys to exist already. Keeping the raw copy lets you rerun a load or trace a number back to its source.

Teams name this first area differently, but a landing area in data warehouse projects does the same job: it holds a raw copy you can reload or check later.

The dimension load adds only customers that are not already in the table:

INSERT INTO dw.DimCustomer (CustomerID, CustomerName, Region)
SELECT s.CustomerID, s.CustomerName, s.Region
FROM stg.Customer AS s
WHERE NOT EXISTS (
    SELECT 1
    FROM dw.DimCustomer AS d
    WHERE d.CustomerID = s.CustomerID
);

Then the fact load looks up each dimension key:

INSERT INTO dw.FactSales (DateKey, CustomerKey, Quantity, SalesAmount)
SELECT
    CONVERT(INT, CONVERT(CHAR(8), o.OrderDate, 112)),  -- yyyymmdd as an integer
    c.CustomerKey,
    o.Quantity,
    o.Amount
FROM stg.Orders AS o
INNER JOIN dw.DimCustomer AS c
    ON c.CustomerID = o.CustomerID;

The inner join silently drops any order whose customer is missing from the dimension, so compare row counts after each load. This dimension load also ignores customers whose details have changed, which the next section covers.

Handle changes to dimension data

Customers move, rename themselves and change regions. Reports sometimes need the value that was true at the time of a sale, and sometimes only the latest value. Two common approaches:

  • Type 1 overwrites the old value, so reports show only the latest one.
  • Type 2 keeps history. The current row gets an end date and its current flag is cleared, and a new row is inserted with a new surrogate key, a start date and the current flag set.

With type 2, fact rows must join to the version that was current when the event happened. If a fact joins to every version of a customer, the sale can be counted more than once. Many teams write down the rule for choosing a version before they build the load.

Index the large tables

Fact tables are often large, and they are mostly read by queries that sum or count many rows. A clustered columnstore index is a common choice for them in SQL Server, because it compresses data well and speeds up large scans. It works best when updates and deletes touch only a small share of rows, so load in batches rather than editing rows in place.

CREATE CLUSTERED COLUMNSTORE INDEX CCI_FactSales ON dw.FactSales;

Dimension tables are small enough that the clustered primary key created in the example is usually fine. Columnstore support and options differ by SQL Server version and edition, so check the index guidance for your release before you create one.

Schedule the loads

Put the loading steps in one stored procedure, in the order they must run: dimensions first, then facts, then checks. Wrap each step in a transaction so a failed run does not leave a table half loaded, and log the row counts and run time for every run.

On SQL Server, SQL Server Agent runs jobs on a schedule. Create a job, add a T-SQL step that runs the procedure, attach a schedule set for a quiet period, and run the job once by hand to test it.

SQL Server Agent is a separate service from the database engine, so check that it is running after a restart. Azure SQL Database does not include SQL Server Agent, so a warehouse hosted there needs another scheduler.

Test and check the results

After each load, check the warehouse against the source:

  • Row counts. The staged rows should match what the fact table gained, once you allow for any rows you excluded on purpose.
  • Totals. Sum a measure, such as the sales amount for one day, in the source and in the warehouse.
  • Duplicates. A business key should have one row in a type 1 dimension, and exactly one current row in a type 2 dimension.
  • Reruns. Running the same load twice should not double the numbers.

Checks often catch problems the code alone does not show, such as a join that quietly drops rows. For more on what those checks look like, see the difference between etl testing and data warehouse testing.

Secure and back up the warehouse

Give the loading account write access to the warehouse schemas, and give report readers read-only access, for example through the db_datareader role.

Back up the database on a schedule, and test a restore at least once. If the database uses the full recovery model, schedule log backups too, or the transaction log will keep growing.

Choose where it runs

You can run SQL Server on your own hardware, on a virtual machine in the cloud, or use a managed Azure service. Each choice changes what you run yourself, including patching, backups, high availability and job scheduling. For a warehouse, the scheduling and feature differences often matter most, so check them before you commit.

Common mistakes

  • Loading fact rows before their dimensions, so lookups fail or rows drop out.
  • Using the source system’s codes as the only key, so a renumbered code breaks the history.
  • Skipping the staging copy, which makes reruns and audits harder.
  • Rewriting a fact table row by row when a batch load would do.
  • Trusting a load without a row count check after its joins.

Summary

Start with a small, correct warehouse: one fact table, two or three dimensions, a scheduled load and checks against the source. When those run reliably, add tables and history tracking one at a time.

Keep exploring

Guides from other topics

All topics →