Saturday, November 30, 2013

Integer Ranges in SQL Server 2012

I was looking at the numeric data types in SQL Server 2012. I wanted to learn the ranges of the integer data types, but didn't want to memorize them. Noticing that each larger data type is twice the size of the smaller one was the key:

 tinyint  1 byte 
 smallint  2 bytes 
 int  4 bytes 
 bigint  8 bytes 

Since a byte is 8 bits, an integer data type can hold 2(8*bytes).

Let's run the numbers:

A tinyint can hold a value as large as 28. 28 is 256, and a tinyint doesn't use negative numbers,so it can hold values from 0 to 255. 

A smallint is 2 bytes, or 16 bits. 216=64K, so a smallint can range from a minimum of -32K to a maximum of 32K-1. The calculation of the exact values is left as an exercise for the reader.

An int is 4 bytes, so we're talking about 232. I know this one by remembering a 32-bit CPU can address 4GB of RAM, which makes the range not 0-4G, but -2G to 2G-1.

Finally, a bigint is 8 bytes. 232 is...a really big range. According to Books Online, the minimum value is -9,223,372,036,854,775,807. The bigint tops out at 9,223,372,036,854,775,808.

As always, refer to Books Online for more detail.

No comments:

Post a Comment