Search code examples
sqlarrayspostgresqloperation

In SQL, how can I multiple a number by an array


Basically, I have an array that I need to multiply a number by each element, for example:

x float[1,2,3,4,5];
x := x * 10; --of course I get the error here

so the output would be: {10,20,30,40,50}


Solution

  • You could use unnest -> do calculation -> array_agg:

    SELECT array_agg(unnest * 10)  FROM UNNEST('{1,2,3,4,5}' :: int[])
    

    DBFiddle Demo


    To be sure about order of elements you could add WITH ORDINALITY:

    SELECT array_agg(unnest * 10 ORDER BY ordinality) 
    FROM UNNEST('{1,2,3,4,5}' :: int[] )WITH ORDINALITY