// aggregates reference

SQL PRODUCT aggregate

PRODUCT(x) is to multiplication what SUM is to addition. Compound growth from a column of rates is the usual reason to want it.

Categoria
Aggregates
Returns
numeric, matching the input type
In this category
52 of 52

Sintaxe

PRODUCT([ALL | DISTINCT] expression)

Suporte a mecanismos

MotorSupportNotas
SQL Server Sim PRODUCT() from SQL Server 2025
PostgreSQL Not built in no; EXP(SUM(LN(x))) for positive values
MySQL Not built in no; EXP(SUM(LN(x))) for positive values
SQLite Not built in no; exp(sum(ln(x))) where the math functions are compiled in
Oracle Not built in no; EXP(SUM(LN(x))) for positive values

Exemplos

SQL Server

SELECT PRODUCT(x) AS all_values, PRODUCT(DISTINCT x) AS distinct_values
FROM (VALUES (2), (2), (3), (CAST(NULL AS INT))) AS t(x);  -- 12, 6

SQL Server

SELECT PRODUCT(1 + r) - 1 AS growth
FROM (VALUES (0.10), (0.05), (-0.02)) AS t(r);  -- 0.131900

PostgreSQL

SELECT exp(sum(ln(x))) AS product
FROM (VALUES (2), (3), (4)) AS t(x);  -- 23.999999999999993

Bom saber

  • PRODUCT ignores NULLs and returns NULL for an empty or all-NULL group.
  • Integer input gives an int result that overflows fast: two rows of 100000 fail with an arithmetic overflow. Cast to bigint, decimal or float first.
  • The EXP(SUM(LN(x))) workaround fails on zero and negative values (LN is undefined there) and returns floating-point noise: 2 * 3 * 4 comes back as 23.999999999999993.
  • For compound growth, PRODUCT(1 + rate) - 1 is the cumulative return: rates of 10%, 5% and -2% give 0.1319.

Questions about PRODUCT

Which engines have PRODUCT?

SQL Server 2025 and Azure SQL Database. None of the other four engines here has a built-in product aggregate.

How do I handle zeros and negatives in the LN workaround?

Multiply the magnitudes and fix the sign separately: CASE WHEN SUM(CASE WHEN x = 0 THEN 1 ELSE 0 END) > 0 THEN 0 ELSE EXP(SUM(LN(ABS(NULLIF(x, 0))))) * (1 - 2 * (SUM(CASE WHEN x < 0 THEN 1 ELSE 0 END) % 2)) END. The NULLIF keeps zeros away from LN, which errors on 0 in PostgreSQL. For -2, 3 and 4 it returns -23.999999999999993.

Browse every function in the SQL function reference, or see what the SQLly desktop app does for your database.

Cheat sheets for the engines that have it: SQL Server.

// fewer lookups

Functions your engine actually has

SQLly's completion lists the built-in functions of the engine you're connected to, whether that's SQL Server, PostgreSQL, MySQL, SQLite or Oracle. Hover a function for help, and signature hints show each argument as you type.