Welcome to the new DOCS.vastdata.com. We've added new menus and a version selector, plus new persona and resource pages to help customers get started. Looking for a previous article? Use the docs search.

quarter

Prev Next

Applies to VAST Cluster 5.5.

Functions › Date and time functions › Parts of a date or time. Returns the quarter of the year, from 1 (January to March) to 4 (October to December), of a date or timestamp.

Syntax

quarter(value)
Argument Type Description
value DATE, TIMESTAMP (also TIMESTAMP_NS, TIMESTAMP_MS, TIMESTAMP_S) or INTERVAL The value to take the quarter of.

Returns: BIGINT.

Same as: date_part('quarter', value) and extract(quarter FROM value); 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_quarter. 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), a timestamp (ts), a time of day (t) and a timestamp with nanoseconds (tns). 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_quarter"'

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, t TIME, tns TIMESTAMP_NS)")
run(f"INSERT INTO {TABLE} VALUES "
    "(1, DATE '2026-02-28', TIMESTAMP '2026-02-28 23:15:00', TIME '23:15:00', "
    "CAST('2026-02-28 23:15:00.123456789' AS TIMESTAMP_NS)), "
    "(2, DATE '2026-03-01', TIMESTAMP '2026-03-01 08:30:45.123456', TIME '08:30:45.123456', "
    "CAST('2026-03-01 08:30:45.123456' AS TIMESTAMP_NS)), "
    "(3, DATE '2024-12-30', TIMESTAMP '2024-12-30 12:00:00', TIME '12:00:00', "
    "CAST('2024-12-30 12:00:00' AS TIMESTAMP_NS)), "
    "(4, NULL, NULL, NULL, NULL), "
    "(5, DATE '1969-12-31', TIMESTAMP '1969-12-31 23:59:59.999999', TIME '23:59:59.999999', "
    "CAST('1969-12-31 23:59:59.999999999' AS TIMESTAMP_NS))")
[]
[]
[(5,)]

What it does

quarter returns which quarter of the calendar year a date or timestamp falls in:

Months Quarter Example Result
January to March 1 quarter(DATE '2026-03-31') 1
April to June 2 quarter(DATE '2026-04-01') 2
July to September 3
October to December 4 quarter(DATE '2026-12-31') 4

Quarters always follow the calendar year. For a fiscal year that starts in another month, shift the date before you take the quarter, or compute it from month.

On an INTERVAL, quarter looks at the months left over after whole years: quarter(INTERVAL '5 months') is 2, and quarter(INTERVAL '14 months'), which is 1 year and 2 months, is 1. A negative interval such as INTERVAL '-1 year -2 months -3 days -04:05:06.789' gives 1.

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' 4
TIMESTAMP '1969-12-31 23:59:59.999999' 4
INTERVAL '5 months' 2
INTERVAL '14 months' 1
INTERVAL '-1 year -2 months -3 days -04:05:06.789' 1
An untyped NULL: quarter(NULL) Error: Could not choose a best candidate function for the function call "quarter("NULL")"
A TIME Error: No function matches the given name and argument types 'quarter(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 'quarter(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, quarter(ts) FROM {TABLE} WHERE id = 4")
run("SELECT quarter(DATE 'infinity'), quarter(TIMESTAMP '-infinity'), quarter(DATE '0001-01-01'), "
    "quarter(DATE '9999-12-31'), quarter(TIMESTAMP '1969-12-31 23:59:59.999999')")
run("SELECT quarter(DATE '2026-03-31'), quarter(DATE '2026-04-01'), quarter(DATE '2026-12-31')")
run("SELECT quarter(INTERVAL '5 months'), quarter(INTERVAL '14 months'), "
    "quarter(INTERVAL '-1 year -2 months -3 days -04:05:06.789')")
run("SELECT quarter(NULL)")
run("SELECT quarter(TIME '13:45:30')")
run("SELECT quarter('2026-03-31')")
run("SELECT quarter(123)")
[(4, None)]
[(None, None, 1, 4, 4)]
[(1, 2, 4)]
[(2, 1, 1)]
InternalError: Binder Error: Could not choose a best candidate function for the function call "quarter("NULL")". In order to select one, please add explicit type casts.
InternalError: Binder Error: No function matches the given name and argument types 'quarter(TIME)'. You might need to add explicit type casts.
InternalError: Binder Error: Could not choose a best candidate function for the function call "quarter(STRING_LITERAL)". In order to select one, please add explicit type casts.
InternalError: Binder Error: No function matches the given name and argument types 'quarter(INTEGER_LITERAL)'. You might need to add explicit type casts.

Examples

The quarter of each event's date and timestamp:

run(f"SELECT id, quarter(d), quarter(ts) FROM {TABLE} ORDER BY id LIMIT 10")
[(1, 1, 1), (2, 1, 1), (3, 4, 4), (4, None, None), (5, 4, 4)]

Label each event with its year and quarter, such as 2026-Q1:

run(f"SELECT id, CAST(year(d) AS VARCHAR) || '-Q' || CAST(quarter(d) AS VARCHAR) FROM {TABLE} ORDER BY id LIMIT 10")
[(1, '2026-Q1'), (2, '2026-Q1'), (3, '2024-Q4'), (4, None), (5, '1969-Q4')]

Keep only the events in the fourth quarter of any year:

run(f"SELECT id FROM {TABLE} WHERE quarter(ts) = 4 ORDER BY id LIMIT 10")
[(3,), (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 quarter() is always computed by the Query Engine:

  • In the SELECT list, the scan reads the column and the Query Engine computes quarter() for each row it returns.
  • In WHERE, the scan sends the column for every row, and a FILTER step in the Query Engine computes quarter() 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 quarter(ts) = 4")
┌───────────────────────────┐
│         PROJECTION        │
│    ────────────────────   │
│             #1            │
│                           │
└─────────────┬─────────────┘
┌─────────────┴─────────────┐
│           FILTER          │
│    ────────────────────   │
│    ("quarter"(ts) = 4)    │
│                           │
└─────────────┬─────────────┘
┌─────────────┴─────────────┐
│         VAST_SCAN         │
│    ────────────────────   │
│    Function: VAST_SCAN    │
│                           │
│        Projections:       │
│             ts            │
│             id            │
│                           │
└───────────────────────────┘

Make it faster

  • For one quarter of one year, filter on a range of the raw column. ts >= TIMESTAMP '2026-01-01 00:00:00' AND ts < TIMESTAMP '2026-04-01 00:00:00' is the first quarter of 2026, and it's pushed down to VAST DataBase, so rows outside it never leave storage. The plan for the range has no FILTER step:
plan(f"SELECT id FROM {TABLE} WHERE ts >= TIMESTAMP '2026-01-01 00:00:00' AND ts < TIMESTAMP '2026-04-01 00:00:00'")
┌───────────────────────────┐
│         VAST_SCAN         │
│    ────────────────────   │
│    Function: VAST_SCAN    │
│      Projections: id      │
│                           │
└───────────────────────────┘
  • Store the quarter if you filter on it across years. quarter(ts) = 4 for every year has no single range. Compute the quarter when you write the rows and keep it in its own column: event_quarter = 4 is pushed down, quarter(ts) = 4 isn't.

Limitations and errors

  • No time-zone support. On a TIMESTAMP WITH TIME ZONE value, such as now(), quarter fails with an Extension Autoloading Error. Cast the value to TIMESTAMP first; see time zones.
  • Not for TIME. quarter(TIME ...) fails with No function matches the given name and argument types 'quarter(TIME)'.
  • TIMESTAMP_NS just before 1970. Row 5's tns, 1969-12-31 23:59:59.999999999, gives 1, not 4. Store such values as TIMESTAMP if you need their quarter.
  • No quarter in strftime or as 'q'. strftime has no quarter code (%q fails with Failed to parse format specifier %q), and date_part('q', ...) fails with extract specifier "q" not recognized. Use quarter() or date_part('quarter', ...).
run(f"SELECT id, quarter(tns), quarter(ts) FROM {TABLE} ORDER BY id LIMIT 10")
run("SELECT strftime(DATE '2026-03-31', '%q')")
run("SELECT date_part('q', DATE '2026-03-31')")
[(1, 1, 1), (2, 1, 1), (3, 4, 4), (4, None, None), (5, 1, 4)]
InternalError: Invalid Input Error: Failed to parse format specifier %q: Unrecognized format for strftime/strptime: %q
InternalError: Conversion Error: extract specifier "q" not recognized

Similar functions

Function Returns Result for DATE '2026-12-31' (quarter gives 4)
month The month, 1 to 12 12
date_trunc with 'quarter' The first day of the quarter, as a DATE 2026-10-01
date_part with 'quarter' The same as quarter 4
to_quarters An INTERVAL of that many quarters, for adding to dates
run("SELECT quarter(DATE '2026-12-31'), month(DATE '2026-12-31'), date_trunc('quarter', DATE '2026-12-31'), "
    "date_part('quarter', DATE '2026-12-31')")
[(4, 12, datetime.date(2026, 10, 1), 4)]

Clean up:

run(f"DROP TABLE IF EXISTS {TABLE}")
run(f"DROP SCHEMA IF EXISTS {SCHEMA}")
conn.close()
[]
[]

See also