SQL Server COS() Function

Summary: in this tutorial, you will learn how to use the SQL Server COS() function to calculate the cosine of a number.

Introduction to the SQL Server COS() function #

In SQL Server, the COS() function is a math function that returns the cosine of a number.

The following shows the syntax of the COS() function:

COS(n)Code language: SQL (Structured Query Language) (sql)

In this syntax:

  • n is the angle in radians for which you want to find the cosine value.

The COS() function returns the cosine of the argument n. If n is NULL, the COS() function returns NULL.

SQL Server COS() function examples #

Let’s explore some examples of using the COS() function.

1) Basic COS() function example #

The following example uses the COS() function to calculate the cosine of the number 1 radian:

SELECT COS(1) as cosine_value;Code language: SQL (Structured Query Language) (sql)

Output:

cosine_value
-----------------
0.54030230586814
Code language: SQL (Structured Query Language) (sql)

2) Using the COS() function with PI() function #

The following statement uses the COS() function to find the cosine of pi:

SELECT COS(PI()) cosine_value;Code language: SQL (Structured Query Language) (sql)

Output:

cosine_value
------------
-1Code language: SQL (Structured Query Language) (sql)

3) Using COS() function with table data #

First, create a table called angles to store angles in radians:

CREATE TABLE angles(
    id INT IDENTITY PRIMARY KEY,
    angle DEC(19,2)
);Code language: SQL (Structured Query Language) (sql)

Second, insert three rows into the angles table:

INSERT INTO
  angles (angle)
VALUES
  (0),
  (PI())
  (PI() / 3);Code language: SQL (Structured Query Language) (sql)

Third, query data from the angles table:

SELECT
  id,
  angle
FROM
  angles;Code language: SQL (Structured Query Language) (sql)

Output:

id | angle
---+------
1  | 0.00
2  | 3.14
3  | 1.05
(3 rows)Code language: SQL (Structured Query Language) (sql)

Finally, calculate the cosines of angles from the angles table:

SELECT
  id,
  COS(angle) cosine_value
FROM
  angles;

Output:

id | cosine_value
---+-------------
1  | 1.0
2  | -1.0
3  | 0.5
(3 rows)Code language: SQL (Structured Query Language) (sql)

Summary #

  • Use the COS() function to calculate the cosine of a number.
Was this tutorial helpful?