 Introduction

Table of Contents
 Microsoft SQL Server Defined
 Microsoft SQL Server Features
 Microsoft SQL Server Administration

Microsoft SQL Server Programming
 An Outline for Development
 Database
 Database Services
 Database Objects: Databases
 Database Objects: Tables
 Database Objects: Table Relationships
 Database Objects: Keys
 Database Objects: Constraints
 Database Objects: Data Types
 Database Objects: Views
 Database Objects: Stored Procedures
 Database Objects: Indexes
 Database Objects: User Defined Functions
 Database Objects: Triggers
 Database Design: Requirements, Entities, and Attributes
 Business Process Model Notation (BPMN) and the Data Professional
 Business Questions for Database Design, Part One
 Business Questions for Database Design, Part Two
 Database Design: Finalizing Requirements and Defining Relationships
 Database Design: Creating an Entity Relationship Diagram
 Database Design: The Logical ERD
 Database Design: Adjusting The Model
 Database Design: Normalizing the Model
 Creating The Physical Model
 Database Design: Changing Attributes to Columns
 Database Design: Creating The Physical Database
 Database Design Example: Curriculum Vitae
 NULLs
 The SQL Server Sample Databases
 The SQL Server Sample Databases: pubs
 The SQL Server Sample Databases: NorthWind
 The SQL Server Sample Databases: AdventureWorks
 The SQL Server Sample Databases: Adventureworks Derivatives
 UniversalDB: The Demo and Testing Database, Part 1
 UniversalDB: The Demo and Testing Database, Part 2
 UniversalDB: The Demo and Testing Database, Part 3
 UniversalDB: The Demo and Testing Database, Part 4
 Getting Started with TransactSQL
 TransactSQL: Data Definition Language (DDL) Basics
 TransactSQL: Limiting Results
 TransactSQL: More Operators
 TransactSQL: Ordering and Aggregating Data
 TransactSQL: Subqueries
 TransactSQL: Joins
 TransactSQL: Complex Joins  Building a View with Multiple JOINs
 TransactSQL: Inserts, Updates, and Deletes
 An Introduction to the CLR in SQL Server 2005
 Design Elements Part 1: Programming Flow Overview, Code Format and Commenting your Code
 Design Elements Part 2: Controlling SQL's Scope
 Design Elements Part 3: Error Handling
 Design Elements Part 4: Variables
 Design Elements Part 5: Where Does The Code Live?
 Design Elements Part 6: Math Operators and Functions
 Design Elements Part 7: Statistical Functions
 Design Elements Part 8: Summarization Statistical Algorithms
 Design Elements Part 9:Representing Data with Statistical Algorithms
 Design Elements Part 10: Interpreting the Data—Regression
 Design Elements Part 11: String Manipulation
 Design Elements Part 12: Loops
 Design Elements Part 13: Recursion
 Design Elements Part 14: Arrays
 Design Elements Part 15: EventDriven Programming Vs. Scheduled Processes
 Design Elements Part 16: EventDriven Programming
 Design Elements Part 17: Program Flow
 Forming Queries Part 1: Design
 Forming Queries Part 2: Query Basics
 Forming Queries Part 3: Query Optimization
 Forming Queries Part 4: SET Options
 Forming Queries Part 5: Table Optimization Hints
 Using SQL Server Templates
 TransactSQL Unit Testing
 Index Tuning Wizard
 Unicode and SQL Server
 SQL Server Development Tools
 The SQL Server TransactSQL Debugger
 The TransactSQL Debugger, Part 2
 Basic Troubleshooting for TransactSQL Code
 An Introduction to Spatial Data in SQL Server 2008
 Performance Tuning
 Practical Applications
 Professional Development
 Application Architecture Assessments
 Business Intelligence
 Tips and Troubleshooting
 Additional Resources
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 TransactSQL (TSQL), 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 TSQL We have the basic set, including addition (+), subtraction (), multiplication (*), division (/) and modulo (%). We can use these operators on both result sets and with direct TSQL 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 TSQL 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 TSQL, 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 decimalbased math sets, but TSQL also provides several "Bitwise" operators for bitmath. 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 SQL92 standard) 
!< 
Not Less Than 
Not less than (not SQL92 standard) 
!> 
Not Greater Than 
Not greater than (not SQL92 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, TSQL 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 TSQL:
ABS 
DEGREES 
RAND 
ACOS 
EXP 
ROUND 
ASIN 
FLOOR 
SIGN 
ATAN 
LOG 
SIN 
ATN2 
LOG10 
SQUARE 
CEILING 
PI 
SQRT 
COS 
POWER 
COT 
RADIANS 
TAN 


In addition, we've got access to several trigonometric functions:
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 openparenthesis and then two numbers:
ROUND(Number_to_round, Precision)
The first is the input, and the second is the precision, followed by the closingparenthesis. 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 TSQL 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.