Why do we need a .0 for: SELECT (517 + 309 + 304 + 282) / 6366.0

https://www.codecademy.com/paths/data-science/tracks/sql-intermediate/modules/dspath-sql-aggregates-projects-and-applications/projects/sql-hackernews

I just had a quick question regarding:

SELECT (517 + 309 + 304 + 282) / 6366.0

At first I tried

SELECT (517 + 309 + 304 + 282) / 6366

And it returned 0

Why do we need to add a .0 at the end of 6366 to get it to calculate?

It makes the result a FLOAT… if you don’t have this not all the values in the data type range can be represented exactly. This will allow it to show to the exact decimal.

Hope this helps.

2 Likes

What about the values in the numerator? Those all dont have decimal places.

You could float all the numbers, but it will yield the same result as just doing either the numerator or denominator. The tool ideally will want to use the minimum amount of memory to achieve the answer.

3 Likes

I still don’t understand it.
I checked this request in bash and DBeaver with INTEGERs and I’ve got 0.2218 two times.
Is this a particularity of codecademy’s editor?

When it comes to programming languages, there are two kinds of division: integer division and floating point division.

In integer division, the quotient (i.e. the result of dividing one number by another number) is always an integer, meaning that there is nothing following the decimal point, and it is obtained by simply ignoring everything that follows the decimal point.

In floating point division, the quotient is a decimal number.

To understand the difference, consider the following example:

Integer Division:
7 / 4 = 1

Floating Point Division:
7.0 / 4.0 = 1.75 (Note, this could also be written as 7.0 / 4 = 1.75 or 7 / 4.0 = 1.75)

Some programming languages will default to floating point division, so that 7 / 4 would result in 1.75, but a lot of languages default to integer division unless at least one of the numbers in the calculation is a decimal number. It is important to know the default in whichever programming language you’re using, especially in complex calculations, and to pay attention to each step of your calculation.

For example, in languages where integer division is the default:
(46 / 4) / 2.0 = 5.5
This is because even though 2.0 specifies floating point division by having .0 at the end, 46 / 4 is still performed as integer division. Consider instead:
(46 / 4.0) / 2.0 = 5.75
In this case, only floating point division is performed in each step of the calculation.