BlackWaspTM
SQL Server
SQL 2005+

SQL Server Trigonometric Functions

The forty-first part of the SQL Server Programming Fundamentals tutorial continues the examination of Transact-SQL (T-SQL) mathematical functions. This article considers the trigonometric functions that allow SQL Server to work with angular data.

Trigonometric Functions

SQL Server's Transact-SQL (T-SQL) scripting language provides several trigonometric functions. These are functions that operate with angles. Most developers who have studied trigonometry will have used trigonometric functions to calculate the angles and the lengths of the sides of triangles.

T-SQL allows the use of eight trigonometric functions, each working with or calculating angles measure in radians. T-SQL also includes related functions that allow the translation of angles between radians and degrees and return the value of Pi. In this article we will examine a total of eleven functions. These will be related to the right-angled triangle pictured below:

Triangle

The diagram shows a standard 3-4-5 triangle, meaning that the lengths of the three sides are in the ratio 3:4:5. The angle at the bottom-right of the triangle is labelled with the Greek letter theta (θ). The three other sides are shown with letters that relate to their positions relative to θ. The "a" side is adjacent to the angle, the "o" is the side opposite θ and the hypotenuse is marked with an "h".

Sine

The sine of an angle returns the ratio of the lengths of the opposing side and the hypotenuse. This function makes it simple to calculate either of these two lengths given the other length and the angle.

In the diagram the ratio between the opposite side to the angle θ and the hypotenuse is 0.6 (3m / 5m). We can use the Sin function to calculate this ratio based upon the angle. However, as the trigonometric functions work with radians, not degrees, we cannot use 36.86 directly. Instead, we must convert this to the equivalent radians value, which is approximately 0.6433.

print sin(0.6433)   // 0.599839

NB: The result is not exact because the original angle of 36.86 degrees was an approximation and rounding was introduced in the conversion to radians.

If you prefer to work in degrees, you can use the Radians function to perform the conversion, as in the following example:

print sin(radians(36.86))   // 0.599862

To calculate the length of the opposite side, you can multiply the sine of the angle by the length of the hypotenuse. As in the previous examples, rounding errors mean that the result will not be exactly three:

print sin(radians(36.86)) * 5   // 2.99931

Similarly, to calculate the hypotenuse you can divide the length of the opposite side by the sine of the angle:

print 3 / sin(radians(36.86))   // 5.00115
3 November 2009