// math reference

SQL COS function

Returns the cosine of an angle expressed in radians: COS(0) is 1 and COS(PI()) is -1.

Catégorie
Math
Returns
float / double
In this category
31 of 82

Syntaxe

COS(angle_radians)

Prise en charge des moteurs

MoteurSupportNotes
SQL Server Oui Supported under this name.
PostgreSQL Oui Supported under this name.
MySQL Oui Supported under this name.
SQLite Oui Requires SQLite 3.35+ with the math functions built in
Oracle Oui Supported under this name.

Exemples

PostgreSQL

SELECT COS(0) AS one, COS(PI()) AS minus_one;  -- 1, -1

PostgreSQL

SELECT COS(RADIANS(lat1 - lat2)) AS lat_cos
FROM geo_pairs;

SQL Server

SELECT COS(60 * PI() / 180) AS cos_60;  -- 0.50000000000000011

Bon à savoir

  • COS itself always returns a value in [-1, 1], but COS(60 * PI() / 180) is 0.50000000000000011, not 0.5, so compare with a tolerance.
  • The argument is radians: COS(60) is the cosine of 60 radians, not 60 degrees. Use RADIANS() or x * PI() / 180.
  • The spherical law of cosines sums products of SIN and COS and feeds the total to ACOS. That sum can land at 1.0000000000000002 for two identical points, and ACOS then fails; clamp it first.

Questions about COS

What range does COS return?

Between -1 and 1 inclusive. The function itself never leaves that range; expressions built from several COS and SIN terms can, which is why distance formulas clamp before calling ACOS.

Why does COS(60) not give 0.5?

60 is interpreted as 60 radians. For degrees, convert: COS(RADIANS(60)) or COS(60 * PI() / 180) returns about 0.5.

How is COS used for distance?

The spherical law of cosines computes ACOS(SIN(lat1) * SIN(lat2) + COS(lat1) * COS(lat2) * COS(lon2 - lon1)) * 6371 for kilometres. Convert all angles to radians first.

Browse every function in the SQL function reference, or see what the SQLly desktop app does for your database.

Cheat sheets for the engines that have it: SQL Server, PostgreSQL, MySQL, SQLite, Oracle.

// fewer lookups

Functions your engine actually has

SQLly's completion lists the built-in functions of the engine you're connected to, whether that's SQL Server, PostgreSQL, MySQL, SQLite or Oracle. Hover a function for help, and signature hints show each argument as you type.