Division ( / ) not giving my answer in postgresql

zeewagon picture zeewagon · Dec 29, 2015 · Viewed 73.5k times · Source

I have a table software and columns in it as dev_cost, sell_cost. If dev_cost is 16000 and sell_cost is 7500.

How do I find the quantity of software to be sold in order to recover the dev_cost?

I have queried as below:

select dev_cost / sell_cost from software ;

It is returning 2 as the answer. But we need to get 3, right?

What would be the query for that? Thanks in advance.

Answer

Ilmari Karonen picture Ilmari Karonen · Dec 29, 2015

Your columns have integer types, and integer division truncates the result towards zero. To get an accurate result, you'll need to cast at least one of the values to float or decimal:

select cast(dev_cost as decimal) / sell_cost from software ;

or just:

select dev_cost::decimal / sell_cost from software ;

You can then round the result up to the nearest integer using the ceil() function:

select ceil(dev_cost::decimal / sell_cost) from software ;

(See demo on SQLFiddle.)