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.

cbrt

Prev Next

Applies to VAST Cluster 5.5.

Functions › Numeric and math functions › Powers and logarithms. Returns the cube root of a number, as a DOUBLE. Unlike a fractional power, it takes negative numbers: cbrt(-8.0::DOUBLE) is -2.0.

Syntax

cbrt(x)
Argument Type Description
x DOUBLE (any number) The number to take the cube root of. It can be negative.

Returns: DOUBLE, whatever the argument type.

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_cbrt. 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 three cube-shaped tanks: the volume of each, and the change in volume since the last reading, which can be negative. 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_cbrt"'

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}.tanks"
run(f"CREATE SCHEMA IF NOT EXISTS {SCHEMA}")
run(f"CREATE TABLE IF NOT EXISTS {TABLE} (id BIGINT, volume DOUBLE, change DOUBLE)")
run(f"INSERT INTO {TABLE} VALUES "
    "(1, 8.0, -8.0), "
    "(2, 1000.0, 125.0), "
    "(3, 2.0, -0.5), "
    "(4, NULL, NULL)")
[]
[]
[(4,)]

What it does

cbrt(x) returns the number whose cube is x. It's defined for every real number, so a negative x gives a negative root: cbrt(-8.0::DOUBLE) is -2.0. That's the difference from a power: pow(-27, 1.0 / 3) is nan, while cbrt(-27) is about -3.

The argument is converted to DOUBLE first, so integers, DECIMAL and FLOAT values all work and all give a DOUBLE; so does a string that holds a number: cbrt('12') is 2.2894284851066633.

The result is rounded to the nearest DOUBLE, so a perfect cube doesn't always give a whole number: cbrt(27) is 3.0000000000000004, and cbrt(27) = 3 is false. Round the result, or compare it with a tolerance, before you test it for equality.

Floating-point special values pass through: inf gives inf, -inf gives -inf, nan gives nan, and -0.0 gives -0.0.

NULLs and edge cases

Input Result
NULL NULL
cbrt(27) 3.0000000000000004
cbrt(-27) -3.0000000000000004
cbrt(-8.0::DOUBLE) -2.0
cbrt(2) 1.2599210498948734
cbrt(0) 0.0
cbrt(-0.0::DOUBLE) -0.0
cbrt(1e300), cbrt(-1e-300) 1e+100, -1e-100
cbrt('inf'::DOUBLE), cbrt('-inf'::DOUBLE), cbrt('nan'::DOUBLE) inf, -inf, nan
cbrt(27) = 3 False
cbrt(27::FLOAT) a DOUBLE
cbrt('12') 2.2894284851066633
cbrt('abc') Error: Could not convert string 'abc' to DOUBLE
A boolean, date, interval, BLOB or list Error: No function matches the given name and argument types, for example 'cbrt(BOOLEAN)'

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

run("SELECT cbrt(NULL), cbrt(27), cbrt(-27), cbrt(-8.0::DOUBLE), cbrt(2)")
run("SELECT cbrt(0), cbrt(-0.0::DOUBLE), cbrt(1e300), cbrt(-1e-300)")
run("SELECT cbrt('inf'::DOUBLE), cbrt('-inf'::DOUBLE), cbrt('nan'::DOUBLE), cbrt(27) = 3, typeof(cbrt(27::FLOAT))")
run(f"SELECT cbrt('12') FROM {TABLE} LIMIT 1")
run(f"SELECT cbrt('abc') FROM {TABLE} LIMIT 1")
run("SELECT cbrt(true)")
[(None, 3.0000000000000004, -3.0000000000000004, -2.0, 1.2599210498948734)]
[(0.0, -0.0, 1e+100, -1e-100)]
[(inf, -inf, nan, False, 'DOUBLE')]
[(2.2894284851066633,)]
OSError: Could not convert string 'abc' to DOUBLE
InternalError: Binder Error: No function matches the given name and argument types 'cbrt(BOOLEAN)'. You might need to add explicit type casts.

Examples

The side of each tank, and the cube root of the change in volume, which keeps its sign:

run(f"SELECT id, cbrt(volume), cbrt(change) FROM {TABLE} ORDER BY id LIMIT 10")
[(1, 2.0, -2.0), (2, 10.0, 5.0), (3, 1.2599210498948734, -0.7937005259840998), (4, None, None)]

Keep only the tanks with a side longer than 5:

run(f"SELECT id, volume FROM {TABLE} WHERE cbrt(volume) > 5 ORDER BY id LIMIT 10")
[(2, 1000.0)]

Round before you compare a root with a whole number:

run("SELECT cbrt(27), cbrt(27) = 3, round(cbrt(27), 9) = 3")
[(3.0000000000000004, False, True)]

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

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

Make it faster

  • Cube the constant instead. A larger number always has a larger cube root, so cbrt(volume) > 5 is the same as volume > 125, and that comparison of the raw column with a constant is pushed down to VAST DataBase, so rows that don't match never leave storage. Its plan has no FILTER step:
plan(f"SELECT id FROM {TABLE} WHERE volume > 125")
┌───────────────────────────┐
│         VAST_SCAN         │
│    ────────────────────   │
│    Function: VAST_SCAN    │
│      Projections: id      │
│                           │
└───────────────────────────┘
  • Store the root if you filter on it often. Compute it when you write the rows and keep it in its own column.
  • Combine it with a pushed-down condition. In id > 100 AND cbrt(volume) > 5, id > 100 is still evaluated in VAST DataBase, so cbrt() runs only on the rows that pass it.

Limitations and errors

  • Numbers only. A boolean, date, interval, BLOB or list fails with No function matches the given name and argument types; the error lists the one form cbrt accepts, cbrt(DOUBLE) -> DOUBLE. A string is converted when the query runs, and one that isn't a number fails with Could not convert string 'abc' to DOUBLE.
  • Not exact. See What it does: round before you test a root for equality.
  • No cube_root. It fails with Scalar Function with name cube_root does not exist!. Use cbrt.
run("SELECT cube_root(8)")
InternalError: Catalog Error: Scalar Function with name cube_root does not exist!

Similar functions

Function Computes Result for 27 Result for -27
cbrt(x) the cube root 3.0000000000000004 -3.0000000000000004
pow (x, 1.0 / 3) the cube root of a non-negative number, as a power 3.0 nan
sqrt the square root; a negative number fails sqrt(1024) is 32.0 (error)
run("SELECT cbrt(27), pow(27, 1.0 / 3), cbrt(-27), pow(-27, 1.0 / 3)")
run("SELECT sqrt(1024), cbrt(1024)")
[(3.0000000000000004, 3.0, -3.0000000000000004, nan)]
[(32.0, 10.079368399158987)]

Clean up:

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

See also