Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PostgreSQL multiplication of columns

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?

like image 881
bbbb Avatar asked Sep 23 '13 18:09

bbbb


People also ask

How do I multiply two 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.

Can you do calculations in PostgreSQL?

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.

How do I sum multiple columns in SQL?

The SQL AGGREGATE SUM() function returns the SUM of all selected column. Applies to all values. Return the SUM of unique values.


2 Answers

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?

like image 135
Erwin Brandstetter Avatar answered Sep 19 '22 14:09

Erwin Brandstetter


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.

like image 44
jperelli Avatar answered Sep 18 '22 14:09

jperelli