Applies to VAST Cluster 5.5.
Functions › Date and time functions › Parts of a date or time. Returns the millennium of a date or timestamp, counted from year 1: the years 2001 to 3000 are millennium 3. On an interval, it returns the whole millennia in its years.
Syntax
millennium(value)
| Argument | Type | Description |
|---|---|---|
value |
DATE, TIMESTAMP (also TIMESTAMP_NS, TIMESTAMP_MS, TIMESTAMP_S) or INTERVAL |
The value to take the millennium of. |
Returns: BIGINT.
Same as: date_part('millennium', value) and extract(millennium FROM value); the part also has the names mil, millennia and millenniums. See date_part.
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_date_time_millennium. 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 events. Each has a date (d) and a timestamp (ts). Rows 2 and 3 are either side of the start of the 3rd millennium, row 4 has no values, and row 5 is the last moment of 1969:
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_millennium"'
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}.events"
run(f"CREATE SCHEMA IF NOT EXISTS {SCHEMA}")
run(f"CREATE TABLE IF NOT EXISTS {TABLE} (id BIGINT, d DATE, ts TIMESTAMP)")
run(f"INSERT INTO {TABLE} VALUES "
"(1, DATE '2026-02-28', TIMESTAMP '2026-02-28 23:15:00'), "
"(2, DATE '2000-12-31', TIMESTAMP '2000-12-31 12:00:00'), "
"(3, DATE '2001-01-01', TIMESTAMP '2001-01-01 00:00:00'), "
"(4, NULL, NULL), "
"(5, DATE '1969-12-31', TIMESTAMP '1969-12-31 23:59:59.999999')")
[]
[]
[(5,)]
What it does
millennium counts millennia from year 1: the 1st millennium is years 1 to 1000, the 2nd is 1001 to 2000, and the 3rd is 2001 to 3000. So millennium(DATE '2000-12-31') is 2 and millennium(DATE '2001-01-01') is 3. The last date a DATE can hold, 9999-12-31, is in millennium 10. It works on every timestamp precision.
Years before year 1 are in millennium -1: both 44 BC and 1 BC give -1.
On an INTERVAL, millennium returns the whole millennia in its years: millennium(INTERVAL '2500 years') is 2. An interval of less than 1000 years gives 0.
NULLs and edge cases
| Input | Result |
|---|---|
| A NULL value (row 4) | NULL |
DATE 'infinity', TIMESTAMP '-infinity' |
NULL |
DATE '0001-01-01' |
1 |
DATE '9999-12-31' |
10 |
44 BC: CAST('0044-03-15 (BC)' AS DATE) |
-1 |
1 BC: CAST('0001-01-01 (BC)' AS DATE) |
-1 |
INTERVAL '2500 years' |
2 |
INTERVAL '25 months 40 days 30 hours' |
0 |
An untyped NULL: millennium(NULL) |
Error: Could not choose a best candidate function for the function call "millennium("NULL")" |
A TIME |
Error: No function matches the given name and argument types 'millennium(TIME)' |
| A string | Error: Could not choose a best candidate function; cast it to DATE first |
A number, boolean, BLOB or list |
Error: No function matches the given name and argument types, for example 'millennium(INTEGER_LITERAL)' |
The same cases, as the cluster returns them. They use the table and helpers from Set up the examples:
run(f"SELECT id, millennium(d), millennium(ts) FROM {TABLE} WHERE id = 4")
run("SELECT millennium(DATE 'infinity'), millennium(TIMESTAMP '-infinity'), millennium(DATE '0001-01-01'), "
"millennium(DATE '9999-12-31'), millennium(CAST('0044-03-15 (BC)' AS DATE)), "
"millennium(CAST('0001-01-01 (BC)' AS DATE))")
run("SELECT millennium(INTERVAL '2500 years'), millennium(INTERVAL '25 months 40 days 30 hours')")
run("SELECT millennium(NULL)")
run("SELECT millennium(TIME '13:45:30')")
run("SELECT millennium('2024-02-29')")
run("SELECT millennium(123)")
[(4, None, None)]
[(None, None, 1, 10, -1, -1)]
[(2, 0)]
InternalError: Binder Error: Could not choose a best candidate function for the function call "millennium("NULL")". In order to select one, please add explicit type casts.
InternalError: Binder Error: No function matches the given name and argument types 'millennium(TIME)'. You might need to add explicit type casts.
InternalError: Binder Error: Could not choose a best candidate function for the function call "millennium(STRING_LITERAL)". In order to select one, please add explicit type casts.
InternalError: Binder Error: No function matches the given name and argument types 'millennium(INTEGER_LITERAL)'. You might need to add explicit type casts.
Examples
The millennium of each event's date and timestamp, next to its year. Rows 2 and 3 are a day apart but in different millennia:
run(f"SELECT id, year(d), millennium(d), millennium(ts) FROM {TABLE} ORDER BY id LIMIT 10")
[(1, 2026, 3, 3), (2, 2000, 2, 2), (3, 2001, 3, 3), (4, None, None, None), (5, 1969, 2, 2)]
Keep only the events from the 2nd millennium. This works, but Make it faster has a faster way to write it:
run(f"SELECT id FROM {TABLE} WHERE millennium(d) = 2 ORDER BY id LIMIT 10")
[(2,), (5,)]
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 millennium() is always computed by the Query Engine:
- In the
SELECTlist, the scan reads the column and the Query Engine computesmillennium()for each row it returns. - In
WHERE, the scan sends the column for every row, and aFILTERstep in the Query Engine computesmillennium()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 millennium(d) = 2")
┌───────────────────────────┐
│ PROJECTION │
│ ──────────────────── │
│ #1 │
│ │
└─────────────┬─────────────┘
┌─────────────┴─────────────┐
│ FILTER │
│ ──────────────────── │
│ ("millennium"(d) = 2) │
│ │
└─────────────┬─────────────┘
┌─────────────┴─────────────┐
│ VAST_SCAN │
│ ──────────────────── │
│ Function: VAST_SCAN │
│ │
│ Projections: │
│ d │
│ id │
│ │
└───────────────────────────┘
Make it faster
- Filter on a range of the raw column, not on
millennium().d >= DATE '1001-01-01' AND d < DATE '2001-01-01'returns the same rows asmillennium(d) = 2, and it's pushed down to VAST DataBase, so rows from other millennia never leave storage. The plan for the range has noFILTERstep:
run(f"SELECT id FROM {TABLE} WHERE d >= DATE '1001-01-01' AND d < DATE '2001-01-01' ORDER BY id LIMIT 10")
plan(f"SELECT id FROM {TABLE} WHERE d >= DATE '1001-01-01' AND d < DATE '2001-01-01'")
[(2,), (5,)]
┌───────────────────────────┐
│ VAST_SCAN │
│ ──────────────────── │
│ Function: VAST_SCAN │
│ Projections: id │
│ │
└───────────────────────────┘
Limitations and errors
- Dates and timestamps only, not
TIME. A time of day has no year, somillennium(TIME ...)fails withNo function matches the given name and argument types 'millennium(TIME)'. - No time-zone support. On a
TIMESTAMP WITH TIME ZONEvalue, such asnow(),millenniumfails with anExtension Autoloading Error. Cast the value toTIMESTAMPfirst; see time zones. date_trunc('millennium', ...)uses other boundaries. It returns the first day of a year that's a multiple of 1000:date_trunc('millennium', DATE '2026-03-01')is2000-01-01, a day thatmillennium()puts in the 2nd millennium. To get the first day of the millennium thatmillennium()reports, usemake_date((millennium(d) - 1) * 1000 + 1, 1, 1).
run("SELECT millennium(DATE '2026-03-01'), date_trunc('millennium', DATE '2026-03-01'), "
"millennium(date_trunc('millennium', DATE '2026-03-01')), "
"make_date((millennium(DATE '2026-03-01') - 1) * 1000 + 1, 1, 1)")
[(3, datetime.date(2000, 1, 1), 2, datetime.date(2001, 1, 1))]
Similar functions
| Function | Returns | Result for DATE '2000-12-31' (millennium gives 2) |
|---|---|---|
| year | The calendar year | 2000 |
| decade | The year divided by 10 | 200 |
| century | The century, counted from year 1 | 20 |
date_trunc with 'millennium' |
The first day of a year that's a multiple of 1000, as a DATE |
2000-01-01 |
run("SELECT millennium(DATE '2000-12-31'), year(DATE '2000-12-31'), decade(DATE '2000-12-31'), "
"century(DATE '2000-12-31'), date_trunc('millennium', DATE '2000-12-31')")
[(2, 2000, 200, 20, datetime.date(2000, 1, 1))]
Clean up:
run(f"DROP TABLE IF EXISTS {TABLE}")
run(f"DROP SCHEMA IF EXISTS {SCHEMA}")
conn.close()
[]
[]
See also
- date_part: any part of a value, by name.
- Date and time functions: all the date and time functions.
- Where filters run and pushdowns.
- EXPLAIN: how to read a plan.