--- title: "list_unique" slug: "dev-database-reference-sql-functions-lists-list-unique" updated: 2026-10-30T18:19:11Z published: 2026-10-30T18:19:11Z canonical: "docs.vastdata.com/dev-database-reference-sql-functions-lists-list-unique" --- > ## 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. # list_unique *Applies to VAST Cluster 5.5.* *[Functions](/develop/docs/dev-database-reference-sql-functions-index) › [List, struct and map functions](/develop/docs/dev-database-reference-sql-functions-lists-and-structs) › Search a list.* Returns the number of distinct values in a list, not counting NULL elements. `array_unique` is the same function. ## Syntax ``` list_unique(l) array_unique(l) ``` | Argument | Type | Description | | --- | --- | --- | | `l` | a list of any type | The list whose distinct values are counted. | **Returns:** `UBIGINT` (an unsigned 64-bit integer). **Aliases:** `array_unique`. ## 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_lists_list_unique`. 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 five rows of lists: numbers, words, measurements 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_unique"' 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}.samples" run(f"CREATE SCHEMA IF NOT EXISTS {SCHEMA}") run(f"CREATE TABLE IF NOT EXISTS {TABLE} (id BIGINT, nums BIGINT[], words VARCHAR[], vals DOUBLE[], nested BIGINT[][])") run(f"INSERT INTO {TABLE} VALUES " "(1, [1, 2, 3], ['a', 'b', 'c'], [0.5, 2.5, -1.0], [[1, 2], [3]]), " "(2, [3, NULL, 3], ['b', NULL, 'B'], [2.0, NULL], [[], NULL, [4]]), " "(3, [], [], [], []), " "(4, NULL, NULL, NULL, NULL), " "(5, [-5, 0, -5, 10], ['\u00e9', 'Zo\u00eb', '\U0001F1EB\U0001F1F7', ''], [1e308, 1e308, -1e-308], [[5, NULL], [], [6, 7, 8]])") ``` ``` [] [] [(5,)] ``` ## What it does `list_unique(l)` counts how many different values `l` holds. Each value counts once however often it occurs, and NULL elements aren't counted: - `[1, 2, 3]` has 3 distinct values, `[1, 1, 2]` has 2, and `[1, NULL, 1]` has 1. - Text is compared exactly, so `['a', 'A']` has 2. - A list of lists compares each inner list as a whole: `[[1], [1]]` has 1. - `NaN` values aren't treated as equal: `['NaN'::DOUBLE, 'NaN'::DOUBLE]` has 2. The result is the length of [list_distinct](/develop/docs/dev-database-reference-sql-functions-lists-list-distinct)`(l)`. ## NULLs and edge cases | Input | Result | | --- | --- | | `NULL` | `NULL` | | `[]` | `0` | | `[NULL]` | `0` | | `[1, NULL, 1]` | `1` | | `['a', 'A']` | `2` | | `['NaN'::DOUBLE, 'NaN'::DOUBLE]` | `2` | | `[[1], [1]]` | `1` | | `typeof(list_unique([1]))` | `'UBIGINT'` | | A number, string, `BLOB`, date or boolean | Error: `No function matches the given name and argument types`, for example `'list_unique(INTEGER_LITERAL)'` | The same cases, as the cluster returns them. They use the helpers from [Set up the examples](/develop/docs/dev-database-reference-sql-functions-lists-list-unique#set-up-the-examples): ``` run("SELECT list_unique(NULL), list_unique([]), list_unique([NULL]), list_unique([1, NULL, 1])") run("SELECT list_unique(['a', 'A']), list_unique(['NaN'::DOUBLE, 'NaN'::DOUBLE]), list_unique([[1], [1]]), " "typeof(list_unique([1]))") run("SELECT list_unique(123)") ``` ``` [(None, 0, 0, 1)] [(2, 2, 1, 'UBIGINT')] InternalError: Binder Error: No function matches the given name and argument types 'list_unique(INTEGER_LITERAL)'. You might need to add explicit type casts. ``` ## Examples The number of distinct values in each list of the table. Row 5's measurements hold `1e308` twice, so they count 2: ``` run(f"SELECT id, list_unique(nums), array_unique(words), list_unique(vals), list_unique(nested) " f"FROM {TABLE} ORDER BY id LIMIT 10") ``` ``` [(1, 3, 3, 3, 2), (2, 1, 2, 1, 2), (3, 0, 0, 0, 0), (4, None, None, None, None), (5, 3, 4, 2, 3)] ``` The rows that hold more than two distinct numbers: ``` run(f"SELECT id, nums FROM {TABLE} WHERE list_unique(nums) > 2 ORDER BY id LIMIT 10") ``` ``` [(1, [1, 2, 3]), (5, [-5, 0, -5, 10])] ``` ## 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_unique()` always runs in the Query Engine: - **In the `SELECT` list,** a projection step computes `list_unique()` for each row the scan returns. - **In `WHERE`,** the scan sends the list for every row, and a `FILTER` step computes `list_unique()` 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_unique(nums) > 2") ``` ``` ┌───────────────────────────┐ │ PROJECTION │ │ ──────────────────── │ │ #1 │ │ │ └─────────────┬─────────────┘ ┌─────────────┴─────────────┐ │ FILTER │ │ ──────────────────── │ │ (list_unique(nums) > 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_unique()` 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 count if you filter on it often.** Compute it when you write the rows and keep it in its own column: `distinct_count > 2` is pushed down, `list_unique(nums) > 2` isn't. ## Limitations and errors - **Lists only.** Any other type fails with `No function matches the given name and argument types`; the error names the accepted form, `list_unique(ANY[]) -> UBIGINT`. ## Similar functions | Function | What it counts | Result for `[3, 1, NULL, 3, 10]` | | --- | --- | --- | | `list_unique` | distinct non-NULL values | `3` | | [list_approx_count_distinct](/develop/docs/dev-database-reference-sql-functions-lists-list-approx-count-distinct) | an estimate of the distinct values | `3` | | [list_count](/develop/docs/dev-database-reference-sql-functions-lists-list-count) | non-NULL elements | `4` | | `len` ([array_length](/develop/docs/dev-database-reference-sql-functions-lists-array-length)) | all elements, NULLs included | `5` | ``` run("SELECT list_unique(l), list_approx_count_distinct(l), list_count(l), len(l) FROM (SELECT [3, 1, NULL, 3, 10] AS l)") ``` ``` [(3, 3, 4, 5)] ``` Clean up: ``` run(f"DROP TABLE IF EXISTS {TABLE}") run(f"DROP SCHEMA IF EXISTS {SCHEMA}") conn.close() ``` ``` [] [] ``` ## See also - [List, struct and map functions](/develop/docs/dev-database-reference-sql-functions-lists-and-structs): all the list functions. - [list_distinct](/develop/docs/dev-database-reference-sql-functions-lists-list-distinct): the distinct values themselves. - [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.