Postgres mathematical expression calculated for each table row

Using PostgreSQL, suppose the table looks like this:

12184 | 4 | 83 12183 | 3 | 171 12176 | 6 | 95 

How can I calculate a mathematical expression for each row of a table?

For example, to divide column 2 into column 3 so that the output is:

  12184 | 0.04819277108 12183 | 0.01754385965 12176 | 0.06315789474 

My instinct was to try:

 SELECT col1, col2 / col3 FROM table_name; 

But this returns the integer part of the ceiling (i.e. rounded), I need a floating point value.

+6
math sql postgresql
source share
5 answers

A typical trick is required because col2 and col3 are integers (so the default result is an integer)

 select col1, col2/col3*1.0 from table 

or

 select col1, col2/col3::float from table 

or (standard SQL)

 select col1, col2/cast(col3 as float) from table 
+9
source share

You can use arithmetic expressions in a SELECT clause, for example:

 SELECT col1 / col2 AS new_name FROM t 
+1
source share
 select col1, col2/col3 from table; 

Must work. Are col2 and col3 numeric?

0
source share

Try the query as follows:

 SELECT col1, col2 / col3::float FROM table_name; 
0
source share

In PgSql, columns are printed. Therefore, if you want an operator on them; you need to specify a column.

suppose you have a column of β€œminutes” and you want to add β€œ+5” to each value of the column β€œmintues”

Since you are adding an integer value as well, the column of minutes must be an integer, then adding can be done.

therefore, it is not true:

select *, minutes+5 from my table β†’ Syntax error

select *, minutes::int + 5 from mytable enter output

0
source share

All Articles