Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Postgres math expression calculcated for each row in table

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.

like image 789
nwb Avatar asked Nov 22 '09 22:11

nwb


People also ask

Can you do calculations in PostgreSQL?

So, the short answer is that you can't, and that is by design. The notable exception to this is Microsoft Access, where you can indeed use calculations in subsequent columns and WHERE clauses.

How do I use division in PostgreSQL?

In PostgreSQL, the / operator stands for division. If the columns have integer types, PostgreSQL will use integer division. Integer division is division in which the fractional part (remainder) is discarded. For example, in integer division, the result of 5/2 is 2.

What does :: means in PostgreSQL?

Type Casts. A type cast specifies a conversion from one data type to another. PostgreSQL accepts two equivalent syntaxes for type casts: CAST ( expression AS type ) expression :: type. The CAST syntax conforms to SQL; the syntax with :: is historical PostgreSQL usage.

How do I sum in PostgreSQL?

Summary. Use the SUM() function to calculate the sum of values. Use the DISTINCT option to calculate the sum of distinct values. Use the SUM() function with the GROUP BY clause to calculate the sum for each group.


2 Answers

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
like image 194
Vinko Vrsalovic Avatar answered Oct 08 '22 20:10

Vinko Vrsalovic


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

SELECT col1 / col2 AS new_name
FROM t
like image 31
Dmitry Avatar answered Oct 08 '22 20:10

Dmitry