--- title: "sqrt" slug: "dev-database-reference-sql-functions-numeric-sqrt" updated: 2026-10-30T18:18:51Z published: 2026-10-30T18:18:51Z canonical: "docs.vastdata.com/dev-database-reference-sql-functions-numeric-sqrt" --- > ## 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. # sqrt *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) › Powers and logarithms.* Returns the square root of a number, as a `DOUBLE`. A negative number fails the query. ## Syntax ``` sqrt(x) ``` | Argument | Type | Description | | --- | --- | --- | | `x` | `DOUBLE` (any number) | The number to take the square root of. It must not 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)](/develop/docs/dev-database-integrations-adbc), and work in a schema called `docs_sql_fn_numeric_sqrt`. 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 three square plots: the area of each, and the offset `dx`, `dy` of its corner from a survey point. One `dx` is 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_sqrt"' 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}.plots" run(f"CREATE SCHEMA IF NOT EXISTS {SCHEMA}") run(f"CREATE TABLE IF NOT EXISTS {TABLE} (id BIGINT, area DOUBLE, dx DOUBLE, dy DOUBLE)") run(f"INSERT INTO {TABLE} VALUES " "(1, 16.0, 3.0, 4.0), " "(2, 2.0, -6.0, 8.0), " "(3, 0.25, 1.0, -1.0), " "(4, NULL, NULL, NULL)") ``` ``` [] [] [(4,)] ``` ## What it does `sqrt(x)` returns the non-negative number whose square is `x`: `sqrt(4)` is `2.0` and `sqrt(2.25)` is `1.5`. 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: `sqrt('12')` is `3.4641016151377544`. **A negative number is an error,** not NaN: `sqrt(-1)` fails with `cannot take square root of a negative number`. The error stops the whole query: if one row of a column is negative, `sqrt()` of that column fails for every row. Keep negative values away from it with `WHERE` or `CASE`; see [Limitations and errors](/develop/docs/dev-database-reference-sql-functions-numeric-sqrt#limitations-and-errors). Floating-point special values pass through: `sqrt('inf'::DOUBLE)` is `inf`, `sqrt('nan'::DOUBLE)` is `nan`, and `sqrt(-0.0::DOUBLE)` is `-0.0`, a negative zero, which isn't an error. `'-inf'::DOUBLE` is negative and fails. ## NULLs and edge cases | Input | Result | | --- | --- | | `NULL` | `NULL` | | `sqrt(4)` | `2.0` | | `sqrt(2)` | `1.4142135623730951` | | `sqrt(2.25)` (a `DECIMAL`) | `1.5` | | `sqrt(-0.0::DOUBLE)` | `-0.0` | | `sqrt('inf'::DOUBLE)` | `inf` | | `sqrt('nan'::DOUBLE)` | `nan` | | `sqrt(5e-324::DOUBLE)` (the smallest `DOUBLE` above 0) | `2.2227587494850775e-162` | | `sqrt('12')` | `3.4641016151377544` | | `sqrt(-1)`, `sqrt(-1e-300)`, `sqrt('-inf'::DOUBLE)` | Error: `cannot take square root of a negative number` | | `sqrt('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 `'sqrt(BOOLEAN)'` | The same cases, as the cluster returns them. They use the table and helpers from [Set up the examples](/develop/docs/dev-database-reference-sql-functions-numeric-sqrt#set-up-the-examples): ``` run("SELECT sqrt(NULL), sqrt(4), sqrt(2), sqrt(2.25), typeof(sqrt(4)), typeof(sqrt(2.25))") run("SELECT sqrt(-0.0::DOUBLE), sqrt('inf'::DOUBLE), sqrt('nan'::DOUBLE), sqrt(5e-324::DOUBLE)") run(f"SELECT sqrt('12') FROM {TABLE} LIMIT 1") run("SELECT sqrt(-1)") run("SELECT sqrt(-1e-300)") run("SELECT sqrt('-inf'::DOUBLE)") run(f"SELECT sqrt('abc') FROM {TABLE} LIMIT 1") run("SELECT sqrt(true)") ``` ``` [(None, 2.0, 1.4142135623730951, 1.5, 'DOUBLE', 'DOUBLE')] [(-0.0, inf, nan, 2.2227587494850775e-162)] [(3.4641016151377544,)] OSError: cannot take square root of a negative number OSError: cannot take square root of a negative number OSError: cannot take square root of a negative number OSError: Could not convert string 'abc' to DOUBLE InternalError: Binder Error: No function matches the given name and argument types 'sqrt(BOOLEAN)'. You might need to add explicit type casts. ``` ## Examples The side of each square plot, and the straight-line distance of its corner from the survey point, `sqrt(dx * dx + dy * dy)`: ``` run(f"SELECT id, sqrt(area), sqrt(dx * dx + dy * dy) FROM {TABLE} ORDER BY id LIMIT 10") ``` ``` [(1, 4.0, 5.0), (2, 1.4142135623730951, 10.0), (3, 0.5, 1.4142135623730951), (4, None, None)] ``` Keep only the plots with a side longer than 1: ``` run(f"SELECT id, area FROM {TABLE} WHERE sqrt(area) > 1 ORDER BY id LIMIT 10") ``` ``` [(1, 16.0), (2, 2.0)] ``` ## 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 `sqrt()` of a column is always computed by the Query Engine: - **In the `SELECT` list,** the scan reads the column and the Query Engine computes `sqrt()` for each row it returns. - **In `WHERE`,** the scan sends the column for every row, and a `FILTER` step in the Query Engine computes `sqrt()` and keeps the rows that match. No rows are skipped in storage. `sqrt()` of a constant is different: it's computed once, before the scan, so `area > sqrt(0.25)` is a comparison with a constant and is pushed down. The plan of the `WHERE` example shows the `FILTER` step above the scan: ``` plan(f"SELECT id FROM {TABLE} WHERE sqrt(area) > 1") ``` ``` ┌───────────────────────────┐ │ PROJECTION │ │ ──────────────────── │ │ #1 │ │ │ └─────────────┬─────────────┘ ┌─────────────┴─────────────┐ │ FILTER │ │ ──────────────────── │ │ (sqrt(area) > 1.0) │ │ │ └─────────────┬─────────────┘ ┌─────────────┴─────────────┐ │ VAST_SCAN │ │ ──────────────────── │ │ Function: VAST_SCAN │ │ │ │ Projections: │ │ area │ │ id │ │ │ └───────────────────────────┘ ``` ## Make it faster - **Square the constant instead.** For a column that isn't negative, `sqrt(area) > 2` is the same as `area > 4`, 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 area > 4") ``` ``` ┌───────────────────────────┐ │ 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 sqrt(area) > 2`, `id > 100` is still evaluated in VAST DataBase, so `sqrt()` runs only on the rows that pass it. ## Limitations and errors - **A negative value fails the whole query.** `sqrt(dx)` fails with `cannot take square root of a negative number` because one row has a negative `dx`, and returns no rows at all. To skip the negative rows, filter them out with a pushed-down condition such as `WHERE dx >= 0`. To keep them in the result with a NULL, use `CASE WHEN dx >= 0 THEN sqrt(dx) END`. - **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 `sqrt` accepts, `sqrt(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`. - **No `hypot` or `square`.** Both fail with `Scalar Function with name ... does not exist!`. Write `sqrt(x * x + y * y)` for `hypot(x, y)`, and `x * x` for `square(x)`. ``` run(f"SELECT sqrt(dx) FROM {TABLE}") run(f"SELECT id, sqrt(dx) FROM {TABLE} WHERE dx >= 0 ORDER BY id LIMIT 10") run(f"SELECT id, CASE WHEN dx >= 0 THEN sqrt(dx) END FROM {TABLE} ORDER BY id LIMIT 10") run("SELECT hypot(3, 4)") run("SELECT sqrt(3 * 3 + 4 * 4)") ``` ``` OSError: cannot take square root of a negative number [(1, 1.7320508075688772), (3, 1.0)] [(1, 1.7320508075688772), (2, None), (3, 1.0), (4, None)] InternalError: Catalog Error: Scalar Function with name hypot does not exist! [(5.0,)] ``` ## Similar functions | Function | Computes | Result for 2 (`sqrt` gives `1.4142135623730951`) | | --- | --- | --- | | [pow](/develop/docs/dev-database-reference-sql-functions-numeric-pow) `(x, 0.5)`, `x ** 0.5` | the same root, as a power; a negative `x` gives `nan` instead of an error | `1.4142135623730951` | | [cbrt](/develop/docs/dev-database-reference-sql-functions-numeric-cbrt) | the cube root; takes negative numbers | `1.2599210498948734` | ``` run("SELECT sqrt(2), pow(2, 0.5), 2 ** 0.5, cbrt(2)") run("SELECT pow(-1, 0.5), pow(-2, 0.5)") ``` ``` [(1.4142135623730951, 1.4142135623730951, 1.4142135623730951, 1.2599210498948734)] [(nan, nan)] ``` 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): all the numeric functions. - [pow](/develop/docs/dev-database-reference-sql-functions-numeric-pow) and [cbrt](/develop/docs/dev-database-reference-sql-functions-numeric-cbrt). - [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.