Friday, 20 March 2026

product function in SQL server

The PRODUCT function in SQL Server is a new aggregate function introduced in SQL Server 2025. It calculates the product of all the numeric values in a specified column or expression within a set of data. PRODUCT operates on a set of rows and returns a single value, much like SUM(), AVG(), COUNT(), MIN(), and MAX() and it works with exact numeric or approximate numeric data types. It will ignore the null value when it performs the calculation.

Syntex

PRODUCT ( [ ALL | DISTINCT ] expression )

Ø  ALL (default): Multiplies all values (including duplicates)

Ø  DISTINCT: Multiplies only unique values

Ø  expression: Numeric expression/column (integer, decimal, float, etc.)

let’s see the demo

-- Sample data

CREATE TABLE Sales (

    Product_ID varchar(50),

    Month_num    int,

    GrowthFactor decimal(6,4)

);

--inserting few rows

INSERT INTO Sales VALUES

('A', 1, 1.12),

('A', 2, 1.08),

('A', 3, 1.15),

('B', 1, 0.95),

('B', 2, 1.03);

 See the product of products ids.

Older versions (2019, 2022, etc.) do not have PRODUCT(). For the same work we are using EXP(SUM(LOG(val))) . This is working for positive numbers only. It failed for zero and null.

See below.

SELECT Product_id,EXP(SUM(LOG(GrowthFactor)))

FROM Sales

WHERE GrowthFactor > 0

group by Product_id;

 

 

No comments:

Post a Comment

If you have any doubt, please let me know.

Popular Posts