Why is Postgres exp / log result different from SQL Server?

I don't have SQL Server on my box, but why doesn't the following answer return 360 on Postgres?

select exp(sum(log(val)))
from (values(4),(5),(3),(6)) as tbl(val)

      

returns 12.888075

0


source to share


1 answer


You should use the natural logarithm (ln function), not the base-10 logarithm (log function):

select exp(sum(ln(val)))
from (values(4),(5),(3),(6)) as tbl(val)

 exp 
-----
 360
(1 row)

      



But this is not the best way to multiply strings - it's slow and prone to rounding errors. You must declare an aggregate:

create function multiply(int,int) returns int as $$
  select $1*$2;
$$ language sql immutable strict;

create aggregate multiply(int) (
  sfunc=multiply,
  stype=int,
  initcond=1
);

select multiply(val)
from (values(4),(5),(3),(6)) as tbl(val)
 multiply 
----------
      360
(1 row)

      

+2


source







All Articles