Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Integer division in sql server

In Microsoft SQL Server 2005, why do the following commands produce integer results?

SELECT cast(151/6 AS DECIMAL(9,2)) SELECT 151/6 
like image 518
Phillip Senn Avatar asked Aug 09 '10 19:08

Phillip Senn


People also ask

What is integer division 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 ).

How do you divide in SQL Server?

The SQL divide ( / ) operator is used to divide one expressions or numbers by another.

What is integer division example?

Division of integers means equal grouping or dividing an integer into a specific number of groups. For example, -6 ÷ 2 means dividing -6 into 2 equal parts, which results in -3.

How do you represent integer division?

Names and symbols used for integer division include div, /, \, and %.


2 Answers

In the first you are getting the result of two integers and then casting the result as DECIMAL(9,2). In the second you're just dividing two integers and that's expected.

If you cast one of the integers as a decimal BEFORE you do the division, you'll get a decimal result.

SELECT 151/CAST(6 AS DECIMAL (9,2)) 
like image 101
Mike M. Avatar answered Sep 19 '22 23:09

Mike M.


Yes that is standard behavior

do

SELECT 151/6.0 

or

SELECT 151/(CONVERT(DECIMAL(9,2),6)) 

or

SELECT 151/(6 * 1.0) 
like image 25
SQLMenace Avatar answered Sep 20 '22 23:09

SQLMenace