Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Server division query

When I run the query:

select (100/50)

It give me 2 - good.

But when I run the query:

select (50/100)

I was expected it will give me 0.5... but it gives me 0 instead? Why? and How can I get the 0.5?

select (25/(30))*100

I was expected it will give me 83.33 but it also gives 0 instead?

like image 869
muhammadanish Avatar asked Oct 27 '25 04:10

muhammadanish


2 Answers

When you divide two integers, the result is an integer as well, so 50 / 100 is 0.5, which is an integer of 0.

To get a decimal point, either write:

Select 50.0 / 100

or Cast the integer o a decimal - i.e.

SELECT (CAST(20 AS DECIMAL(5,1))/30)
like image 87
Dibstar Avatar answered Oct 29 '25 20:10

Dibstar


Try this:

select (50/100.0)

Using an integer for division will lead to zero if the result is less than 1 because integer values can only be round numbers.

0.99 will result in the lower value = 0
3.876 will result in 3 and so on.

Use decimal variables to get the result you want. You can easily do that by using a . in your numbers: 100.0

like image 31
juergen d Avatar answered Oct 29 '25 21:10

juergen d