Applies to VAST Cluster 5.5.
Functions › List, struct and map functions › Aggregate a list. Returns the product of the elements of a list, one value per row, as a DOUBLE. NULL elements are skipped. It's the same as list_aggregate(l, 'product').
Syntax
list_product(l)
| Argument | Type | Description |
|---|---|---|
l |
a list of numbers | The list to multiply out. |
Returns: DOUBLE, for lists of integers and decimals too.
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_product. 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 of numbers and measurements. Row 3 has empty lists, row 4 has no values, and row 5 has measurements close to the largest DOUBLE:
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_product"'
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[])")
run(f"INSERT INTO {TABLE} VALUES "
"(1, [1, 2, 3], [0.5, 2.5, -1.0]), "
"(2, [3, NULL, 3], [2.0, NULL]), "
"(3, [], []), "
"(4, NULL, NULL), "
"(5, [-5, 0, -5, 10], [1e308, 1e308, -1e-308])")
[]
[]
[(5,)]
What it does
list_product(l) multiplies together the elements of l that aren't NULL. list_product([2, 3]) returns 6.0, and list_product([NULL, 2]) returns 2.0.
- The result is always
DOUBLE. A list of integers returnsDOUBLEtoo, so a large product loses precision instead of overflowing:list_product([9223372036854775807, 2])returns1.8446744073709552e+19. - Too large returns
inf.list_product([1e200, 1e200])returnsinf, not an error. - A zero makes the product 0, and a
NaNmakes itnan.
NULLs and edge cases
| Input | Result |
|---|---|
list_product(NULL) |
NULL |
list_product(NULL::BIGINT[]) |
NULL |
list_product([]::BIGINT[]) |
NULL, not 1 |
list_product([NULL, 2]) |
2.0 |
list_product([2, 3, 0]) |
0.0 |
list_product([-2, 3]) |
-6.0 |
list_product([1.5, 2.0]) |
3.0 |
list_product([9223372036854775807, 2]) |
1.8446744073709552e+19 |
list_product([1e200, 1e200]) |
inf |
list_product(['NaN'::DOUBLE, 1.0]) |
nan |
list_product(['a']) |
Error: Binder Error: No matching aggregate function |
| 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, as the cluster returns them. They use the table and helpers from Set up the examples:
run("SELECT list_product(NULL), list_product(NULL::BIGINT[]), list_product([]::BIGINT[]), list_product([NULL, 2])")
run("SELECT list_product([2, 3, 0]), list_product([-2, 3]), list_product([1.5, 2.0]), "
"list_product([9223372036854775807, 2]), list_product([1e200, 1e200]), list_product(['NaN'::DOUBLE, 1.0])")
run("SELECT list_product(['a'])")
run(f"SELECT list_product(123) FROM {TABLE} LIMIT 1")
[(None, None, None, 2.0)]
[(0.0, -6.0, 3.0, 1.8446744073709552e+19, inf, nan)]
InternalError: Binder Error: No matching aggregate function
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 product of each row's numbers and measurements. Row 5's numbers include a 0, and its measurements multiply out to more than the largest DOUBLE:
run(f"SELECT id, list_product(nums), list_product(vals) FROM {TABLE} ORDER BY id LIMIT 10")
[(1, 6.0, -1.25), (2, 9.0, 2.0), (3, None, None), (4, None, None), (5, 0.0, -inf)]
The result type, for an integer and a DOUBLE list:
run("SELECT typeof(list_product([1, 2])), typeof(list_product([1.5::DOUBLE]))")
[('DOUBLE', 'DOUBLE')]
The rows whose product isn't NULL:
run(f"SELECT id FROM {TABLE} WHERE list_product(nums) IS NOT NULL ORDER BY id LIMIT 10")
[(1,), (2,), (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_product() always runs in the Query Engine. It multiplies within each row's list, so it's a scalar function: it returns one value per row and needs no GROUP BY.
- In the
SELECTlist, a projection step computes the product of each row's list after the scan. The plan has noFILTERstep. - In
WHERE, the scan sends the list for every row, and aFILTERstep computes the product 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_product(nums) IS NOT NULL")
┌───────────────────────────┐
│ PROJECTION │
│ ──────────────────── │
│ #1 │
│ │
└─────────────┬─────────────┘
┌─────────────┴─────────────┐
│ FILTER │
│ ──────────────────── │
│ (list_aggr(CAST(nums AS │
│ DOUBLE[]), 'product') IS │
│ NOT NULL) │
│ │
└─────────────┬─────────────┘
┌─────────────┴─────────────┐
│ 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, solist_product()runs only on the rows that pass it. The plan forid > 1alone has noFILTERstep:
plan(f"SELECT id FROM {TABLE} WHERE id > 1")
┌───────────────────────────┐
│ VAST_SCAN │
│ ──────────────────── │
│ Function: VAST_SCAN │
│ Projections: id │
│ │
└───────────────────────────┘
- Store the product if you filter on it often. Compute it when you write the rows and keep it in its own column, where a comparison with a constant is pushed down.
Limitations and errors
- Numbers only. A list of text fails with
No matching aggregate function. A value that isn't a list fails with an error that nameslist_aggr, the functionlist_productis built on. - Not exact for large integers. The result is a
DOUBLE, which holds about 15 to 17 significant digits. - An empty list returns NULL. Use
coalesce(list_product(l), 1)where you need1. ORDER BYneeds aLIMIT. Without one, the query fails withThe 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_product(l) |
product of the elements, as DOUBLE |
90.0 |
list_aggregate(l, 'product') |
the same, by name | 90.0 |
list_sum(l) |
sum of the elements | 17 |
list_avg(l) |
mean of the elements | 4.25 |
| product | product over the rows of a table |
run("SELECT list_product(l), list_aggregate(l, 'product'), list_sum(l), list_avg(l) FROM (SELECT [3, 1, NULL, 3, 10] AS l)")
[(90.0, 90.0, Decimal('17'), 4.25)]
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: all the list aggregates.
- product: the aggregate over rows.
- Where filters run and pushdowns.
- EXPLAIN: how to read a plan.