--- title: "fmod" slug: "dev-database-reference-sql-functions-numeric-fmod" updated: 2026-10-30T18:18:51Z published: 2026-10-30T18:18:51Z canonical: "docs.vastdata.com/dev-database-reference-sql-functions-numeric-fmod" --- > ## 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. # fmod *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) › Arithmetic.* Returns the remainder of `a` divided by `b` when the quotient is rounded down, as a `DOUBLE`. The remainder has the sign of `b`, so `fmod(-5.5, 2)` is `0.5`. It goes with [fdiv](/develop/docs/dev-database-reference-sql-functions-numeric-fdiv): for ordinary values, `a = fdiv(a, b) * b + fmod(a, b)`. ## Syntax ``` fmod(a, b) ``` | Argument | Type | Description | | --- | --- | --- | | `a` | Any number | The dividend. | | `b` | Any number | The divisor. | **Returns:** `DOUBLE`, for every numeric input 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_fmod`. 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 seven pairs of numbers `a` and `b`. Rows 4 and 5 are compass headings with `b` = 360; 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_fmod"' 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}.pairs" run(f"CREATE SCHEMA IF NOT EXISTS {SCHEMA}") run(f"CREATE TABLE IF NOT EXISTS {TABLE} (id BIGINT, a DOUBLE, b DOUBLE)") run(f"INSERT INTO {TABLE} VALUES " "(1, 5.5, 2), " "(2, -5.5, 2), " "(3, 5.5, -2), " "(4, 370, 360), " "(5, -90, 360), " "(6, 7, 0), " "(7, NULL, NULL)") ``` ``` [] [] [(7,)] ``` ## What it does `fmod(a, b)` divides `a` by `b`, rounds the quotient down (towards minus infinity), and returns what's left. For finite values the result lies between 0 and `b`, so it has the sign of `b`: | Call | Quotient rounded down | Result | | --- | --- | --- | | `fmod(5.5, 2)` | `2` | `1.5` | | `fmod(-5.5, 2)` | `-3` | `0.5` | | `fmod(5.5, -2)` | `-3` | `-0.5` | | `fmod(5, 3)` | `1` | `2.0` | | `fmod(-5, 3)` | `-2` | `1.0` | This differs from `%` and `mod()`, whose remainder has the sign of `a`: `-5.5 % 2` is `-1.5`. `fmod` is the one to use to bring a value into a range that starts at 0, such as a heading in degrees into 0 to 360. ## NULLs and edge cases | Input | Result | | --- | --- | | `a` or `b` is `NULL` | `NULL` | | `b` = 0, also `0` by `0` | `nan` | | `a` infinite, or `b` infinite | `nan` | | `a` is `NaN` | `nan` | | `fmod(1e308, 1e-308)` | `-inf` | | `fmod(2.5, 1.5)` | `1.0` | | `fmod(7::DECIMAL(4,1), 2)` | `1.0`, a `DOUBLE` | | `fmod(-9223372036854775808, -1)` | `0.0` | | `'7'` (a string) | Error: `No function matches the given name and argument types 'floor(INTERVAL)'` | 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-fmod#set-up-the-examples): ``` run("SELECT fmod(NULL, 2), fmod(1, NULL), fmod(5, 0), fmod(5.0, 0.0), fmod(0, 0)") run("SELECT fmod('inf'::DOUBLE, 1), fmod(1, 'inf'::DOUBLE), fmod('NaN'::DOUBLE, 1), fmod(1e308, 1e-308)") run("SELECT fmod(2.5, 1.5), fmod(7::DECIMAL(4,1), 2), fmod(-9223372036854775808, -1), typeof(fmod(5, 2))") run("SELECT fmod('7', 2)") ``` ``` [(None, None, nan, nan, nan)] [(nan, nan, nan, -inf)] [(1.0, 1.0, 0.0, 'DOUBLE')] InternalError: Binder Error: No function matches the given name and argument types 'floor(INTERVAL)'. You might need to add explicit type casts. ``` ## Examples The remainder for each pair, and the matching quotient from [fdiv](/develop/docs/dev-database-reference-sql-functions-numeric-fdiv). Row 5 turns a heading of -90 degrees into 270, and row 6 divides by zero: ``` run(f"SELECT id, a, b, fmod(a, b), fdiv(a, b) FROM {TABLE} ORDER BY id LIMIT 10") ``` ``` [(1, 5.5, 2.0, 1.5, 2.0), (2, -5.5, 2.0, 0.5, -3.0), (3, 5.5, -2.0, -0.5, -3.0), (4, 370.0, 360.0, 10.0, 1.0), (5, -90.0, 360.0, 270.0, -1.0), (6, 7.0, 0.0, nan, inf), (7, None, None, None, None)] ``` The rows with an even `id`: ``` run(f"SELECT id FROM {TABLE} WHERE fmod(id, 2) = 0 ORDER BY id LIMIT 10") ``` ``` [(2,), (4,), (6,)] ``` ## 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 `fmod()` is always computed by the Query Engine: - **In the `SELECT` list,** the scan reads the columns and the Query Engine computes `fmod()` for each row it returns. - **In `WHERE`,** the scan sends the columns for every row, and a `FILTER` step in the Query Engine computes `fmod()` 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 fmod(id, 2) = 0") ``` ``` ┌───────────────────────────┐ │ FILTER │ │ ──────────────────── │ │ ((CAST(id AS DOUBLE) - (2 │ │ .0 * floor((CAST(id AS │ │ DOUBLE) / 2.0)))) = 0.0) │ │ │ └─────────────┬─────────────┘ ┌─────────────┴─────────────┐ │ VAST_SCAN │ │ ──────────────────── │ │ Function: VAST_SCAN │ │ Projections: id │ │ │ └───────────────────────────┘ ``` ## Make it faster - **Combine it with a pushed-down condition.** In `id > 3 AND fmod(a, b) > 0`, `id > 3` is a comparison of a raw column with a constant, which VAST DataBase evaluates, so `fmod()` runs only on the rows that pass it. Compare its plan with the one above: ``` plan(f"SELECT id FROM {TABLE} WHERE id > 3 AND fmod(a, b) > 0") ``` ``` ┌───────────────────────────┐ │ PROJECTION │ │ ──────────────────── │ │ #0 │ │ │ └─────────────┬─────────────┘ ┌─────────────┴─────────────┐ │ FILTER │ │ ──────────────────── │ │ ((a - (b * floor((a / b)))│ │ ) > 0.0) │ │ │ └─────────────┬─────────────┘ ┌─────────────┴─────────────┐ │ VAST_SCAN │ │ ──────────────────── │ │ Function: VAST_SCAN │ │ │ │ Projections: │ │ id │ │ a │ │ b │ │ │ └───────────────────────────┘ ``` - **Store the remainder if you filter on it often.** Compute it when you write the rows and keep it in its own column, which a comparison with a constant can then filter in storage. ## Limitations and errors - **The result is always a `DOUBLE`,** also for integers: `fmod(5, 3)` is `2.0`. Cast it if you need an integer: `CAST(fmod(5, 3) AS BIGINT)`. - **Division by zero returns `nan`, not an error and not `NULL`.** Test for it with `isnan()`, or guard the divisor: `fmod(a, NULLIF(b, 0))` returns `NULL` instead. - **Numbers only.** A date, boolean, list or `BLOB` fails with an error that names the division `fmod` performs, for example `No function matches the given name and argument types '/(DATE, INTEGER_LITERAL)'`. A string, even a numeric one, fails with `'floor(INTERVAL)'`. Cast strings to a number first. ``` run("SELECT CAST(fmod(5, 3) AS BIGINT), isnan(fmod(1, 0)), fmod(1, NULLIF(0, 0))") run("SELECT fmod(DATE '2026-10-16', 2)") run("SELECT fmod(CAST('7' AS DOUBLE), 2)") ``` ``` [(2, True, None)] InternalError: Binder Error: No function matches the given name and argument types '/(DATE, INTEGER_LITERAL)'. You might need to add explicit type casts. [(1.0,)] ``` ## Similar functions | Function | Does | `-5.5` by `2` | `5` by `3` | | --- | --- | --- | --- | | `fmod` | the remainder of rounding the quotient down, with the sign of `b`, as a `DOUBLE` | `0.5` | `2.0` | | [% and mod](/develop/docs/dev-database-reference-sql-functions-operators-modulo) | the remainder of truncating the quotient, with the sign of `a` | `-1.5` | `2` | | [fdiv](/develop/docs/dev-database-reference-sql-functions-numeric-fdiv) | the quotient that goes with `fmod` | `-3.0` | `1.0` | | [// (integer division)](/develop/docs/dev-database-reference-sql-functions-operators-integer-division) | the quotient that goes with `%` | | `1` | ``` run("SELECT fmod(-5.5, 2), -5.5 % 2, mod(-5.5, 2), fdiv(-5.5, 2)") run("SELECT fmod(5, 3), 5 % 3, mod(5, 3), fdiv(5, 3), 5 // 3") ``` ``` [(0.5, Decimal('-1.5'), Decimal('-1.5'), -3.0)] [(2.0, 2, 2, 1.0, 1)] ``` 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. - [fdiv](/develop/docs/dev-database-reference-sql-functions-numeric-fdiv), [% and mod](/develop/docs/dev-database-reference-sql-functions-operators-modulo) and [floor](/develop/docs/dev-database-reference-sql-functions-numeric-floor). - [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.