Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best datatype to store a single digit?

Tags:

types

mysql

I need a datatype to store this range: [0 - 9]. Something like this:

+-----+
| col |
+-----+
| 3   |
| 2   |
| 8   |
| 0   |
| 2   |
| 1   |
+-----+

What datatype is the best in this case?

like image 586
Shafizadeh Avatar asked Jan 04 '16 23:01

Shafizadeh


People also ask

Which is the best data type to store the number?

Use DECIMAL for decimal numbers.

What data type should you choose for a variable that needs to hold letters and numbers?

One of the most widely used data types is a string. A string consists of one or more characters, which can include letters, numbers, and other types of characters. You can think of a string as plain text.

What are numeric data types?

Numeric types consist of two-, four-, and eight-byte integers, four- and eight-byte floating-point numbers, and selectable-precision decimals.

What is a float data type in SQL?

Float Data Type Float is an approximate number data type used to store a floating-point number. float (n) - n is the number of bits that are used to store the mantissa in scientific notation. Range of values: - 1.79E+308 to -2.23E-308, 0 and 2.23E-308 to 1.79E+308.


1 Answers

Despite the documentation, I'm not clear on whether the size of a DECIMAL(1,0) is "rounded up" to four bytesm or whether the single digit counts as a "left-over digit", resulting in a width of a single byte for the whole data type.

Regardless, you can't use less space than a TINYINT, because a TINYINT is a single byte wide, and a byte is the smallest unit of data on a computer (without getting into bitpacking, which doesn't seem plausible on tabular data!).

So, of the numeric types, use a TINYINT. Anything else is needless obfuscation.

That being said, I'm a big fan of ENUMs, and this would seem to be a perfect case for them. Since your enumeration would have fewer than 255 possible values, like a TINYINT it would only take a single byte.

ENUM('0', '1', '2', '3', '4', '5', '6', '7', '8', '9')

Sadly, it's a little verbose to write out. But at least now your values are inherently range-constrained.

like image 113
Lightness Races in Orbit Avatar answered Oct 17 '22 00:10

Lightness Races in Orbit