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.

sin

Prev Next

Applies to VAST Cluster 5.5.

Functions › Numeric and math functions › Trigonometry. Returns the sine of an angle given in radians, from -1 to 1. For an angle in degrees, convert it first with radians: sin(radians(deg)). It has no aliases.

Syntax

sin(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), and work in a schema called docs_sql_fn_numeric_sin. 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 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_sin"'

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}.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

sin(x) returns the sine of the angle x, in radians: sin(0) is 0.0 and sin(pi() / 2) is 1.0. The argument is converted to DOUBLE, and so is the result, whatever the argument's type. A string of digits is converted too: sin('12') returns -0.5365729180004349.

pi() is π rounded to a DOUBLE, so an angle built from it isn't exact, and neither is its sine: sin(pi()) is 1.2246467991473532e-16, not 0, and sin(pi() / 6) is 0.49999999999999994, not 0.5. Compare results with a tolerance, such as abs(sin(x) - 0.5) < 1e-9, rather than with =.

Any finite angle works, however large: sin(1e308) returns 0.4533964905016491. An infinite angle is an error, and nan gives nan.

NULLs and edge cases

Input Result
NULL NULL
0 0.0
pi() / 6 0.49999999999999994
pi() / 2 1.0
pi() 1.2246467991473532e-16
-0.0::DOUBLE -0.0
5e-324::DOUBLE (the smallest DOUBLE above 0) 5e-324
1e308 0.4533964905016491
'nan'::DOUBLE nan
'12' (a string of digits) -0.5365729180004349
'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 'sin(DATE)'

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

run("SELECT sin(NULL), sin(0), sin(pi() / 6), sin(pi() / 2), sin(pi()), sin(-0.0::DOUBLE)")
run("SELECT sin(5e-324::DOUBLE), sin(1e308), sin('nan'::DOUBLE)")
run("SELECT sin('12')")
run("SELECT sin('inf'::DOUBLE)")
run("SELECT sin('-inf'::DOUBLE)")
run("SELECT sin('abc')")
run("SELECT sin('\\xAA'::BLOB)")
run("SELECT sin(DATE '2026-10-16')")
run("SELECT sin(true)")
run("SELECT sin([1, 2])")
run("SELECT sin(INTERVAL 1 DAY)")
[(None, 0.0, 0.49999999999999994, 1.0, 1.2246467991473532e-16, -0.0)]
[(5e-324, 0.4533964905016491, nan)]
[(-0.5365729180004349,)]
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 'sin(BLOB)'. You might need to add explicit type casts.
InternalError: Binder Error: No function matches the given name and argument types 'sin(DATE)'. You might need to add explicit type casts.
InternalError: Binder Error: No function matches the given name and argument types 'sin(BOOLEAN)'. You might need to add explicit type casts.
InternalError: Binder Error: No function matches the given name and argument types 'sin(INTEGER[])'. You might need to add explicit type casts.
InternalError: Binder Error: No function matches the given name and argument types 'sin(INTERVAL)'. You might need to add explicit type casts.

Examples

The sine of each joint's angle, and the vertical reach of each segment, its length times the sine of its angle:

run(f"SELECT id, joint, sin(angle), len * sin(angle) FROM {TABLE} ORDER BY id LIMIT 10")
[(1, 'shoulder', 0.8414709848078965, 0.42073549240394825), (2, 'elbow', 0.5984721441039565, 0.23938885764158263), (3, 'wrist', -0.9489846193555862, -0.18979692387111724), (4, 'gripper', 0.0, 0.0), (5, None, None, None)]

An angle in degrees, converted with radians first, and an angle in radians shown in degrees with degrees:

run(f"SELECT id, joint, degrees(angle), sin(radians(30)) FROM {TABLE} ORDER BY id LIMIT 10")
[(1, 'shoulder', 57.29577951308232, 0.49999999999999994), (2, 'elbow', 143.2394487827058, 0.49999999999999994), (3, 'wrist', -71.6197243913529, 0.49999999999999994), (4, 'gripper', 0.0, 0.49999999999999994), (5, None, None, 0.49999999999999994)]

Keep only the segments that point upwards:

run(f"SELECT id, joint FROM {TABLE} WHERE sin(angle) > 0 ORDER BY id LIMIT 10")
[(1, 'shoulder'), (2, 'elbow')]

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

  • In the SELECT list, the scan reads the column and the Query Engine computes sin() for each row it returns.
  • In WHERE, the scan sends the column for every row, and a FILTER step in the Query Engine computes sin() 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 sin(angle) > 0")
┌───────────────────────────┐
│         PROJECTION        │
│    ────────────────────   │
│             #1            │
│                           │
└─────────────┬─────────────┘
┌─────────────┴─────────────┐
│           FILTER          │
│    ────────────────────   │
│     (sin(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: angle > radians(90) has no FILTER step, while degrees(angle) > 90 runs in one. The same holds for a range of angles you can write as constants, such as angle > 0 AND angle < pi().
plan(f"SELECT id FROM {TABLE} WHERE angle > radians(90)")
┌───────────────────────────┐
│         VAST_SCAN         │
│    ────────────────────   │
│    Function: VAST_SCAN    │
│      Projections: id      │
│                           │
└───────────────────────────┘
  • Store the sine 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, sin(angle) in WHERE isn't.
  • Combine it with a pushed-down condition. In id > 100 AND sin(angle) > 0, id > 100 is still evaluated in VAST DataBase, so sin() runs only on the rows that pass it.

Limitations and errors

  • Radians only. There is no degree version: sind fails with Scalar Function with name sind does not exist!. Use sin(radians(x)).
  • No csc. For the cosecant, use 1 / sin(x).
  • Infinite angles are errors. sin('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 or isfinite.
  • One argument, numbers only. sin(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 sind(30)")
run("SELECT csc(1)")
run("SELECT sin(1, 2)")
InternalError: Catalog Error: Scalar Function with name sind does not exist!
InternalError: Catalog Error: Scalar Function with name csc does not exist!
InternalError: Binder Error: No function matches the given name and argument types 'sin(INTEGER_LITERAL, INTEGER_LITERAL)'. You might need to add explicit type casts.

Similar functions

Function Computes Result for pi() / 4
sin(x) the sine 0.7071067811865475
cos the cosine 0.7071067811865476
tan the tangent, sin(x) / cos(x) 0.9999999999999999
cot the cotangent, cos(x) / sin(x) 1.0000000000000002
asin the inverse: the angle whose sine is x
sinh the hyperbolic sine
run("SELECT sin(pi() / 4), cos(pi() / 4), tan(pi() / 4), cot(pi() / 4)")
[(0.7071067811865475, 0.7071067811865476, 0.9999999999999999, 1.0000000000000002)]

Clean up:

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

See also