Schema Design, APPLY and Temporal Tables

Article · 5:00

Constraints the engine enforces, clustered index choice as a design decision, APPLY and window functions, views, and system-versioned tables that keep their own history.

The clustered index is a schema decision, not an afterthought. In SQL Server a table's clustered index is the table - the rows are stored in its order. Every nonclustered index stores the clustered key as its pointer back to the row. Two consequences follow. A wide clustered key makes every nonclustered index wider. And an ever-increasing clustered key means inserts append to the end rather than splitting pages in the middle.

The default - clustering on the IDENTITY primary key - is usually right. It is wrong when the dominant access pattern is a range over something else, such as reading all order lines for one order, where clustering on (order_id, order_line_id) turns many random reads into one sequential one.

Constraints. CHECK, UNIQUE, FOREIGN KEY, DEFAULT. Name them explicitly: a system-generated name like CK__order_li__quant__3B75D760 is unusable in a migration script and differs between environments. A filtered unique index gives you what the standard's UNIQUE does not - uniqueness over only the rows that matter, such as one active record per customer.

APPLY is the feature people arrive at SQL Server without and leave unable to do without. CROSS APPLY runs a table expression once per row of the left side, with access to that row's columns - the "top three orders per customer" problem in one statement. OUTER APPLY keeps left rows with no match. It is also how you call a table-valued function per row.

Window functions compute across rows without collapsing them: running totals, ranks within a partition, each row beside its predecessor with LAG. ROWS BETWEEN versus RANGE BETWEEN matters and is routinely got wrong - RANGE with duplicate ordering values includes all the peers, which is rarely what the author meant.

Temporal tables are system-versioned: SQL Server maintains a history table automatically and FOR SYSTEM_TIME AS OF queries the state at any past instant. For anything auditable - prices, entitlements, addresses - this replaces a hand-written trigger-and-history-table arrangement that is always slightly wrong.

Laboratory exercise 2 - two competing models.

Design two schemas for the capstone warehouse. Suggested contrast: a normalised operational model, against a star schema with a fact table and dimensions. Implement both, with constraints named explicitly.

Make the clustered index choice deliberate in each, and write down why. Implement the representative queries on both: insert an order, read an order with its lines, total sales by product by month, and the top three products per customer.

Make one table temporal and demonstrate AS OF returning a past state after an update.

Deliverable: both schemas, the queries, a test that attempts to violate each constraint and shows the engine refusing, the temporal demonstration, and a page arguing for one model against the stated access patterns - including what the clustered index choice costs the other queries.

-- ------------------------------------------------------------------
-- The clustered index IS the table. Choose it deliberately.
-- ------------------------------------------------------------------
CREATE TABLE sales.[order] (
    order_id    bigint IDENTITY(1,1) NOT NULL,
    customer_id int    NOT NULL,
    ordered_at  datetime2(3) NOT NULL CONSTRAINT DF_order_at DEFAULT SYSUTCDATETIME(),
    status      varchar(20)  NOT NULL CONSTRAINT CK_order_status
                    CHECK (status IN ('pending','paid','shipped','cancelled')),
    CONSTRAINT PK_order PRIMARY KEY CLUSTERED (order_id),
    CONSTRAINT FK_order_customer FOREIGN KEY (customer_id)
        REFERENCES sales.customer (customer_id)
);
-- Name every constraint. A system name like CK__order__status__3B75D760
-- differs between environments and is unusable in a migration.

-- Here the clustered key is NOT the identity column, because the
-- dominant read is "all lines for this order". Clustering on order_id
-- makes that one sequential read instead of N random ones.
CREATE TABLE sales.order_line2 (
    order_id      bigint NOT NULL,
    line_no       int    NOT NULL,
    product_id    int    NOT NULL,
    quantity      int    NOT NULL CONSTRAINT CK_line2_qty CHECK (quantity > 0),
    unit_price    decimal(19,4) NOT NULL,
    CONSTRAINT PK_order_line2 PRIMARY KEY CLUSTERED (order_id, line_no),
    CONSTRAINT FK_line2_order FOREIGN KEY (order_id)
        REFERENCES sales.[order] (order_id) ON DELETE CASCADE
);
-- Every NONCLUSTERED index on this table now carries (order_id, line_no)
-- as its row pointer. A wide clustered key makes every other index wide.

-- A filtered unique index: uniqueness over only the rows that matter.
CREATE UNIQUE NONCLUSTERED INDEX UX_customer_one_active
    ON sales.customer (email) WHERE deleted_at IS NULL;
-- Standard UNIQUE cannot express this. Soft-deleted rows may repeat.

-- ------------------------------------------------------------------
-- APPLY: a table expression evaluated once per row of the left side.
-- ------------------------------------------------------------------
-- Top three orders per customer, in one statement:
SELECT c.customer_id, c.name, o.order_id, o.ordered_at, o.total
FROM sales.customer AS c
CROSS APPLY (
    SELECT TOP (3) o.order_id, o.ordered_at,
           SUM(l.quantity * l.unit_price) AS total
    FROM sales.[order] AS o
    JOIN sales.order_line2 AS l ON l.order_id = o.order_id
    WHERE o.customer_id = c.customer_id     -- <- the left row's column
    GROUP BY o.order_id, o.ordered_at
    ORDER BY total DESC
) AS o;
-- CROSS APPLY drops customers with no orders; OUTER APPLY keeps them
-- with NULLs, which is the LEFT JOIN of the APPLY family.

-- ------------------------------------------------------------------
-- Window functions, and the frame clause people get wrong.
-- ------------------------------------------------------------------
SELECT
    o.customer_id, o.ordered_at, t.total,
    SUM(t.total) OVER (PARTITION BY o.customer_id ORDER BY o.ordered_at
                       ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW)
        AS running_total,
    LAG(t.total) OVER (PARTITION BY o.customer_id ORDER BY o.ordered_at)
        AS previous_order,
    DENSE_RANK() OVER (PARTITION BY o.customer_id ORDER BY t.total DESC)
        AS size_rank
FROM sales.[order] AS o
CROSS APPLY (SELECT SUM(quantity * unit_price) AS total
             FROM sales.order_line2 WHERE order_id = o.order_id) AS t;
--
-- ROWS BETWEEN counts physical rows. RANGE BETWEEN includes every row
-- with the same ORDER BY value - so with duplicate timestamps a RANGE
-- running total jumps by the whole group at once. ROWS is almost
-- always what was meant, and RANGE is the default. Say ROWS.

-- ------------------------------------------------------------------
-- Temporal tables: the engine keeps the history.
-- ------------------------------------------------------------------
CREATE TABLE sales.product (
    product_id  int IDENTITY(1,1) NOT NULL,
    name        varchar(200) NOT NULL,
    list_price  decimal(19,4) NOT NULL,
    valid_from  datetime2(3) GENERATED ALWAYS AS ROW START HIDDEN NOT NULL,
    valid_to    datetime2(3) GENERATED ALWAYS AS ROW END   HIDDEN NOT NULL,
    PERIOD FOR SYSTEM_TIME (valid_from, valid_to),
    CONSTRAINT PK_product PRIMARY KEY CLUSTERED (product_id)
)
WITH (SYSTEM_VERSIONING = ON (HISTORY_TABLE = sales.product_history));

UPDATE sales.product SET list_price = 19.99 WHERE product_id = 1;

-- What was the price last Tuesday? No trigger, no history table of
-- your own, no chance of them disagreeing:
SELECT product_id, name, list_price
FROM sales.product FOR SYSTEM_TIME AS OF '2026-11-25T00:00:00'
WHERE product_id = 1;

-- Every version, and when each was current:
SELECT product_id, list_price, valid_from, valid_to
FROM sales.product FOR SYSTEM_TIME ALL
WHERE product_id = 1 ORDER BY valid_from;

Discussion

No questions on this topic yet. Sign in to ask the first one.