# SQL Server Reference Guide

Hosted by

## Design Elements Part 6: Math Operators and Functions

Last updated Mar 28, 2003.

Numeric manipulation and analysis make up a large part of almost every development effort. You add up the quarterly sales, figure out the average salesperson's income, and so on.

It's convenient to think about numeric analysis in three parts: Arithmetic (or mathematical), Trigonometric, and Statistical. This week, I'll show you how to use the math operators in Transact-SQL (T-SQL), and some of the trigonometric functions.

While we won't delve into the specifics of every function, I'll show you the importance of operator order, syntax, and application. This tutorial will form the basis for creating useful algorithms that we'll incorporate into our design efforts.

#### Math Operators

Let's begin with the math operators. In T-SQL We have the basic set, including addition (+), subtraction (-), multiplication (*), division (/) and modulo (%). We can use these operators on both result sets and with direct T-SQL commands. In other words, we can SELECT the results of a math operator, like this:

``` SELECT 2+2
GO
-------------
4```

Or we can use the operators as part of another T-SQL construct, like this:

``` SELECT qty * (.05)
FROM sales
GO
-------------
1.05
2.05
...```

It's important to understand the "order of operations" paradigm -- the same rules you learned back when you studied algebra. Remember the acronym PEMDAS? It stands for the fact that in math "sentences" the order the numbers are processed is Parentheses, Exponents, Multiplication, Addition and Subtraction. That order precedence largely holds true here as well.

To see why it's important to be careful with the order of operations, let's take a look at two math statements:

``` SELECT 2 + 5*2
GO

SELECT (2+5) * 2
GO```

Even though these statements look similar, they return different results. Multiplication comes before addition in T-SQL, so the first statement reads "multiply 2 times 5, and then add 2", which is 12.

But because parentheses come before multiplication, the second statement reads "add 2 to 5 and then multiply the result by 2", which is14. The parentheses change things dramatically.

In this simple example, it's easy enough to spot the possible interpretations. When these expressions reach epic proportions, however, it can get quite confusing to spot any potential misinterpretations. I say "misinterpretations" because the server will (under normal conditions) always produce correct answers, but they might not be the answers we expected. It's normally a good practice to enclose almost all math operators with parenthesis, so there's no confusion.

Now that we have the precedence order firmly in hand, let's take a closer look at one of the operators, modulo (%). The modulo operator divides two numbers and provides the remainder (the modulus). Modulo has some really neat features, one of which is to show the last N digits of a large number. For instance, to get the last digit of 12345, just divide it by 10 and get the remainder:

``` SELECT 12345 % 10
GO
----------
5```

To get the last two digits we can use modulo 100, and so on. Pretty neat! We can also use modulo to get an alternating series, iterate a loop by a set divisor, and just about anywhere that we want to have recursion. We'll learn more about this useful operator in future tutorials.

So far we've been focusing on decimal-based math sets, but T-SQL also provides several "Bitwise" operators for bit-math. We'll deal with those a bit later.

#### Math Comparisons

We can combine the math operators with several tools used to compare values. Here's a quick list:

 = Equals Equal to > Greater Than Greater than < Less Than Less than >= Greater Than or Equal To Greater than or equal to <= Less Than or Equal To Less than or equal to <> Not Equal To Not equal to != Not Equal To Not equal to (not SQL-92 standard) !< Not Less Than Not less than (not SQL-92 standard) !> Not Greater Than Not greater than (not SQL-92 standard)

We've already examined many of these comparison conditions during our foray into the SELECT...WHERE constructs. We'll see them again during our tutorials on Stored Procedures.

#### Math Functions

Besides the operators, T-SQL provides several functions. You can think of functions as machines: they accept an input, do something to the input using operators and comparisons, and produce an output.

Here are a few of the functions available in T-SQL:

 ABS DEGREES RAND ACOS EXP ROUND ASIN FLOOR SIGN ATAN LOG SIN ATN2 LOG10 SQUARE CEILING PI SQRT COS POWER COT RADIANS TAN

 ACOS TAN COS SIN ATAN ASIN ATN2 COT

We'll cover the use of these functions in more depth later, but let's take a simple example by rounding a number to two decimal places using a function from above:

``` SELECT ROUND(12.71231, 2)
GO
-------
12.71000```

As we can see, the ROUND function has a syntax that is bounded by an open-parenthesis and then two numbers:

`ROUND(Number_to_round, Precision)`

The first is the input, and the second is the precision, followed by the closing-parenthesis. Many of the functions in the list above have this kind of syntax, meaning that they require more than one parameter.

Another feature of operators and functions are that they can be nested, such that we can find the square root of the rounded number:

`SELECT SQRT(ROUND(12.71231, 2))`

Practical applications of these functions, along with operators and comparisons, produce algorithms. It's not so important to memorize the format of each function (we can always look that up); it's far more important to be familiar with the function's use and application. I've seen some really convoluted attempts at building functions that T-SQL already provides.

In our learning process we'll make frequent reference to these functions to build useful algorithms for our programs.

### Online Resources

Really into math? I like Joe's site on the subject.

Lynn Fields has a great article on SQL Server Magazine's sitem called Algorithms Still Matter, with more depth on using the functions and operators we've covered here.

### InformIT Tutorials and Sample Chapters

Baya Pavliashvili has a good article called Math and Text Functions in SQL Server 2000.