--- title: "cos" slug: "dev-database-reference-sql-functions-numeric-cos" updated: 2026-10-30T18:18:51Z published: 2026-10-30T18:18:51Z canonical: "docs.vastdata.com/dev-database-reference-sql-functions-numeric-cos" --- > ## Documentation Index > Fetch the complete documentation index at: https://docs.vastdata.com/llms.txt > Use this file to discover all available pages before exploring further. # cos *Applies to VAST Cluster 5.5.* *[Functions](/develop/docs/dev-database-reference-sql-functions-index) › [Numeric and math functions](/develop/docs/dev-database-reference-sql-functions-numeric) › Trigonometry.* Returns the cosine of an angle given in radians, from -1 to 1. For an angle in degrees, convert it first with [radians](/develop/docs/dev-database-reference-sql-functions-numeric-radians): `cos(radians(deg))`. It has no aliases. ## Syntax ``` cos(x) ``` | Argument | Type | Description | | --- | --- | --- | | `x` | `DOUBLE` (any integer, `DECIMAL` or `FLOAT` is converted) | The angle, in radians. | **Returns:** `DOUBLE`, from -1 to 1. **Aliases:** none. ## Set up the examples The examples connect with the ADBC driver, as in [VAST Query Engine (ADBC)](/develop/docs/dev-database-integrations-adbc), and work in a schema called `docs_sql_fn_numeric_cos`. Set `QE_ENDPOINT`, `AWS_ACCESS_KEY_ID`, `AWS_SECRET_ACCESS_KEY` and `VASTDB_BUCKET` ([SQL reference](/develop/docs/dev-database-reference-sql-index#example-connect-and-use-a-transaction)), and run the blocks in order in one Python session. Below each block is the output you should see. This block connects, defines the `run()` and `plan()` helpers, and creates a table of the five segments of a robot arm, each with its length in metres and its angle in radians. The last row has no values: ``` import os import re import adbc_driver_manager import adbc_driver_manager.dbapi as dbapi import adbc_driver_vastdb BUCKET = os.environ["VASTDB_BUCKET"] SCHEMA = f'"{BUCKET}/docs_sql_fn_numeric_cos"' conn = dbapi.connect( driver=adbc_driver_vastdb.get_driver_path(), db_kwargs={ "vast.db.endpoint": os.environ["QE_ENDPOINT"], "vast.db.access_key": os.environ["AWS_ACCESS_KEY_ID"], "vast.db.secret_key": os.environ["AWS_SECRET_ACCESS_KEY"], }, autocommit=True, ) def server_message(e): """The server's message in a driver error, without the request ID or the echoed statement.""" text = re.sub(r"\[req=0x[0-9a-f]+\]: ", "", str(e)) found = (re.search(r'message: "(.*?)", request_id', text, re.S) or re.search(r"description: (.*)\)", text, re.S)) message = found.group(1) if found else text.strip().splitlines()[-1] message = re.sub(r"^Plan query: '.*?' failed with: ", "", message, flags=re.S) message = re.split(r"\\n|\n", message)[0].replace('\\"', '"') return message.replace(BUCKET, "") def run(sql): """Run one statement. Print the rows it returns, or the error.""" try: with conn.cursor() as cur: cur.execute(sql) rows = cur.fetchall() if cur.description else [] except (adbc_driver_manager.Error, OSError) as e: print(f"{type(e).__name__}: {server_message(e)}") else: print(rows) def plan(sql): """Print the plan without its ~N Rows lines: the table's row count, which can still be 0 just after an insert.""" with conn.cursor() as cur: cur.execute("EXPLAIN " + sql) steps = cur.fetchall()[0][1] print("\n".join(line for line in steps.splitlines() if "Rows" not in line)) TABLE = f"{SCHEMA}.joints" run(f"CREATE SCHEMA IF NOT EXISTS {SCHEMA}") run(f"CREATE TABLE IF NOT EXISTS {TABLE} (id BIGINT, joint VARCHAR, len DOUBLE, angle DOUBLE)") run(f"INSERT INTO {TABLE} VALUES " "(1, 'shoulder', 0.5, 1.0), " "(2, 'elbow', 0.4, 2.5), " "(3, 'wrist', 0.2, -1.25), " "(4, 'gripper', 0.1, 0.0), " "(5, NULL, NULL, NULL)") ``` ``` [] [] [(5,)] ``` ## What it does `cos(x)` returns the cosine of the angle `x`, in radians: `cos(0)` is `1.0` and `cos(pi())` is `-1.0`. The cosine is the same for `x` and `-x`, so `cos(-0.0::DOUBLE)` is `1.0` too. The argument is converted to `DOUBLE`, and so is the result, whatever the argument's type. A string of digits is converted too: `cos('12')` returns `0.8438539587324921`. [pi](/develop/docs/dev-database-reference-sql-functions-numeric-pi)`()` is π rounded to a `DOUBLE`, so an angle built from it isn't exact, and neither is its cosine: `cos(pi() / 2)` is `6.123233995736766e-17`, not 0, and `cos(pi() / 3)` is `0.5000000000000001`, not 0.5. Compare results with a tolerance, such as `abs(cos(x)) < 1e-9`, rather than with `=`. Any finite angle works, however large: `cos(1e308)` returns `-0.8913089376870335`. An infinite angle is an error, and `nan` gives `nan`. ## NULLs and edge cases | Input | Result | | --- | --- | | `NULL` | `NULL` | | `0`, `-0.0::DOUBLE` | `1.0` | | `pi() / 3` | `0.5000000000000001` | | `pi() / 2` | `6.123233995736766e-17` | | `pi()` | `-1.0` | | `5e-324::DOUBLE` (the smallest `DOUBLE` above 0) | `1.0` | | `1e308` | `-0.8913089376870335` | | `'nan'::DOUBLE` | `nan` | | `'12'` (a string of digits) | `0.8438539587324921` | | `'inf'::DOUBLE` | Error: `input value inf is out of range for numeric function` | | `'-inf'::DOUBLE` | Error: `input value -inf is out of range for numeric function` | | `'abc'` | Error: `Could not convert string 'abc' to DOUBLE` | | A `BLOB`, date, boolean, list or interval | Error: `No function matches the given name and argument types`, for example `'cos(DATE)'` | The same cases, as the cluster returns them. They use the helpers from [Set up the examples](/develop/docs/dev-database-reference-sql-functions-numeric-cos#set-up-the-examples): ``` run("SELECT cos(NULL), cos(0), cos(-0.0::DOUBLE), cos(pi() / 3), cos(pi() / 2), cos(pi())") run("SELECT cos(5e-324::DOUBLE), cos(1e308), cos('nan'::DOUBLE)") run("SELECT cos('12')") run("SELECT cos('inf'::DOUBLE)") run("SELECT cos('-inf'::DOUBLE)") run("SELECT cos('abc')") run("SELECT cos('\\xAA'::BLOB)") run("SELECT cos(DATE '2026-10-16')") run("SELECT cos(true)") run("SELECT cos([1, 2])") run("SELECT cos(INTERVAL 1 DAY)") ``` ``` [(None, 1.0, 1.0, 0.5000000000000001, 6.123233995736766e-17, -1.0)] [(1.0, -0.8913089376870335, nan)] [(0.8438539587324921,)] OSError: input value inf is out of range for numeric function OSError: input value -inf is out of range for numeric function OSError: Could not convert string 'abc' to DOUBLE InternalError: Binder Error: No function matches the given name and argument types 'cos(BLOB)'. You might need to add explicit type casts. InternalError: Binder Error: No function matches the given name and argument types 'cos(DATE)'. You might need to add explicit type casts. InternalError: Binder Error: No function matches the given name and argument types 'cos(BOOLEAN)'. You might need to add explicit type casts. InternalError: Binder Error: No function matches the given name and argument types 'cos(INTEGER[])'. You might need to add explicit type casts. InternalError: Binder Error: No function matches the given name and argument types 'cos(INTERVAL)'. You might need to add explicit type casts. ``` ## Examples The cosine of each joint's angle, and the horizontal reach of each segment, its length times the cosine of its angle: ``` run(f"SELECT id, joint, cos(angle), len * cos(angle) FROM {TABLE} ORDER BY id LIMIT 10") ``` ``` [(1, 'shoulder', 0.5403023058681398, 0.2701511529340699), (2, 'elbow', -0.8011436155469337, -0.3204574462187735), (3, 'wrist', 0.3153223623952687, 0.06306447247905374), (4, 'gripper', 1.0, 0.1), (5, None, None, None)] ``` An angle in degrees, converted with [radians](/develop/docs/dev-database-reference-sql-functions-numeric-radians) first: ``` run("SELECT cos(radians(60)), cos(radians(180))") ``` ``` [(0.5000000000000001, -1.0)] ``` Keep only the segments that point forwards: ``` run(f"SELECT id, joint FROM {TABLE} WHERE cos(angle) > 0 ORDER BY id LIMIT 10") ``` ``` [(1, 'shoulder'), (3, 'wrist'), (4, 'gripper')] ``` ## How it runs in VAST The Query Engine runs on the cluster's CNodes, and a query on a table starts with a scan in VAST DataBase (`VAST_SCAN`). VAST DataBase can evaluate a comparison of a column with a constant, but not a function of a column, so `cos()` is always computed by the Query Engine: - **In the `SELECT` list,** the scan reads the column and the Query Engine computes `cos()` for each row it returns. - **In `WHERE`,** the scan sends the column for every row, and a `FILTER` step in the Query Engine computes `cos()` and keeps the rows that match. No rows are skipped in storage. The plan of the `WHERE` example shows the `FILTER` step above the scan: ``` plan(f"SELECT id FROM {TABLE} WHERE cos(angle) > 0") ``` ``` ┌───────────────────────────┐ │ PROJECTION │ │ ──────────────────── │ │ #1 │ │ │ └─────────────┬─────────────┘ ┌─────────────┴─────────────┐ │ FILTER │ │ ──────────────────── │ │ (cos(angle) > 0.0) │ │ │ └─────────────┬─────────────┘ ┌─────────────┴─────────────┐ │ VAST_SCAN │ │ ──────────────────── │ │ Function: VAST_SCAN │ │ │ │ Projections: │ │ angle │ │ id │ │ │ └───────────────────────────┘ ``` ## Make it faster - **Convert the constant, not the column.** A function of constants is computed once, and the comparison is pushed down to VAST DataBase, so rows that don't match never leave storage. If your angles lie in a known range, write the condition on the angle itself: for angles from -π to π, `cos(angle) > 0` is `angle > -pi() / 2 AND angle < pi() / 2`. The plan for a comparison with `pi() / 2` has no `FILTER` step: ``` plan(f"SELECT id FROM {TABLE} WHERE angle < pi() / 2") ``` ``` ┌───────────────────────────┐ │ VAST_SCAN │ │ ──────────────────── │ │ Function: VAST_SCAN │ │ Projections: id │ │ │ └───────────────────────────┘ ``` - **Store the cosine if you filter on it often.** Compute it when you write the rows and keep it in its own column: a comparison of that column is pushed down, `cos(angle)` in `WHERE` isn't. - **Combine it with a pushed-down condition.** In `id > 100 AND cos(angle) > 0`, `id > 100` is still evaluated in VAST DataBase, so `cos()` runs only on the rows that pass it. ## Limitations and errors - **Radians only.** There is no degree version: `cosd` fails with `Scalar Function with name cosd does not exist!`. Use `cos(radians(x))`. - **No `sec`.** For the secant, use `1 / cos(x)`. - **Infinite angles are errors.** `cos('inf'::DOUBLE)` fails with `input value inf is out of range for numeric function`, and `'-inf'::DOUBLE` with the same message for `-inf`. Test for them with [isinf](/develop/docs/dev-database-reference-sql-functions-numeric-isinf) or [isfinite](/develop/docs/dev-database-reference-sql-functions-numeric-isfinite). - **One argument, numbers only.** `cos(1, 2)`, a `BLOB`, a date, a boolean, a list or an interval fails with `No function matches the given name and argument types`. A string is converted to `DOUBLE`, so a string that isn't a number fails with `Could not convert string ... to DOUBLE`. ``` run("SELECT cosd(60)") run("SELECT sec(0)") run("SELECT cos(1, 2)") ``` ``` InternalError: Catalog Error: Scalar Function with name cosd does not exist! InternalError: Catalog Error: Scalar Function with name sec does not exist! InternalError: Binder Error: No function matches the given name and argument types 'cos(INTEGER_LITERAL, INTEGER_LITERAL)'. You might need to add explicit type casts. ``` ## Similar functions | Function | Computes | Result for `pi() / 4` | | --- | --- | --- | | `cos(x)` | the cosine | `0.7071067811865476` | | [sin](/develop/docs/dev-database-reference-sql-functions-numeric-sin) | the sine | `0.7071067811865475` | | [tan](/develop/docs/dev-database-reference-sql-functions-numeric-tan) | the tangent, `sin(x) / cos(x)` | `0.9999999999999999` | | [cot](/develop/docs/dev-database-reference-sql-functions-numeric-cot) | the cotangent, `cos(x) / sin(x)` | `1.0000000000000002` | | [acos](/develop/docs/dev-database-reference-sql-functions-numeric-acos) | the inverse: the angle whose cosine is `x` | | | [cosh](/develop/docs/dev-database-reference-sql-functions-numeric-cosh) | the hyperbolic cosine | | ``` run("SELECT cos(pi() / 4), sin(pi() / 4), tan(pi() / 4), cot(pi() / 4)") ``` ``` [(0.7071067811865476, 0.7071067811865475, 0.9999999999999999, 1.0000000000000002)] ``` Clean up: ``` run(f"DROP TABLE IF EXISTS {TABLE}") run(f"DROP SCHEMA IF EXISTS {SCHEMA}") conn.close() ``` ``` [] [] ``` ## See also - [Numeric and math functions](/develop/docs/dev-database-reference-sql-functions-numeric#trigonometry): all the trigonometric functions. - [sin](/develop/docs/dev-database-reference-sql-functions-numeric-sin), [tan](/develop/docs/dev-database-reference-sql-functions-numeric-tan), [acos](/develop/docs/dev-database-reference-sql-functions-numeric-acos), [radians](/develop/docs/dev-database-reference-sql-functions-numeric-radians) and [degrees](/develop/docs/dev-database-reference-sql-functions-numeric-degrees). - [Where filters run](/develop/docs/dev-database-reference-sql-select#where-filters-run) and [pushdowns](/develop/docs/dev-database-reference-pushdowns). - [EXPLAIN](/develop/docs/dev-database-reference-sql-explain): how to read a plan.