Reading data with SELECT
Calculated columns
Compute a value in SELECT without changing the stored table.
Lesson 9 of 84
Reading: about 2 min
Lesson + practice: about 10 min
Difficulty: Beginner
On this page4 sections
This lesson uses DDI_SQL_Training dataset version 1.0.0 on SQL Server 2019 or later. OrderItems stores Quantity and UnitPrice separately. A report can calculate the value of each line when it reads the table, without storing another column.
Run the example
SELECT TOP (3) OrderID, LineNumber,
Quantity * UnitPrice AS LineTotal
FROM dbo.OrderItems
ORDER BY OrderID, LineNumber;Read it step by step
- Quantity * UnitPrice multiplies the two values from each OrderItems row. The * operator means multiplication in T-SQL.
- AS LineTotal names that calculated result. It does not create a LineTotal column in dbo.OrderItems.
- TOP (3) shows only three rows after ORDER BY OrderID, LineNumber. OrderID plus LineNumber is the table’s unique key, so the example always selects the same three lines.
Check the result
| OrderID | LineNumber | LineTotal |
|---|---|---|
| 1 | 1 | 117.00 |
| 1 | 2 | 180.00 |
| 2 | 1 | 516.00 |
Order 1 has two lines, so its ID appears twice. Their calculated totals are 117.00 and 180.00. The next ordered row is line 1 of order 2, worth 516.00. A calculated column is evaluated for each returned row.
Practice
Create a result column named AnnualSalaryAfterRaise showing each employee salary multiplied by 1.05. Does this update Employees?
Check your answer and expected result
Reveal answer
SELECT EmployeeID, AnnualSalary * 1.05 AS AnnualSalaryAfterRaise FROM dbo.Employees;| EmployeeID | AnnualSalaryAfterRaise |
|---|---|
| 1 | 65100.0000 |
| 2 | 40950.0000 |
| 3 | 44100.0000 |
| 4 | 38850.0000 |
| 5 | 67200.0000 |
| 6 | 43050.0000 |
| 7 | 42000.0000 |
| 8 | 54600.0000 |
| 9 | 69300.0000 |
| 10 | 45150.0000 |
| 11 | 43050.0000 |
| 12 | 52500.0000 |
It returns 12 calculated values and does not change stored salaries. SQL Server displays four decimal places here because multiplying decimal values increases the result scale; AnnualSalary itself remains stored with two decimal places.
Your progress
Reveal the check answer or reach the end to complete this lesson.