Add a Computed Column to an Existing Table in SQL Server

This article demonstrates how to use T-SQL to add a computed column to an existing table in SQL Server.

A computed column is a virtual column that uses an expression to calculate its value. The expression will typically use data from other columns. A computed column is not physically stored in the table unless it’s marked PERSISTED.

Example 1 – Create a Table WITHOUT a Computed Column

First, let’s create a table without a computed column.

CREATE TABLE Products
  (
    ProductID int IDENTITY (1,1) NOT NULL,
    ProductName varchar(255), 
    Quantity smallint,
    Price money
  );

INSERT INTO Products (ProductName, Quantity, Price)
VALUES 
  ('Hammer', 5, 10),
  ('Corkscrew', 2, 7.50),
  ('Kettle', 3, 25.15);

SELECT *
FROM Products;

Result:

+-------------+---------------+------------+---------+
| ProductID   | ProductName   | Quantity   | Price   |
|-------------+---------------+------------+---------|
| 1           | Hammer        | 5          | 10.0000 |
| 2           | Corkscrew     | 2          | 7.5000  |
| 3           | Kettle        | 3          | 25.1500 |
+-------------+---------------+------------+---------+

Example 2 – Add a Computed Column

Now let’s add a computed column.

ALTER TABLE Products 
ADD TotalValue AS (Quantity * Price);

We’ve just added a computed column called TotalValue that multiplies the value in the Quantity column with the value in the Price column.

Here’s what happens when we select the table’s contents now:

SELECT *
FROM Products;

Result:

+-------------+---------------+------------+---------+--------------+
| ProductID   | ProductName   | Quantity   | Price   | TotalValue   |
|-------------+---------------+------------+---------+--------------|
| 1           | Hammer        | 5          | 10.0000 | 50.0000      |
| 2           | Corkscrew     | 2          | 7.5000  | 15.0000      |
| 3           | Kettle        | 3          | 25.1500 | 75.4500      |
+-------------+---------------+------------+---------+--------------+

Example 3 – Update a Value

Now, if a value is updated in the Quantity or Price columns, this will affect the total value returned by the computed column.

Example:

UPDATE Products
SET Quantity = 4
WHERE ProductId = 1;

SELECT *
FROM Products;

Result:

+-------------+---------------+------------+---------+--------------+
| ProductID   | ProductName   | Quantity   | Price   | TotalValue   |
|-------------+---------------+------------+---------+--------------|
| 1           | Hammer        | 4          | 10.0000 | 40.0000      |
| 2           | Corkscrew     | 2          | 7.5000  | 15.0000      |
| 3           | Kettle        | 3          | 25.1500 | 75.4500      |
+-------------+---------------+------------+---------+--------------+