Computed Values in the Select List

Accessing and Changing Relational Data

Accessing and Changing Relational Data

Computed Values in the Select List

A select list can contain expressions that are built by applying operators to one or more simple expressions. This allows result sets to contain values that do not exist in the base tables, but are calculated from the values stored in the base tables. These result set columns are called derived columns, and include:

  • Calculations and computations that use arithmetic operators or functions on numeric columns or constants:
    SELECT ROUND( (UnitPrice * .9), 2) AS DiscountPrice
    FROM Products
    WHERE ProductID = 58
    
  • Data type conversions:
    SELECT ( CAST(ProductID AS VARCHAR(10)) + ': '
           + ProductName ) AS ProductIDName
    FROM Products
    
  • CASE functions:
    SELECT ProductID, ProductName,
        CASE CategoryID
            WHEN 1 THEN ROUND( (UnitPrice * .6), 2)
            WHEN 2 THEN ROUND( (UnitPrice * .7), 2)
            WHEN 3 THEN ROUND( (UnitPrice * .8), 2)
            ELSE ROUND( (UnitPrice * .9), 2)
        END AS DiscountPrice
    FROM Products
    
  • Subqueries:
    SELECT Prd.ProductID, Prd.ProductName,
           (   SELECT SUM(OD.UnitPrice * OD.Quantity)
               FROM Northwind.dbo.[Order Details] AS OD
               WHERE OD.ProductID = Prd.ProductID
           ) AS SumOfSales
    FROM Northwind.dbo.Products AS Prd
    ORDER BY Prd.ProductID
    

Calculations and computations can be performed with data by using numeric columns or numeric constants in a select list with arithmetic operators, functions, conversions, or nested queries. Arithmetic operators let you add, subtract, multiply, and divide numeric data.

The following arithmetic operators are supported.

Symbol Operation
+ Addition
- Subtraction
/ Division
* Multiplication
% Modulo

The arithmetic operators that perform addition, subtraction, division, and multiplication can be used on any numeric column or expression ( int, smallint, tinyint, decimal, numeric, float, real, money, or smallmoney). The modulo operator can only be used on int, smallint, or tinyint columns or expressions.

Arithmetic operations can also be performed on datetime and smalldatetime columns using the date functions or regular addition or subtraction arithmetic operators.

You can use arithmetic operators to perform computations involving one or more columns. The use of constants in arithmetic expressions is optional, as shown in this example:

SELECT ProductID, ProductName,
       UnitPrice * UnitsInStock AS InventoryValue
FROM Northwind.dbo.Products

See Also

FROM

SELECT

Operators

Join Fundamentals

Subquery Fundamentals

+ (Add)

- (Subtract)

Functions