I have Postgres database and I have to multiply column by column like this:
SELECT SUM(column1*column2) AS res (...)
And the result is 0
. Both columns are real
type.
But the multiplication operator works great when I do:
SELECT SUM(column * 100) AS res (...)
Is it possible to do arithmetics using columns in PostgreSQL?
All you need to do is use the multiplication operator (*) between the two multiplicand columns ( price * quantity ) in a simple SELECT query.
Mathematical operators are provided for many PostgreSQL types. For types without common mathematical conventions for all possible permutations (e.g., date/time types) we describe the actual behavior in subsequent sections. Table 9-2 shows the available mathematical operators.
The SQL AGGREGATE SUM() function returns the SUM of all selected column. Applies to all values. Return the SUM of unique values.
This query works just fine:
SELECT SUM(column1 * column2) AS res
FROM tbl;
If your result res
is 0
, then you must have:
0
in one or both of the columns and none of them NULL
in at least one row.0
or NULL
in one or both of the columns for every other selected row.Or there is some other trivial misunderstanding involved. Maybe you are confusing your column alias res
with result
?
Try using a subquery
SELECT
SUM(subq.multiplied_column)
FROM (
SELECT
column1 * column2 AS multiplied_column
FROM
table
) as subq
Also Take care of NULL values. If some value from column1 or column2 is NULL then all the result of SUM() can be NULL, and depending on the language you are using and the connection library, you can see 0 as a result instead of NULL.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With