views:

70

answers:

4

Using PostgreSQL, supposing a table like the following:

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

How can I compute a math expression for each row in the table?

For example, to divide column 2 by column 3, such that the output would be:

 12184 |   0.04819277108
 12183 |   0.01754385965
 12176 |   0.06315789474

My instinct was to try:

SELECT col1, col2 / col3 FROM table_name;

But that return the ceiling (ie. rounded-down) integer part, I need the floating point value.

A: 
select col1, col2/col3 from table;

Should work. Aren't col2 and col3 numeric?

Paul Tomblin
Yes, however I require the floating point value, and Postgres is only returning the integer part.
nwb
A: 

You can use arithmetic expressions in SELECT clause, like this:

SELECT col1 / col2 AS new_name
FROM t
Dmitry
A: 

Typical cast trick needed because col2 and col3 are integers (so result is by default an integer)

select col1, col2/col3*1.0 from table

or

select col1, col2/col3::float from table

or (SQL Standard way)

select col1, col2/cast(col3 as float) from table
Vinko Vrsalovic
Thanks very much all. I actually used the following:SELECT col1, cast(col2 as float) / cast(col3 as float) FROM table;Is there any reason to preffer one way opposed to another?
nwb
See http://www.postgresql.org/docs/8.4/interactive/typeconv.html for details. In fact I prefer your way, as it's standard, the ::type form is a PostgreSQL extension.
Vinko Vrsalovic
And, as you can see from my examples, you can get away casting only the denominator.
Vinko Vrsalovic
A: 

Try query like this:

SELECT col1, col2 / col3::float FROM table_name;
Simon