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.

list_min

Prev Next

Applies to VAST Cluster 5.5.

Functions › List, struct and map functions › Aggregate a list. Returns the smallest element of a list, one value per row. NULL elements are skipped. It's the same as list_aggregate(l, 'min').

Syntax

list_min(l)
Argument Type Description
l a list of any type whose values can be ordered The list whose smallest element you want.

Returns: the element type of l.

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_lists_list_min. 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 rows of lists (numbers, measurements, words, flags and lists of lists). Row 3 has empty lists and 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_lists_list_min"'

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}.samples"
run(f"CREATE SCHEMA IF NOT EXISTS {SCHEMA}")
run(f"CREATE TABLE IF NOT EXISTS {TABLE} (id BIGINT, nums BIGINT[], vals DOUBLE[], words VARCHAR[], flags BOOLEAN[], nested BIGINT[][])")
run(f"INSERT INTO {TABLE} VALUES "
    "(1, [1, 2, 3], [0.5, 2.5, -1.0], ['a', 'b', 'c'], [true, false, true], [[1, 2], [3]]), "
    "(2, [3, NULL, 3], [2.0, NULL], ['b', NULL, 'B'], [NULL, true], [[], NULL, [4]]), "
    "(3, [], [], [], [], []), "
    "(4, NULL, NULL, NULL, NULL, NULL), "
    "(5, [-5, 0, -5, 10], [1e308, 1e308, -1e-308], ['\u00e9', 'Zo\u00eb', '\U0001F1EB\U0001F1F7', ''], [false, false], [[5, NULL], [], [6, 7, 8]])")
[]
[]
[(5,)]

What it does

list_min(l) compares the elements of l that aren't NULL and returns the smallest. list_min([3, 1, 2]) returns 1, and list_min([NULL, 2, 1]) returns 1.

How elements are compared depends on their type:

Element type Smallest is Example Result
Numbers the lowest value; -inf is below every number list_min(['NaN'::DOUBLE, 1.0, -'inf'::DOUBLE]) -inf
Text the first by character code: 'A' before 'a', 'e' before 'é' list_min(['b', 'A', 'a']), list_min(['é', 'e', 'f']) 'A', 'e'
Dates the earliest list_min([DATE '2026-01-02', DATE '2026-01-01']) 2026-01-01
Booleans false list_min([true, false]) false
Lists the first element by element; an empty list is the smallest list_min([[2], [1, 9]]) [1, 9]

The result keeps the element type: INTEGER for [1, 2], DOUBLE for a DOUBLE list.

NULLs and edge cases

Input Result
list_min(NULL) NULL
list_min(NULL::BIGINT[]) NULL
list_min([]::BIGINT[]) NULL
list_min([NULL, 2, 1]) 1
list_min(['NaN'::DOUBLE, 1.0, -'inf'::DOUBLE]) -inf
A number, string, date or other non-list Error: Binder Error: No function matches the given name and argument types, for example 'list_aggr(INTEGER_LITERAL, STRING_LITERAL)'

The same cases, and those of the table above, as the cluster returns them. They use the table and helpers from Set up the examples:

run("SELECT list_min(NULL), list_min(NULL::BIGINT[]), list_min([]::BIGINT[]), list_min([NULL, 2, 1]), "
    "list_min(['NaN'::DOUBLE, 1.0, -'inf'::DOUBLE])")
run("SELECT list_min(['b', 'A', 'a']), list_min(['\u00e9', 'e', 'f']), list_min([DATE '2026-01-02', DATE '2026-01-01']), "
    "list_min([true, false]), list_min([[2], [1, 9]])")
run(f"SELECT list_min(123) FROM {TABLE} LIMIT 1")
[(None, None, None, 1, -inf)]
[('A', 'e', datetime.date(2026, 1, 1), False, [1, 9])]
InternalError: Binder Error: No function matches the given name and argument types 'list_aggr(INTEGER_LITERAL, STRING_LITERAL)'. You might need to add explicit type casts.

Examples

The smallest number, measurement and word of each row. In row 5, the empty string '' is the smallest word:

run(f"SELECT id, list_min(nums), list_min(vals), list_min(words) FROM {TABLE} ORDER BY id LIMIT 10")
[(1, 1, -1.0, 'a'), (2, 3, 2.0, 'B'), (3, None, None, None), (4, None, None, None), (5, -5, -1e-308, '')]

The smallest flag and the smallest inner list. In rows 2 and 5, the empty inner list [] is the smallest:

run(f"SELECT id, list_min(flags), list_min(nested) FROM {TABLE} ORDER BY id LIMIT 10")
[(1, False, [1, 2]), (2, True, []), (3, None, None), (4, None, None), (5, False, [])]

The rows whose smallest number is below 2:

run(f"SELECT id FROM {TABLE} WHERE list_min(nums) < 2 ORDER BY id LIMIT 10")
[(1,), (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). The scan reads a list column whole, and list_min() always runs in the Query Engine. It works within each row's list, so it's a scalar function: it returns one value per row and needs no GROUP BY.

  • In the SELECT list, a projection step finds the smallest element of each row's list after the scan. The plan has no FILTER step.
  • In WHERE, the scan sends the list for every row, and a FILTER step computes list_min() 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 list_min(nums) < 2")
┌───────────────────────────┐
│         PROJECTION        │
│    ────────────────────   │
│             #1            │
│                           │
└─────────────┬─────────────┘
┌─────────────┴─────────────┐
│           FILTER          │
│    ────────────────────   │
│ (list_aggr(nums, 'min') < │
│             2)            │
│                           │
└─────────────┬─────────────┘
┌─────────────┴─────────────┐
│         VAST_SCAN         │
│    ────────────────────   │
│    Function: VAST_SCAN    │
│                           │
│        Projections:       │
│            nums           │
│             id            │
│                           │
└───────────────────────────┘

Make it faster

  • Add a condition on a plain column. A comparison of a column with a constant, such as id > 1, is evaluated in VAST DataBase, so list_min() runs only on the rows that pass it. The plan for id > 1 alone has no FILTER step:
plan(f"SELECT id FROM {TABLE} WHERE id > 1")
┌───────────────────────────┐
│         VAST_SCAN         │
│    ────────────────────   │
│    Function: VAST_SCAN    │
│      Projections: id      │
│                           │
└───────────────────────────┘
  • Store the smallest value if you filter on it often. Compute it when you write the rows and keep it in its own column: min_num < 2 is pushed down, list_min(nums) < 2 isn't.

Limitations and errors

  • Lists only. A value that isn't a list fails with an error that names list_aggr, the function list_min is built on.
  • Text order is by character code, not by language. 'A' comes before 'a', and 'e' before 'é'.
  • ORDER BY needs a LIMIT. Without one, the query fails with The operator 'ORDER_BY' type=1 is currently not supported for this usage.

Similar functions

Function What it does Result for [3, 1, NULL, 3, 10]
list_min(l) smallest element 1
list_aggregate(l, 'min') the same, by name 1
list_max(l) largest element 10
list_first(l) first element 3
list_sort(l) all elements, smallest first; NULLs last [1, 3, 3, 10, NULL]
min smallest value over the rows of a table
run("SELECT list_min(l), list_aggregate(l, 'min'), list_max(l), list_first(l), list_sort(l) "
    "FROM (SELECT [3, 1, NULL, 3, 10] AS l)")
[(1, 1, 10, 3, [1, 3, 3, 10, None])]

Clean up:

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

See also