Applies to VAST Cluster 5.5.
Functions › Numeric and math functions › Trigonometry. Returns the tangent of an angle given in radians: sin(x) / cos(x), the slope of a line at that angle. For an angle in degrees, convert it first with radians: tan(radians(deg)). It has no aliases.
Syntax
tan(x)
| Argument | Type | Description |
|---|---|---|
x |
DOUBLE (any integer, DECIMAL or FLOAT is converted) |
The angle, in radians. |
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_tan. 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 five ramps, each with its horizontal run in metres and its angle of incline 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_tan"'
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}.ramps"
run(f"CREATE SCHEMA IF NOT EXISTS {SCHEMA}")
run(f"CREATE TABLE IF NOT EXISTS {TABLE} (id BIGINT, ramp VARCHAR, run_m DOUBLE, angle DOUBLE)")
run(f"INSERT INTO {TABLE} VALUES "
"(1, 'loading dock', 4.0, 0.1), "
"(2, 'garage', 6.0, 0.25), "
"(3, 'stair lift', 2.0, 1.0), "
"(4, 'corridor', 10.0, 0.0), "
"(5, NULL, NULL, NULL)")
[]
[]
[(5,)]
What it does
tan(x) returns the tangent of the angle x, in radians: tan(0) is 0.0, and tan(1) is 1.5574077246549023. It repeats every π, and changes sign with x. The argument is converted to DOUBLE, and so is the result, whatever the argument's type. A string of digits is converted too: tan('12') returns -0.6358599286615808.
pi() is π rounded to a DOUBLE, so an angle built from it isn't exact, and neither is its tangent: tan(pi() / 4) is 0.9999999999999999, not 1, and tan(pi()) is -1.2246467991473532e-16, not 0. At π/2 the tangent isn't defined, but pi() / 2 isn't exactly π/2, so tan(pi() / 2) returns a large finite number, 1.633123935319537e+16, rather than inf or an error.
An infinite angle is an error, and nan gives nan.
NULLs and edge cases
| Input | Result |
|---|---|
NULL |
NULL |
0 |
0.0 |
-0.0::DOUBLE |
-0.0 |
pi() / 4 |
0.9999999999999999 |
pi() / 2 |
1.633123935319537e+16 |
-pi() / 2 |
-1.633123935319537e+16 |
pi() |
-1.2246467991473532e-16 |
5e-324::DOUBLE (the smallest DOUBLE above 0) |
5e-324 |
'nan'::DOUBLE |
nan |
'12' (a string of digits) |
-0.6358599286615808 |
'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 'tan(DATE)' |
The same cases, as the cluster returns them. They use the helpers from Set up the examples:
run("SELECT tan(NULL), tan(0), tan(-0.0::DOUBLE), tan(pi() / 4), tan(pi() / 2), tan(-pi() / 2), tan(pi())")
run("SELECT tan(5e-324::DOUBLE), tan('nan'::DOUBLE)")
run("SELECT tan('12')")
run("SELECT tan('inf'::DOUBLE)")
run("SELECT tan('-inf'::DOUBLE)")
run("SELECT tan('abc')")
run("SELECT tan('\\xAA'::BLOB)")
run("SELECT tan(DATE '2026-10-16')")
run("SELECT tan(true)")
run("SELECT tan([1, 2])")
run("SELECT tan(INTERVAL 1 DAY)")
[(None, 0.0, -0.0, 0.9999999999999999, 1.633123935319537e+16, -1.633123935319537e+16, -1.2246467991473532e-16)]
[(5e-324, nan)]
[(-0.6358599286615808,)]
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 'tan(BLOB)'. You might need to add explicit type casts.
InternalError: Binder Error: No function matches the given name and argument types 'tan(DATE)'. You might need to add explicit type casts.
InternalError: Binder Error: No function matches the given name and argument types 'tan(BOOLEAN)'. You might need to add explicit type casts.
InternalError: Binder Error: No function matches the given name and argument types 'tan(INTEGER[])'. You might need to add explicit type casts.
InternalError: Binder Error: No function matches the given name and argument types 'tan(INTERVAL)'. You might need to add explicit type casts.
Examples
The slope of each ramp, the tangent of its angle, and the height it climbs over its run:
run(f"SELECT id, ramp, tan(angle), run_m * tan(angle) FROM {TABLE} ORDER BY id LIMIT 10")
[(1, 'loading dock', 0.10033467208545055, 0.4013386883418022), (2, 'garage', 0.25534192122103627, 1.5320515273262176), (3, 'stair lift', 1.5574077246549023, 3.1148154493098046), (4, 'corridor', 0.0, 0.0), (5, None, None, None)]
A slope given in degrees, converted with radians first:
run("SELECT tan(radians(45)), tan(radians(5))")
[(0.9999999999999999, 0.08748866352592401)]
Keep only the ramps steeper than a 1 in 5 slope:
run(f"SELECT id, ramp FROM {TABLE} WHERE tan(angle) > 0.2 ORDER BY id LIMIT 10")
[(2, 'garage'), (3, 'stair lift')]
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 tan() is always computed by the Query Engine:
- In the
SELECTlist, the scan reads the column and the Query Engine computestan()for each row it returns. - In
WHERE, the scan sends the column for every row, and aFILTERstep in the Query Engine computestan()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 tan(angle) > 0.2")
┌───────────────────────────┐
│ PROJECTION │
│ ──────────────────── │
│ #1 │
│ │
└─────────────┬─────────────┘
┌─────────────┴─────────────┐
│ FILTER │
│ ──────────────────── │
│ (tan(angle) > 0.2) │
│ │
└─────────────┬─────────────┘
┌─────────────┴─────────────┐
│ VAST_SCAN │
│ ──────────────────── │
│ Function: VAST_SCAN │
│ │
│ Projections: │
│ angle │
│ id │
│ │
└───────────────────────────┘
Make it faster
- Compare the angle, not its tangent. Between -π/2 and π/2 the tangent grows with the angle, so for angles in that range
tan(angle) > 1keeps the same rows asangle > 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 noFILTERstep:
plan(f"SELECT id FROM {TABLE} WHERE angle > pi() / 4")
┌───────────────────────────┐
│ VAST_SCAN │
│ ──────────────────── │
│ Function: VAST_SCAN │
│ Projections: id │
│ │
└───────────────────────────┘
- Store the slope 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,
tan(angle)inWHEREisn't. - Combine it with a pushed-down condition. In
id > 100 AND tan(angle) > 0.2,id > 100is still evaluated in VAST DataBase, sotan()runs only on the rows that pass it.
Limitations and errors
- Radians only. Convert degrees with radians:
tan(radians(x)). - No error or
infat π/2. Near an odd multiple of π/2,tan()returns a very large number, positive or negative. If such angles can occur, test the angle rather than the result. - Infinite angles are errors.
tan('inf'::DOUBLE)fails withinput value inf is out of range for numeric function, and'-inf'::DOUBLEwith the same message for-inf. Test for them with isinf or isfinite. - One argument, numbers only.
tan(1, 2), aBLOB, a date, a boolean, a list or an interval fails withNo function matches the given name and argument types. A string is converted toDOUBLE, so a string that isn't a number fails withCould not convert string ... to DOUBLE. For the angle of a point (x, y), with the right quadrant, use atan2.
run("SELECT tan(pi() / 2), tan(-pi() / 2)")
run("SELECT tan(1, 2)")
[(1.633123935319537e+16, -1.633123935319537e+16)]
InternalError: Binder Error: No function matches the given name and argument types 'tan(INTEGER_LITERAL, INTEGER_LITERAL)'. You might need to add explicit type casts.
Similar functions
| Function | Computes | Result for pi() / 4 |
|---|---|---|
tan(x) |
the tangent | 0.9999999999999999 |
| cot | the cotangent, 1 / tan(x) |
1.0000000000000002 |
1 / tan(x) |
the cotangent, from tan |
1.0000000000000002 |
| sin, cos | the sine and cosine; tan(x) is sin(x) / cos(x) |
0.7071067811865475, 0.7071067811865476 |
| atan | the inverse: the angle whose tangent is x |
|
| tanh | the hyperbolic tangent |
run("SELECT tan(pi() / 4), cot(pi() / 4), 1 / tan(pi() / 4), sin(pi() / 4), cos(pi() / 4)")
[(0.9999999999999999, 1.0000000000000002, 1.0000000000000002, 0.7071067811865475, 0.7071067811865476)]
Clean up:
run(f"DROP TABLE IF EXISTS {TABLE}")
run(f"DROP SCHEMA IF EXISTS {SCHEMA}")
conn.close()
[]
[]
See also
- Numeric and math functions: all the trigonometric functions.
- sin, cos, cot, atan and radians.
- Where filters run and pushdowns.
- EXPLAIN: how to read a plan.