Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Division ( / ) not giving my answer in postgresql

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?

like image 764
zeewagon Avatar asked Dec 29 '15 04:12

zeewagon


People also ask

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.

How do I find the quotient in PostgreSQL?

The PostgreSQL div() function is used to return the integer quotient of a division as specified in the argument.

What is decimal in PostgreSQL?

The DECIMAL and NUMERIC data types are equivalent in PostgreSQL. Both of them have a variable storage size, i.e. the storage size depends on the number of digits contained. As opposed to INTEGER and BIGINT data types that can store only whole numbers, the DECIMAL and NUMERIC data types can store rational numbers.

How do I cast an expression in PostgreSQL?

PostgreSQL supports a CAST operator that is used to convert a value of one type to another. Syntax: CAST ( expression AS target_type ); Let's analyze the above syntax: First, specify an expression that can be a constant, a table column, an expression that evaluates to a value.


Video Answer


2 Answers

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.)

like image 167
Ilmari Karonen Avatar answered Oct 11 '22 21:10

Ilmari Karonen


You can cast integer type to numeric and use ceil() function to get the desired output

The PostgreSQL ceil function returns the smallest integer value that is greater than or equal to a number.

SELECT 16000::NUMERIC / 7500 col 
      ,ceil(16000::NUMERIC / 7500) 

Result:

col                  ceil 
------------------   ---- 
2.1333333333333333     3    

So your query should be

select ceil(dev_cost::numeric/sell_cost) 
from software
like image 12
Vivek S. Avatar answered Oct 11 '22 20:10

Vivek S.