Welcome to the new DOCS.vastdata.com. We've added new menus and a version selector, plus new persona and resource pages to help customers get started. Looking for a previous article? Use the docs search.

cot

Prev Next

Applies to VAST Cluster 5.5.

Functions › Numeric and math functions › Trigonometry. Returns the cotangent of an angle given in radians: cos(x) / sin(x), or 1 divided by the tangent. For an angle in degrees, convert it first with radians: cot(radians(deg)). It has no aliases.

Syntax

cot(x)
Argument Type Description
x DOUBLE (any integer, DECIMAL or FLOAT is converted) The angle, in radians. It can't be 0.

Returns: DOUBLE.

Aliases: none.

Set up the examples

The examples connect with the ADBC driver, as in VAST Query Engine (ADBC), and work in a schema called docs_sql_fn_numeric_cot. Set QE_ENDPOINT, AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY and VASTDB_BUCKET (SQL reference), 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 four readings of a 10-metre mast, each with the sun's elevation above the horizon 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_cot"'

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, "<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}.shadows"
run(f"CREATE SCHEMA IF NOT EXISTS {SCHEMA}")
run(f"CREATE TABLE IF NOT EXISTS {TABLE} (id BIGINT, reading VARCHAR, height_m DOUBLE, elevation DOUBLE)")
run(f"INSERT INTO {TABLE} VALUES "
    "(1, 'noon', 10.0, 1.0), "
    "(2, 'afternoon', 10.0, 0.5), "
    "(3, 'evening', 10.0, 0.25), "
    "(4, NULL, NULL, NULL)")
[]
[]
[(4,)]

What it does

cot(x) returns the cotangent of the angle x, in radians: cot(1) is 0.6420926159343306. The argument is converted to DOUBLE, and so is the result, whatever the argument's type. A string of digits is converted too: cot('12') returns -1.5726734063976893.

pi() is π rounded to a DOUBLE, so an angle built from it isn't exact, and neither is its cotangent: cot(pi() / 4) is 1.0000000000000002, not 1, and cot(pi() / 2) is 6.123233995736766e-17, not 0. At π the cotangent isn't defined, but pi() isn't exactly π, so cot(pi()) returns a large finite number, -8165619676597685.0.

At 0, cot() is an error, not infinity: cot(0) fails with input value 0.000000 is out of range for numeric function cotangent. Very small angles other than 0 work and give very large results: cot(1e-300) is 9.999999999999999e+299, and cot(5e-324::DOUBLE) is inf. 1 / tan(x) computes the same cotangent, but doesn't fail at 0: 1 / tan(0.0::DOUBLE) returns inf.

NULLs and edge cases

Input Result
NULL NULL
1 0.6420926159343306
pi() / 4 1.0000000000000002
pi() / 2 6.123233995736766e-17
pi() -8165619676597685.0
1e-300 9.999999999999999e+299
5e-324::DOUBLE (the smallest DOUBLE above 0) inf
'nan'::DOUBLE nan
'12' (a string of digits) -1.5726734063976893
0 Error: input value 0.000000 is out of range for numeric function cotangent
-0.0::DOUBLE Error: input value -0.000000 is out of range for numeric function cotangent
'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 'cot(DATE)'

The same cases, as the cluster returns them. They use the helpers from Set up the examples:

run("SELECT cot(NULL), cot(1), cot(pi() / 4), cot(pi() / 2), cot(pi()), cot(1e-300)")
run("SELECT cot(5e-324::DOUBLE), cot('nan'::DOUBLE)")
run("SELECT cot('12')")
run("SELECT cot(0)")
run("SELECT cot(-0.0::DOUBLE)")
run("SELECT cot('inf'::DOUBLE)")
run("SELECT cot('-inf'::DOUBLE)")
run("SELECT cot('abc')")
run("SELECT cot('\\xAA'::BLOB)")
run("SELECT cot(DATE '2026-10-16')")
run("SELECT cot(true)")
run("SELECT cot([1, 2])")
run("SELECT cot(INTERVAL 1 DAY)")
[(None, 0.6420926159343306, 1.0000000000000002, 6.123233995736766e-17, -8165619676597685.0, 9.999999999999999e+299)]
[(inf, nan)]
[(-1.5726734063976893,)]
OSError: input value 0.000000 is out of range for numeric function cotangent
OSError: input value -0.000000 is out of range for numeric function cotangent
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 'cot(BLOB)'. You might need to add explicit type casts.
InternalError: Binder Error: No function matches the given name and argument types 'cot(DATE)'. You might need to add explicit type casts.
InternalError: Binder Error: No function matches the given name and argument types 'cot(BOOLEAN)'. You might need to add explicit type casts.
InternalError: Binder Error: No function matches the given name and argument types 'cot(INTEGER[])'. You might need to add explicit type casts.
InternalError: Binder Error: No function matches the given name and argument types 'cot(INTERVAL)'. You might need to add explicit type casts.

Examples

The length of the mast's shadow at each reading: its height times the cotangent of the sun's elevation. The lower the sun, the longer the shadow:

run(f"SELECT id, reading, cot(elevation), height_m * cot(elevation) FROM {TABLE} ORDER BY id LIMIT 10")
[(1, 'noon', 0.6420926159343306, 6.420926159343306), (2, 'afternoon', 1.830487721712452, 18.30487721712452), (3, 'evening', 3.91631736464594, 39.1631736464594), (4, None, None, None)]

An elevation given in degrees, converted with radians first:

run("SELECT cot(radians(45)), 10 * cot(radians(30))")
[(1.0000000000000002, 17.320508075688775)]

Keep only the readings where the shadow is longer than the mast:

run(f"SELECT id, reading FROM {TABLE} WHERE cot(elevation) > 1 ORDER BY id LIMIT 10")
[(2, 'afternoon'), (3, 'evening')]

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 cot() is always computed by the Query Engine:

  • In the SELECT list, the scan reads the column and the Query Engine computes cot() for each row it returns.
  • In WHERE, the scan sends the column for every row, and a FILTER step in the Query Engine computes cot() 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 cot(elevation) > 1")
┌───────────────────────────┐
│         PROJECTION        │
│    ────────────────────   │
│             #1            │
│                           │
└─────────────┬─────────────┘
┌─────────────┴─────────────┐
│           FILTER          │
│    ────────────────────   │
│   (cot(elevation) > 1.0)  │
│                           │
└─────────────┬─────────────┘
┌─────────────┴─────────────┐
│         VAST_SCAN         │
│    ────────────────────   │
│    Function: VAST_SCAN    │
│                           │
│        Projections:       │
│         elevation         │
│             id            │
│                           │
└───────────────────────────┘

Make it faster

  • Compare the angle, not its cotangent. Between 0 and π the cotangent falls as the angle grows, so for angles in that range cot(elevation) > 1 keeps the same rows as elevation < pi() / 4, up to rounding at the boundary itself. A function of constants is computed once, and the comparison of the raw column is pushed down to VAST DataBase, so rows that don't match never leave storage. The plan has no FILTER step:
plan(f"SELECT id FROM {TABLE} WHERE elevation < pi() / 4")
┌───────────────────────────┐
│         VAST_SCAN         │
│    ────────────────────   │
│    Function: VAST_SCAN    │
│      Projections: id      │
│                           │
└───────────────────────────┘
  • Store the cotangent 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, cot(elevation) in WHERE isn't.
  • Combine it with a pushed-down condition. In id > 100 AND cot(elevation) > 1, id > 100 is still evaluated in VAST DataBase, so cot() runs only on the rows that pass it.

Limitations and errors

  • An angle of 0 is an error. cot(0) fails with input value 0.000000 is out of range for numeric function cotangent, and -0.0 with the same message for -0.000000. On a table, one row with an angle of 0 fails the whole query, not just that row. Keep zeros out of the column, or use 1 / tan(x), which returns inf for 0.
  • Infinite angles are errors. cot('inf'::DOUBLE) fails with input value inf is out of range for numeric function, and '-inf'::DOUBLE with the same message for -inf.
  • Radians only. Convert degrees with radians: cot(radians(x)).
  • One argument, numbers only. cot(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 cot(0)")
run("SELECT 1 / tan(0.0::DOUBLE)")
run("SELECT cot(1, 2)")
OSError: input value 0.000000 is out of range for numeric function cotangent
[(inf,)]
InternalError: Binder Error: No function matches the given name and argument types 'cot(INTEGER_LITERAL, INTEGER_LITERAL)'. You might need to add explicit type casts.

Similar functions

Function Computes Result for pi() / 4 Result for 0
cot(x) the cotangent 1.0000000000000002 Error
1 / tan(x) the cotangent, from tan 1.0000000000000002 inf (for 0.0::DOUBLE)
tan the tangent, 1 / cot(x) 0.9999999999999999 0.0
sin, cos the sine and cosine; cot(x) is cos(x) / sin(x) 0.7071067811865475, 0.7071067811865476 0.0, 1.0
run("SELECT cot(pi() / 4), 1 / tan(pi() / 4), tan(pi() / 4), sin(pi() / 4), cos(pi() / 4)")
run("SELECT 1 / tan(0.0::DOUBLE), tan(0), sin(0), cos(0)")
[(1.0000000000000002, 1.0000000000000002, 0.9999999999999999, 0.7071067811865475, 0.7071067811865476)]
[(inf, 0.0, 0.0, 1.0)]

Clean up:

run(f"DROP TABLE IF EXISTS {TABLE}")
run(f"DROP SCHEMA IF EXISTS {SCHEMA}")
conn.close()
[]
[]

See also