SQL COS function
Returns the cosine of an angle expressed in radians: COS(0) is 1 and COS(PI()) is -1.
- Category
- Math
- Returns
float / double- In this category
- 31 of 82
Syntax
COS(angle_radians)
Engine support
| Engine | Support | Notes |
|---|---|---|
| SQL Server | Yes | Supported under this name. |
| PostgreSQL | Yes | Supported under this name. |
| MySQL | Yes | Supported under this name. |
| SQLite | Yes | Requires SQLite 3.35+ with the math functions built in |
| Oracle | Yes | Supported under this name. |
Examples
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
Good to know
- 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.
Related on SQLly
Cheat sheets for the engines that have it: SQL Server, PostgreSQL, MySQL, SQLite, Oracle.
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.