23

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.

5 Answers 5

35

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
Sign up to request clarification or add additional context in comments.

3 Comments

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?
See 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.
And, as you can see from my examples, you can get away casting only the denominator.
2

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

SELECT col1 / col2 AS new_name
FROM t

Comments

0
select col1, col2/col3 from table;

Should work. Aren't col2 and col3 numeric?

1 Comment

Yes, however I require the floating point value, and Postgres is only returning the integer part.
0

Try query like this:

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

Comments

0

In PgSql the columns are typed. So if you want to operator on them; you need to cast the column.

suppose you have a column 'minutes' and you wanna add '+5' in every values of column 'mintues'

Because you are adding and integer value the minutes column must be a integer only then the addition can be performed.

hence incorrect way:

select *, minutes+5 from my table >> syntax error

select *, minutes::int + 5 from mytable >> give the output

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.