Calculating values in application code requires logic duplication. Computed columns calculate automatically in database.
Create Computed Column:
CREATE TABLE Orders (
OrderId INT PRIMARY KEY,
Quantity INT,
PricePerUnit DECIMAL(10,2),
-- Computed column (calculated automatically)
TotalPrice AS (Quantity * PricePerUnit),
-- Persisted (stored, can be indexed)
TotalWithTax AS (Quantity * PricePerUnit * 1.1) PERSISTED
);
Automatic Calculation:
INSERT INTO Orders (OrderId, Quantity, PricePerUnit) VALUES (1, 5, 10.00); SELECT * FROM Orders; -- TotalPrice = 50.00 (calculated automatically!) -- TotalWithTax = 55.00 (calculated and stored)
Full Name Example:
CREATE TABLE Employees (
FirstName NVARCHAR(50),
LastName NVARCHAR(50),
FullName AS (FirstName + ' ' + LastName) PERSISTED
);
-- FullName automatically maintained when FirstName/LastName change!
PERSISTED vs Non-Persisted:
Non-Persisted: Calculated on query (no storage)
PERSISTED: Calculated once, stored (can index, faster queries)
