# Introduction to SQL Server’s Mathematical Functions

## Math Rocks!

SQLServer includes many mathematical functions you can use to perform business and engineering calculations. Many of these aren’t used in typical day-to-day operations; however, there are several commonly used functions we’ll cover.

If you not familiar with SQL functions, then I would recommend staring with the Introduction to SQL Server Built-In Functions.

All the examples for this lesson are based on Microsoft SQL Server Management Studio and the AdventureWorks2012 database. You can get started using these free tools using my Guide *Getting Started Using SQL Server*.

## Introduction to SQL Server’s Mathematical Functions

There are many mathematical functions within SQLServer at your disposal. I would generally categorize them as the following:

- Scientific and Trig Functions
- Rounding Functions
- Signs
- Random Numbers

All of the functions are listed on this MSDN page. I would recommend visiting that page to learn about each function.

Rather than reiterate that material, we’ll focus on the functions I’ve seen in commonly used in business.

In the following table I categorized the functions and color coded them. The color code corresponds to the likely hood you will use that particular function in a business environment: Green are most likely used, and red less so.

This isn’t a strict scale, and all functions are awesome (I’m an engineer and love math), but I wanted a way to help you winnow down the field to those most relevant.

Here is my attempt:

In the remainder of the article we’ll go over the functions highlighted in green. Along the way, I’ll try point out some interesting ideas and uses about the functions. Please read every section, as there is always something new to learn.

## Scientific and Trig Functions

### PI

To be honest PI really shouldn’t be on this list, but let’s face it, PI is cool. And now that you have the function, there is no need to memorize this fabled constant used to calculate circumference and area of circles.

SELECT 2 * PI() * 10

Returns the circumference of a circle with radius 10.

### SQRT

SQRT stands for square root. This is a relatively common function. Most of us have run across it when working with areas.

The SQRT function accepts any numeric value that can be implicitly converted to a float datatype. The result is also float.

To illustrate

SELECT SQRT(25)

Returns 5

Imaginary numbers aren’t supported, so trying to calculate the square root of a negative number won’t work. You’ll get the following error

Msg 3623, Level 16, State 1, Line 1

An invalid floating point operation occurred.

### SQUARE

SQUARE is a short hand way to multiply an expression by itself.

Do you remember Pythagoras theorem from high school as A^{2} + B^{2} = C^{2}?

We could write this in SQL as

SELECT SQUARE(A) + SQUARE(B) as CSquared

And now that we know about SQRT we can calculate C as

`SELECT SQRT(SQUARE(A) + SQUARE(B)) as C`

One point to get out of this is that you can nest functions. The result of one function can be pumped into the next.

## Rounding Functions

### CEILING and FLOOR

The CEILING and FLOOR functions are useful when you have a float or decimal value and you need to find the next lowest or highest integer.

The CEILING is the next highest integer value; whereas, floor is the next lowest.

CEILING and FLOOR have a practical use when you’re working with discrete quantities and averages.

For instance, let’s assume the sales manager is having a sales convention for all the sales people. They want to rent cars to be able to get around town. Assuming each car holds 4 people how many cars do he need to rent for the business trip?

To figure this out, we can take the number of sales people and divide by four

SELECT COUNT(*) / 4.0 as NumberCars FROM Sales.SalesPerson

This result is 4.25 cars. As you know you cannot rent nor drive a quarter of a car!

To get around this we need to round up to the nearest whole car. We can use CEILING to do so. Here is the query to use

```
SELECT CEILING(COUNT(*) / 4.0) as NumberCars
FROM Sales.SalesPerson
```

Also, did you notice I used 4.0 rather than 4 in the calculation? This is to ensure the result is a float; otherwise, the result is returned as an integer, and would have been implicitly converted to an integer value of 4.

### ROUND

The ROUND function is used to round a value to the nearest specified decimal place. The general format for ROUND is

ROUND(value, number of decimal places)

Thus

`SELECT ROUND(5.153745,0)`

returns 5.000000 as 5.1 is rounded to 5

`SELECT ROUND(5.153745,1)`

returns 5.200000 as 5.15 is rounded to 5.2 and

`SELECT ROUND(5.153745,2)`

returns 5.150000 as 5.153 is rounded to 5.15

In all cases results datatype is the same as the input value.

Let’s look at another example, suppose the sales manager asks for sales order detail information. You provide him with the following query:

SELECT SalesOrderID, SalesOrderDetailID, OrderQty, UnitPrice, UnitPriceDiscount, LineTotal FROM Sales.SalesOrderDetail

He says, “That’s great, but can you round the line totals to the nearest penny?”

How would go about doing that? Here is a query you can use with the ROUND function to accomplish that task:

SELECT SalesOrderID, SalesOrderDetailID, OrderQty, UnitPrice, UnitPriceDiscount, ROUND(LineTotal,2) as LineTotal FROM Sales.SalesOrderDetail Here are the line totals rounded

One thing to notice is, though the line total is rounded, the number of decimal place are retained. The round function returns the same data type as the input value, in this case one with 6 decimal places.

Can you think of another way to satisfy this request? What about converting data types?

Check out this query

SELECT SalesOrderID, SalesOrderDetailID, OrderQty, UnitPrice, UnitPriceDiscount, Cast(LineTotal as Decimal(10,2)) as LineTotal FROM Sales.SalesOrderDetail

This displays the same results, but since the datatype changed, only two decimal places are displayed.

## Signs

### ABS

There are many situations where you need to obtain the absolute difference between two values. In these situations returning the absolute value is useful. The absolute value of a number is the number with the sign removed. The absolute value of -6 is 6.

In t-SQL, you can use the ABS function to do this.

Suppose the sales manager would like to understand which products differ the most from the industry accepted price of $520? To get the absolute difference we can use t-SQL.

SELECT ListPrice, ABS(ListPrice - 520) AbsoluteDifference FROM production.Product WHERE ListPrice > 0 ORDER BY AbsoluteDifference

Notice how we also sort on the AbsoluteDifference. This allows us to sort by the magnitude of the difference and not whether it is a negative or positive value.

### SIGN

Speaking of negative and positive values, one handy function I’ve found to determine a value’s sign is to use the SIGN function. This function returns a -1, 0, or 1 depending on whether the value being tested is negative, zero, or positive.

Here is an example of it being used.

SELECT ListPrice, ABS(ListPrice - 520) AbsoluteDifference, SIGN(ListPrice - 520) DifferenceSignFunction, CASE WHEN SIGN(ListPrice - 520) < 0 THEN -1 WHEN SIGN(ListPrice - 520) = 0 THEN 0 WHEN SIGN(ListPrice - 520) > 0 THEN 1 END DifferenceSignCase FROM production.Product WHERE ListPrice > 0 ORDER BY AbsoluteDifference

There are couple of things to notice in the results

First notice that I also show how you can do the same function using the CASE statement. In this instance, SIGN is certainly simpler. You’ll find in SQL there are usually several ways to obtain a solution!

The second point is notice that the columns AbsoluteDifference and DifferenceSignFunction are the same data type as ListPrice. In general arithmetic functions such as ABS return the same datatype as their inputs. Other function, such as the trigonometric functions SIN and COS return floats.

Write a sql block that asks the user to enter the radius of a circle as well ast the operation code. The operation code can be A for area, C for circumference D for diameter. The block should execute if the user enter the code in either capital letter or small letter. Use the CASE statement to determine the answer depending on the operation code

I really need your help

To Donald: The way that you have stated the problem requires the use of a scalar function, because two values have to be provided, so here is my solution, and I don’t understand why you would use a CASE statement.

CREATE FUNCTION [dbo].[Circle_Values]

(

@radius decimal(10,2),

@operation CHAR(1)

)

RETURNS DECIMAL(10, 2)

AS

BEGIN

DECLARE @measure decimal(10,2)

IF UPPER(@operation) = ‘A’

BEGIN

SET @measure = ROUND(PI() * SQUARE(@radius), 2)

END

IF UPPER(@operation) = ‘C’

BEGIN

SET @measure = ROUND(2 * PI() * @radius, 2)

END

IF UPPER(@operation) = ‘D’

BEGIN

SET @measure = ROUND(2 * @radius, 2)

END

RETURN @measure

END

SELECT Radius = [dbo].[Circle_Values] (5.5, ‘A’)

SELECT Circumference = [dbo].[Circle_Values] (5.5, ‘c’)

SELECT Diameter = [dbo].[Circle_Values] (5.5, ‘d’)