SQL Server Interview Question #180

What are computed columns?

Database Design, Normalization & Advanced SQL Senior Advanced

Detailed Explanation

A computed column derives its value from an expression involving other columns in the same table. SQL Server calculates the value according to the expression rather than requiring the application to maintain it manually.

A computed column can sometimes be marked PERSISTED so the computed result is physically stored, subject to SQL Server requirements. Eligible computed columns can also be indexed when determinism, precision, and other requirements are satisfied.

Computed columns are useful for reusable derived values, but business rules and performance implications should be considered before storing or indexing them.

Code Example

CREATE TABLE dbo.OrderItems
(
    Id INT IDENTITY PRIMARY KEY,
    Quantity INT NOT NULL,
    UnitPrice DECIMAL(18,2) NOT NULL,
    LineTotal AS
        (CONVERT(DECIMAL(18,2), Quantity * UnitPrice))
        PERSISTED
);