Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Divide in SQL Server

In SQL Server 2005 Express, the result is below

SELECT 100 / 15 --Result 6

But I wanna get approximate value 7 (like using calculator)

100 / 15 = 6.6666..

How to make it in SQL Server?

like image 296
soclose Avatar asked Mar 01 '11 05:03

soclose


People also ask

What is divide in database?

Division is typically required when you want to find out entities that are interacting with all entities of a set of different type entities. The division operator is used when we have to evaluate queries which contain the keyword 'all'.

Can you divide integers in SQL?

Integer division in SQL takes place when both the dividend and the divisor are integers. Since they are integers, SQL wants to return an integer result to match the number type. In PostgreSQL and SQL Server, it is integer division. In MySQL and Oracle it is regular division (and the result of 1/4 is 0.25 ).

What is divide operator?

Division (/) The division operator ( / ) produces the quotient of its operands where the left operand is the dividend and the right operand is the divisor.

How do you find the quotient in SQL?

DIV() function : This function in MySQL is used to return a quotient (integer) value when integer division is done. For example, when 7 is divided by 3, then 2 will be returned.


4 Answers

You have to use decimal numbers e.g. 100 / 15.0. If you use integers the result is interpreted as an integer and truncated to the largest integer that is smaller than or equal to the result.

like image 155
Aleksi Yrttiaho Avatar answered Sep 30 '22 17:09

Aleksi Yrttiaho


SELECT cast(100 as float) / (15 as float)

like image 37
user2373127 Avatar answered Sep 30 '22 17:09

user2373127


You want SQL Server to perform floating-point divison, as opposed to integer division. If you're using literal values, as in your example, suffix the denominator with .0 to force SQL Server to treat it as a floating-point value.

SELECT 100 / 15.0

Otherwise, make sure you declare your variables as FLOAT.

like image 44
Michael Petrotta Avatar answered Sep 30 '22 18:09

Michael Petrotta


Try declaring variables as floats:

DECLARE @var1 FLOAT
DECLARE @var2 FLOAT
SET @var1 = 100
SET @var2 = 15
SELECT @var1 / @var2
like image 42
Dubmun Avatar answered Sep 30 '22 17:09

Dubmun