Applies to VAST Cluster 5.5.
Functions › Date and time functions › Parts of a date or time. Returns the century of a date or timestamp, counted from year 1: the years 2001 to 2100 are century 21. On an interval, it returns the whole centuries in its years.
Syntax
century(value)
| Argument | Type | Description |
|---|---|---|
value |
DATE, TIMESTAMP (also TIMESTAMP_NS, TIMESTAMP_MS, TIMESTAMP_S) or INTERVAL |
The value to take the century of. |
Returns: BIGINT.
Same as: date_part('century', value) and extract(century FROM value); the part also has the names c, cent and centuries. 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_century. 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 21st century, 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_century"'
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
century counts centuries from year 1, as in "the 21st century": the 1st century is years 1 to 100, and the 21st is years 2001 to 2100. So century(DATE '2000-12-31') is 20 and century(DATE '2001-01-01') is 21. It works on every timestamp precision.
Years before year 1 have negative centuries: 44 BC and 1 BC are both in century -1.
On an INTERVAL, century returns the whole centuries in its years: century(INTERVAL '250 years') is 2. An interval of less than 100 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' |
100 |
DATE '1900-06-01' |
19 |
44 BC: CAST('0044-03-15 (BC)' AS DATE) |
-1 |
1 BC: CAST('0001-01-01 (BC)' AS DATE) |
-1 |
INTERVAL '250 years' |
2 |
INTERVAL '1 year 2 months 3 days 04:05:06.789' |
0 |
An untyped NULL: century(NULL) |
Error: Could not choose a best candidate function for the function call "century("NULL")" |
A TIME |
Error: No function matches the given name and argument types 'century(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 'century(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, century(d), century(ts) FROM {TABLE} WHERE id = 4")
run("SELECT century(DATE 'infinity'), century(TIMESTAMP '-infinity'), century(DATE '0001-01-01'), "
"century(DATE '9999-12-31'), century(DATE '1900-06-01'), century(CAST('0044-03-15 (BC)' AS DATE)), "
"century(CAST('0001-01-01 (BC)' AS DATE))")
run("SELECT century(INTERVAL '250 years'), century(INTERVAL '1 year 2 months 3 days 04:05:06.789')")
run("SELECT century(NULL)")
run("SELECT century(TIME '13:45:30')")
run("SELECT century('2024-02-29')")
run("SELECT century(123)")
[(4, None, None)]
[(None, None, 1, 100, 19, -1, -1)]
[(2, 0)]
InternalError: Binder Error: Could not choose a best candidate function for the function call "century("NULL")". In order to select one, please add explicit type casts.
InternalError: Binder Error: No function matches the given name and argument types 'century(TIME)'. You might need to add explicit type casts.
InternalError: Binder Error: Could not choose a best candidate function for the function call "century(STRING_LITERAL)". In order to select one, please add explicit type casts.
InternalError: Binder Error: No function matches the given name and argument types 'century(INTEGER_LITERAL)'. You might need to add explicit type casts.
Examples
The century of each event's date and timestamp, next to its year. Rows 2 and 3 are a day apart but in different centuries:
run(f"SELECT id, year(d), century(d), century(ts) FROM {TABLE} ORDER BY id LIMIT 10")
[(1, 2026, 21, 21), (2, 2000, 20, 20), (3, 2001, 21, 21), (4, None, None, None), (5, 1969, 20, 20)]
Keep only the events from the 21st century. This works, but Make it faster has a faster way to write it:
run(f"SELECT id FROM {TABLE} WHERE century(d) = 21 ORDER BY id LIMIT 10")
[(1,), (3,)]
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 century() is always computed by the Query Engine:
- In the
SELECTlist, the scan reads the column and the Query Engine computescentury()for each row it returns. - In
WHERE, the scan sends the column for every row, and aFILTERstep in the Query Engine computescentury()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 century(d) = 21")
┌───────────────────────────┐
│ PROJECTION │
│ ──────────────────── │
│ #1 │
│ │
└─────────────┬─────────────┘
┌─────────────┴─────────────┐
│ FILTER │
│ ──────────────────── │
│ ("century"(d) = 21) │
│ │
└─────────────┬─────────────┘
┌─────────────┴─────────────┐
│ VAST_SCAN │
│ ──────────────────── │
│ Function: VAST_SCAN │
│ │
│ Projections: │
│ d │
│ id │
│ │
└───────────────────────────┘
Make it faster
- Filter on a range of the raw column, not on
century().d >= DATE '2001-01-01' AND d < DATE '2101-01-01'returns the same rows ascentury(d) = 21, and it's pushed down to VAST DataBase, so rows from other centuries never leave storage. The plan for the range has noFILTERstep:
run(f"SELECT id FROM {TABLE} WHERE d >= DATE '2001-01-01' AND d < DATE '2101-01-01' ORDER BY id LIMIT 10")
plan(f"SELECT id FROM {TABLE} WHERE d >= DATE '2001-01-01' AND d < DATE '2101-01-01'")
[(1,), (3,)]
┌───────────────────────────┐
│ VAST_SCAN │
│ ──────────────────── │
│ Function: VAST_SCAN │
│ Projections: id │
│ │
└───────────────────────────┘
Limitations and errors
- Dates and timestamps only, not
TIME. A time of day has no year, socentury(TIME ...)fails withNo function matches the given name and argument types 'century(TIME)'. - No time-zone support. On a
TIMESTAMP WITH TIME ZONEvalue, such asnow(),centuryfails with anExtension Autoloading Error. Cast the value toTIMESTAMPfirst; see time zones. date_trunc('century', ...)uses other boundaries. It returns the first day of a year that's a multiple of 100:date_trunc('century', DATE '2026-03-01')is2000-01-01, a day thatcentury()puts in the 20th century. To get the first day of the century thatcentury()reports, usemake_date((century(d) - 1) * 100 + 1, 1, 1).
run("SELECT century(DATE '2026-03-01'), date_trunc('century', DATE '2026-03-01'), "
"century(date_trunc('century', DATE '2026-03-01')), "
"make_date((century(DATE '2026-03-01') - 1) * 100 + 1, 1, 1)")
[(21, datetime.date(2000, 1, 1), 20, datetime.date(2001, 1, 1))]
Similar functions
| Function | Returns | Result for DATE '2000-12-31' (century gives 20) |
|---|---|---|
| year | The calendar year | 2000 |
| decade | The year divided by 10 | 200 |
| millennium | The millennium, counted from year 1 | 2 |
date_trunc with 'century' |
The first day of a year that's a multiple of 100, as a DATE |
2000-01-01 |
run("SELECT century(DATE '2000-12-31'), year(DATE '2000-12-31'), decade(DATE '2000-12-31'), "
"millennium(DATE '2000-12-31'), date_trunc('century', DATE '2000-12-31')")
[(20, 2000, 200, 2, 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.