--- title: "last_day" slug: "dev-database-reference-sql-functions-date-time-last-day" updated: 2026-10-30T18:19:01Z published: 2026-10-30T18:19:01Z canonical: "docs.vastdata.com/dev-database-reference-sql-functions-date-time-last-day" --- > ## 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. # last_day *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) › Names and calendar.* Returns the last day of the month of a date or timestamp, as a `DATE`. Leap years are taken into account. ## Syntax ``` last_day(value) ``` | Argument | Type | Description | | --- | --- | --- | | `value` | `DATE` or `TIMESTAMP` (also `TIMESTAMP_NS`, `TIMESTAMP_MS`, `TIMESTAMP_S`) | A day in the month. | **Returns:** `DATE`, also for a `TIMESTAMP`. ## 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_last_day`. 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 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, row 5 is a leap day, and row 6 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_last_day"' 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}.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 '2024-02-29', TIMESTAMP '2024-02-29 00:00:00', TIME '00:00:00', " "CAST('2024-02-29 00:00:00' AS TIMESTAMP_NS)), " "(6, 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)), " "(7, DATE '2027-01-03', TIMESTAMP '2027-01-03 00:00:00.5', TIME '00:00:00.000001', " "CAST('2027-01-03 00:00:00.5' AS TIMESTAMP_NS))") ``` ``` [] [] [(7,)] ``` ## What it does `last_day` returns the date of the last day of the month that the value falls in. February follows the Gregorian leap-year rule: a year divisible by 4 is a leap year, except a century year that isn't divisible by 400: | Input | Result | | --- | --- | | `DATE '2024-02-10'` | `2024-02-29` | | `DATE '2023-02-10'` | `2023-02-28` | | `DATE '2000-02-10'` | `2000-02-29` | | `DATE '1900-02-10'` | `1900-02-28` | | `DATE '2026-12-31'` (already the last day) | `2026-12-31` | | `TIMESTAMP '2026-04-30 23:59:59'` | `2026-04-30`, a `DATE`: the time of day is dropped | ## NULLs and edge cases | Input | Result | | --- | --- | | A NULL value (row 4) | `NULL` | | An untyped `NULL`: `last_day(NULL)` | `NULL` | | `DATE 'infinity'`, `TIMESTAMP '-infinity'` | `NULL` | | `DATE '0001-01-01'` | `0001-01-31` | | `DATE '9999-12-31'` | `9999-12-31` | | `TIMESTAMP '1969-12-31 23:59:59.999999'` | `1969-12-31` | | An `INTERVAL` | Error: `No function matches the given name and argument types 'last_day(INTERVAL)'` | | A `TIME` | Error: `No function matches the given name and argument types 'last_day(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 `'last_day(INTEGER_LITERAL)'` | 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-last-day#set-up-the-examples): ``` run(f"SELECT id, last_day(ts) FROM {TABLE} WHERE id = 4") run("SELECT last_day(DATE '2024-02-10'), last_day(DATE '2023-02-10'), last_day(DATE '2000-02-10'), " "last_day(DATE '1900-02-10'), last_day(DATE '2026-12-31')") run("SELECT last_day(TIMESTAMP '2026-04-30 23:59:59'), typeof(last_day(TIMESTAMP '2026-04-30 23:59:59'))") run("SELECT last_day(NULL), last_day(DATE 'infinity'), last_day(TIMESTAMP '-infinity'), " "last_day(DATE '0001-01-01'), last_day(DATE '9999-12-31'), last_day(TIMESTAMP '1969-12-31 23:59:59.999999')") run("SELECT last_day(INTERVAL 1 MONTH)") run("SELECT last_day(TIME '13:45:30')") run("SELECT last_day('2026-03-01')") run("SELECT last_day(123)") ``` ``` [(4, None)] [(datetime.date(2024, 2, 29), datetime.date(2023, 2, 28), datetime.date(2000, 2, 29), datetime.date(1900, 2, 28), datetime.date(2026, 12, 31))] [(datetime.date(2026, 4, 30), 'DATE')] [(None, None, None, datetime.date(1, 1, 31), datetime.date(9999, 12, 31), datetime.date(1969, 12, 31))] InternalError: Binder Error: No function matches the given name and argument types 'last_day(INTERVAL)'. You might need to add explicit type casts. InternalError: Binder Error: No function matches the given name and argument types 'last_day(TIME)'. You might need to add explicit type casts. InternalError: Binder Error: Could not choose a best candidate function for the function call "last_day(STRING_LITERAL)". In order to select one, please add explicit type casts. InternalError: Binder Error: No function matches the given name and argument types 'last_day(INTEGER_LITERAL)'. You might need to add explicit type casts. ``` ## Examples The last day of each event's month: ``` run(f"SELECT id, d, last_day(d), last_day(ts) FROM {TABLE} ORDER BY id LIMIT 10") ``` ``` [(1, datetime.date(2026, 2, 28), datetime.date(2026, 2, 28), datetime.date(2026, 2, 28)), (2, datetime.date(2026, 3, 1), datetime.date(2026, 3, 31), datetime.date(2026, 3, 31)), (3, datetime.date(2024, 12, 30), datetime.date(2024, 12, 31), datetime.date(2024, 12, 31)), (4, None, None, None), (5, datetime.date(2024, 2, 29), datetime.date(2024, 2, 29), datetime.date(2024, 2, 29)), (6, datetime.date(1969, 12, 31), datetime.date(1969, 12, 31), datetime.date(1969, 12, 31)), (7, datetime.date(2027, 1, 3), datetime.date(2027, 1, 31), datetime.date(2027, 1, 31))] ``` The number of days in each event's month is the day of the month of its last day, with [day](/develop/docs/dev-database-reference-sql-functions-date-time-day): ``` run(f"SELECT id, d, day(last_day(d)) FROM {TABLE} ORDER BY id LIMIT 10") ``` ``` [(1, datetime.date(2026, 2, 28), 28), (2, datetime.date(2026, 3, 1), 31), (3, datetime.date(2024, 12, 30), 31), (4, None, None), (5, datetime.date(2024, 2, 29), 29), (6, datetime.date(1969, 12, 31), 31), (7, datetime.date(2027, 1, 3), 31)] ``` Keep only the events on the last day of a month: ``` run(f"SELECT id, d FROM {TABLE} WHERE last_day(d) = d ORDER BY id LIMIT 10") ``` ``` [(1, datetime.date(2026, 2, 28)), (5, datetime.date(2024, 2, 29)), (6, datetime.date(1969, 12, 31))] ``` ## 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 `last_day()` is always computed by the Query Engine: - **In the `SELECT` list,** the scan reads the column and the Query Engine computes `last_day()` for each row it returns. - **In `WHERE`,** the scan sends the column for every row, and a `FILTER` step in the Query Engine computes `last_day()` and keeps the rows that match. No rows are skipped in storage. The plan of the last-day example shows the `FILTER` step above the scan: ``` plan(f"SELECT id, d FROM {TABLE} WHERE last_day(d) = d") ``` ``` ┌───────────────────────────┐ │ PROJECTION │ │ ──────────────────── │ │ id │ │ d │ │ │ └─────────────┬─────────────┘ ┌─────────────┴─────────────┐ │ FILTER │ │ ──────────────────── │ │ (last_day(d) = d) │ │ │ └─────────────┬─────────────┘ ┌─────────────┴─────────────┐ │ VAST_SCAN │ │ ──────────────────── │ │ Function: VAST_SCAN │ │ │ │ Projections: │ │ d │ │ id │ │ │ └───────────────────────────┘ ``` ## Make it faster - **For one month, filter on a range of the raw column.** To select a month, compare the column with its first day and the first day of the next month, such as `d >= DATE '2026-02-01' AND d < DATE '2026-03-01'`, rather than with `last_day(d)`. The range is 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, d FROM {TABLE} WHERE d >= DATE '2026-02-01' AND d < DATE '2026-03-01'") ``` ``` ┌───────────────────────────┐ │ PROJECTION │ │ ──────────────────── │ │ id │ │ d │ │ │ └─────────────┬─────────────┘ ┌─────────────┴─────────────┐ │ VAST_SCAN │ │ ──────────────────── │ │ Function: VAST_SCAN │ │ │ │ Projections: │ │ d │ │ id │ │ │ └───────────────────────────┘ ``` - **Store a flag if you filter on month ends often.** `last_day(d) = d` must be computed for every row. Compute it when you write the rows and keep it in its own column: `is_month_end = true` is pushed down, `last_day(d) = d` isn't. ## Limitations and errors - **No time-zone support.** On a `TIMESTAMP WITH TIME ZONE` value, such as `now()`, `last_day` fails with an `Extension Autoloading Error`. Cast the value to `TIMESTAMP` first; see [time zones](/develop/docs/dev-database-reference-sql-functions-date-time-time-zones). - **Not for `TIME` or `INTERVAL`.** Both fail with `No function matches the given name and argument types`. - **`TIMESTAMP_NS` before 1970.** Row 6's `TIMESTAMP_NS` value `1969-12-31 23:59:59.999999999` gives `1970-01-31`, while the `TIMESTAMP` value `1969-12-31 23:59:59.999999` gives `1969-12-31`. If you need the month of nanosecond values before 1970 that are close to midnight at a month end, check the result or store the value as `TIMESTAMP`. ``` run(f"SELECT id, last_day(tns), last_day(ts) FROM {TABLE} WHERE id = 6") ``` ``` [(6, datetime.date(1970, 1, 31), datetime.date(1969, 12, 31))] ``` ## Similar functions | Expression | Returns | Result for `DATE '2024-02-10'` (`last_day` gives `2024-02-29`) | | --- | --- | --- | | [date_trunc](/develop/docs/dev-database-reference-sql-functions-date-time-date-trunc) `('month', d)` | The first day of the month | `2024-02-01` | | `date_trunc('month', d) + INTERVAL 1 MONTH - INTERVAL 1 DAY` | The last day, as a `TIMESTAMP` at midnight | `2024-02-29 00:00:00` | | The same, cast to `DATE` | The same as `last_day` | `2024-02-29` | | [make_date](/develop/docs/dev-database-reference-sql-functions-date-time-make-date) `(2024, 3, 1) - 1` | The day before a date you build | `2024-02-29` | ``` run("SELECT last_day(DATE '2024-02-10'), date_trunc('month', DATE '2024-02-10'), " "date_trunc('month', DATE '2024-02-10') + INTERVAL 1 MONTH - INTERVAL 1 DAY, " "CAST(date_trunc('month', DATE '2024-02-10') + INTERVAL 1 MONTH - INTERVAL 1 DAY AS DATE), " "make_date(2024, 3, 1) - 1") ``` ``` [(datetime.date(2024, 2, 29), datetime.date(2024, 2, 1), datetime.datetime(2024, 2, 29, 0, 0), datetime.date(2024, 2, 29), datetime.date(2024, 2, 29))] ``` Clean up: ``` run(f"DROP TABLE IF EXISTS {TABLE}") run(f"DROP SCHEMA IF EXISTS {SCHEMA}") conn.close() ``` ``` [] [] ``` ## See also - [date_trunc](/develop/docs/dev-database-reference-sql-functions-date-time-date-trunc): the first day of the month, week or year. - [day](/develop/docs/dev-database-reference-sql-functions-date-time-day) and [month](/develop/docs/dev-database-reference-sql-functions-date-time-month): parts of a date. - [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.