--- title: "to_days" slug: "dev-database-reference-sql-functions-date-time-to-days" updated: 2026-10-30T18:19:01Z published: 2026-10-30T18:19:01Z canonical: "docs.vastdata.com/dev-database-reference-sql-functions-date-time-to-days" --- > ## 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. # to_days *Applies to VAST Cluster 5.5.* *[Functions](/develop/docs/dev-database-reference-sql-functions-index) › [Date and time functions](/develop/docs/dev-database-reference-sql-functions-date-time) › Interval constructors.* Returns an interval of `n` days, the same as `INTERVAL n DAY`. Add it to a date or a timestamp, or subtract it, to move by that many days. ## Syntax ``` to_days(n) ``` | Argument | Type | Description | | --- | --- | --- | | `n` | `INTEGER`; also `SMALLINT`, or a string that holds a whole number | The number of days. It can be negative. | **Returns:** `INTERVAL`. **Same as:** `INTERVAL n DAY` for a constant `n`. ## 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_date_time_to_days`. 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 five tasks. Each has a start time (`ts`), a date (`d`), a whole number (`n`, an `INTEGER`) and a number with a fraction (`f`, a `DOUBLE`). Row 4 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_date_time_to_days"' 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}.tasks" run(f"CREATE SCHEMA IF NOT EXISTS {SCHEMA}") run(f"CREATE TABLE IF NOT EXISTS {TABLE} (id BIGINT, ts TIMESTAMP, d DATE, n INTEGER, f DOUBLE)") run(f"INSERT INTO {TABLE} VALUES " "(1, TIMESTAMP '2026-02-28 23:15:00', DATE '2026-01-31', 1, 1.5), " "(2, TIMESTAMP '2026-03-01 08:30:45.123456', DATE '2026-03-01', -2, -0.25), " "(3, TIMESTAMP '2024-12-30 12:00:00', DATE '2024-12-30', 0, 0.0), " "(4, NULL, NULL, NULL, NULL), " "(5, TIMESTAMP '2024-02-29 00:00:00', DATE '2024-02-29', 12, 0.000001)") ``` ``` [] [] [(5,)] ``` ## What it does An `INTERVAL` has three parts: months, days and a time part. ADBC returns it as an Arrow month-day-nanosecond interval, which Python prints as `MonthDayNano(months=..., days=..., nanoseconds=...)`. The parts are kept apart: they're combined only when the interval is added to a date or a timestamp. `to_days(n)` puts `n` in the days part: `to_days(2)` is `days=2`. A day moves the date and keeps the time of day: `TIMESTAMP '2024-02-29 00:00:00' + to_days(1)` is `2024-03-01 00:00:00`, and `DATE '2026-01-31' + to_days(1)` is `2026-02-01 00:00:00`, a `TIMESTAMP`. Days aren't turned into months on their own: `normalized_interval(to_days(100))` turns 100 days into 3 months and 10 days. Where days have to be compared with a time, a day counts as 24 hours: `INTERVAL 1 DAY = INTERVAL 24 HOUR` is true, and `epoch(to_days(1))` is `86400.0` seconds. ## NULLs and edge cases | Input | Result | | --- | --- | | `NULL`, or a NULL value (row 4) | `NULL` | | `0` | An empty interval: every part is `0` | | `-1` | A negative interval: one day back | | `'2'` (a string) | The same as `to_days(2)` | | `CAST(2 AS SMALLINT)` | The same as `to_days(2)` | | A `BIGINT`, such as `CAST(2 AS BIGINT)` or a `BIGINT` column | Error: `No function matches the given name and argument types 'to_days(BIGINT)'`; cast it to `INTEGER` | | A fraction, such as `1.5` | Error: `No function matches the given name and argument types 'to_days(DECIMAL(2,1))'` | | `2147483647` | The largest accepted value | | `2147483648` | Error: `No function matches the given name and argument types 'to_days(INTEGER_LITERAL)'` | | A `DATE`, `INTERVAL` or `BOOLEAN` | Error: `No function matches the given name and argument types`, for example `'to_days(DATE)'` | 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-date-time-to-days#set-up-the-examples): ``` run(f"SELECT id, to_days(n) FROM {TABLE} WHERE id = 4") run("SELECT to_days(NULL), to_days(0), to_days(-1), to_days('2'), to_days(CAST(2 AS SMALLINT))") run("SELECT to_days(CAST(2 AS BIGINT))") run("SELECT to_days(1.5)") run("SELECT to_days(2147483647)") run("SELECT to_days(2147483648)") run("SELECT to_days(DATE '2026-01-01')") ``` ``` [(4, None)] [(None, MonthDayNano(months=0, days=0, nanoseconds=0), MonthDayNano(months=0, days=-1, nanoseconds=0), MonthDayNano(months=0, days=2, nanoseconds=0), MonthDayNano(months=0, days=2, nanoseconds=0))] InternalError: Binder Error: No function matches the given name and argument types 'to_days(BIGINT)'. You might need to add explicit type casts. InternalError: Binder Error: No function matches the given name and argument types 'to_days(DECIMAL(2,1))'. You might need to add explicit type casts. [(MonthDayNano(months=0, days=2147483647, nanoseconds=0),)] InternalError: Binder Error: No function matches the given name and argument types 'to_days(INTEGER_LITERAL)'. You might need to add explicit type casts. InternalError: Binder Error: No function matches the given name and argument types 'to_days(DATE)'. You might need to add explicit type casts. ``` ## Examples An interval of `n` days for each task: ``` run(f"SELECT id, n, to_days(n) FROM {TABLE} ORDER BY id LIMIT 10") ``` ``` [(1, 1, MonthDayNano(months=0, days=1, nanoseconds=0)), (2, -2, MonthDayNano(months=0, days=-2, nanoseconds=0)), (3, 0, MonthDayNano(months=0, days=0, nanoseconds=0)), (4, None, None), (5, 12, MonthDayNano(months=0, days=12, nanoseconds=0))] ``` Move each start time by `n` days, and the last day of January by one day: ``` run(f"SELECT id, ts, ts + to_days(n) FROM {TABLE} ORDER BY id LIMIT 10") run("SELECT DATE '2026-01-31' + to_days(1), TIMESTAMP '2024-02-29 00:00:00' + to_days(1), TIMESTAMP '2024-02-29 00:00:00' - to_days(1)") ``` ``` [(1, datetime.datetime(2026, 2, 28, 23, 15), datetime.datetime(2026, 3, 1, 23, 15)), (2, datetime.datetime(2026, 3, 1, 8, 30, 45, 123456), datetime.datetime(2026, 2, 27, 8, 30, 45, 123456)), (3, datetime.datetime(2024, 12, 30, 12, 0), datetime.datetime(2024, 12, 30, 12, 0)), (4, None, None), (5, datetime.datetime(2024, 2, 29, 0, 0), datetime.datetime(2024, 3, 12, 0, 0))] [(datetime.datetime(2026, 2, 1, 0, 0), datetime.datetime(2024, 3, 1, 0, 0), datetime.datetime(2024, 2, 28, 0, 0))] ``` Keep only the tasks that, moved by `n` days, end after midnight on 1 March 2026: ``` run(f"SELECT id FROM {TABLE} WHERE ts + to_days(n) > TIMESTAMP '2026-03-01 00:00:00' ORDER BY id LIMIT 10") ``` ``` [(1,)] ``` ## 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 an interval built from a column is always computed by the Query Engine: - **In the `SELECT` list,** the scan reads the column and the Query Engine computes `to_days()` for each row it returns. - **In `WHERE`,** the scan sends the columns for every row, and a `FILTER` step in the Query Engine computes `ts + to_days(n)` 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 ts + to_days(n) > TIMESTAMP '2026-03-01 00:00:00'") ``` ``` ┌───────────────────────────┐ │ PROJECTION │ │ ──────────────────── │ │ #2 │ │ │ └─────────────┬─────────────┘ ┌─────────────┴─────────────┐ │ FILTER │ │ ──────────────────── │ │ ((ts + to_days(n)) > '2026│ │ -03-01 00:00:00': │ │ :TIMESTAMP) │ │ │ └─────────────┬─────────────┘ ┌─────────────┴─────────────┐ │ VAST_SCAN │ │ ──────────────────── │ │ Function: VAST_SCAN │ │ │ │ Projections: │ │ ts │ │ n │ │ id │ │ │ └───────────────────────────┘ ``` ## Make it faster - **Put the interval on the constant side.** `ts > TIMESTAMP '2026-01-15 00:00:00' + to_days(30)` compares the raw column with a constant, so it's pushed down to VAST DataBase and rows that don't match never leave storage. `ts + to_days(30) > ...` needs the `FILTER` step. The plan has no `FILTER` step: ``` plan(f"SELECT id FROM {TABLE} WHERE ts > TIMESTAMP '2026-01-15 00:00:00' + to_days(30)") ``` ``` ┌───────────────────────────┐ │ VAST_SCAN │ │ ──────────────────── │ │ Function: VAST_SCAN │ │ Projections: id │ │ │ └───────────────────────────┘ ``` - **Store the result if you filter on it often.** When the number of days comes from a column, as `n` does here, there's no single constant to compare with. Compute `ts + to_days(n)` when you write the rows and keep it in its own `TIMESTAMP` column; a comparison of that column with a constant is pushed down. ## Limitations and errors - **`INTEGER` only.** A `BIGINT`, the type of most ID and count columns, fails with `No function matches the given name and argument types 'to_days(BIGINT)'`. Cast it with `CAST(id AS INTEGER)`. A fraction fails the same way: use [to_hours](/develop/docs/dev-database-reference-sql-functions-date-time-to-hours) or [to_seconds](/develop/docs/dev-database-reference-sql-functions-date-time-to-seconds) for part of a day. - **Range.** `to_days(2147483647)` is the largest accepted value; `to_days(2147483648)` fails with `No function matches the given name and argument types 'to_days(INTEGER_LITERAL)'`: the number doesn't fit in an `INTEGER`. - **No `INTERVAL` columns.** A table can't have an `INTERVAL` column: `CREATE TABLE` fails with `INTERVAL type is not supported in table definitions`. Store the number of days in a number column and build the interval with `to_days()` in the query. ``` run(f"SELECT id, to_days(id) FROM {TABLE} ORDER BY id LIMIT 10") run(f"SELECT id, to_days(CAST(id AS INTEGER)) FROM {TABLE} ORDER BY id LIMIT 10") run(f"CREATE TABLE {SCHEMA}.durations (id BIGINT, v INTERVAL)") ``` ``` InternalError: Binder Error: No function matches the given name and argument types 'to_days(BIGINT)'. You might need to add explicit type casts. [(1, MonthDayNano(months=0, days=1, nanoseconds=0)), (2, MonthDayNano(months=0, days=2, nanoseconds=0)), (3, MonthDayNano(months=0, days=3, nanoseconds=0)), (4, MonthDayNano(months=0, days=4, nanoseconds=0)), (5, MonthDayNano(months=0, days=5, nanoseconds=0))] InternalError: Binder Error: INTERVAL type is not supported in table definitions. Column "v" has type: INTERVAL ``` ## Similar functions | Function or form | What it builds | Result | | --- | --- | --- | | `INTERVAL 1 DAY` | The same interval, written as a literal | `to_days(1) = INTERVAL 1 DAY` is `true` | | `INTERVAL (n) DAY` | The same interval; `n` can be a column | | | [to_weeks](/develop/docs/dev-database-reference-sql-functions-date-time-to-weeks) | Seven days each | | | [to_hours](/develop/docs/dev-database-reference-sql-functions-date-time-to-hours) | A time part, not days; `to_days(1) = to_hours(24)` is true | `to_days(1) = to_hours(24)` is `true` | | [date_add](/develop/docs/dev-database-reference-sql-functions-date-time-date-add) | Adds an interval to a date or timestamp: `date_add(ts, to_days(1))` is `ts + to_days(1)` | | | [normalized_interval](/develop/docs/dev-database-reference-sql-functions-date-time-normalized-interval) | Rewrites an interval so that 30 days become a month and 24 hours a day | | ``` run("SELECT to_days(1) = INTERVAL 1 DAY, to_days(1) = to_hours(24)") run(f"SELECT id, to_days(CAST(id AS INTEGER)) = INTERVAL (id) DAY FROM {TABLE} ORDER BY id LIMIT 10") run("SELECT date_add(TIMESTAMP '2024-02-29 00:00:00', to_days(1)), normalized_interval(to_days(100))") ``` ``` [(True, True)] [(1, True), (2, True), (3, True), (4, True), (5, True)] [(datetime.datetime(2024, 3, 1, 0, 0), MonthDayNano(months=3, days=10, nanoseconds=0))] ``` Clean up: ``` run(f"DROP TABLE IF EXISTS {SCHEMA}.durations") run(f"DROP TABLE IF EXISTS {TABLE}") run(f"DROP SCHEMA IF EXISTS {SCHEMA}") conn.close() ``` ``` [] [] [] ``` ## See also - The other interval constructors: [to_years](/develop/docs/dev-database-reference-sql-functions-date-time-to-years), [to_quarters](/develop/docs/dev-database-reference-sql-functions-date-time-to-quarters), [to_months](/develop/docs/dev-database-reference-sql-functions-date-time-to-months), [to_weeks](/develop/docs/dev-database-reference-sql-functions-date-time-to-weeks), [to_hours](/develop/docs/dev-database-reference-sql-functions-date-time-to-hours), [to_minutes](/develop/docs/dev-database-reference-sql-functions-date-time-to-minutes), [to_seconds](/develop/docs/dev-database-reference-sql-functions-date-time-to-seconds), [to_milliseconds](/develop/docs/dev-database-reference-sql-functions-date-time-to-milliseconds), [to_microseconds](/develop/docs/dev-database-reference-sql-functions-date-time-to-microseconds). - [Date and time functions](/develop/docs/dev-database-reference-sql-functions-date-time): all the date and time functions. - [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.