MySQL integer columns and display widthOne confusing aspect of MySQL is declaring integer columns. It took me a while to understand what the number in parenthesis meant, for example:
Initially, I thought it meant that column could only hold unsigned (no negatives) integer values up to a maximum 999999, which is 6 characters wide. This is wrong thinking. The 6 means something else entirely... However, the reason I thought this is because string columns are declared in a similar fashion:
This means a character column, with a maximum length of 6 characters, such as these words:
Notice those are all 6 characters in length. If I tried storing the word "special" in that column, MySQL would chop the value to be "specia", since the original word has 7 characters. Anyway, integer columns all have a preset range of values allowed. The number in parenthesis only indicates the display width. This is probably still confusing, so let me explain further... The display width is a number from 1 to 255. You can set the display width if you want all of your integer values to "appear" similarly:
Actually, you can't see it, because the left side is padded with spaces. To help visualize it easier, try this:
Does that help? Notice how they all have a display width of 6.
Enter ZEROFILL. If you declare your integer column like this:
... your numbers will "appear" like this:
Notice how the left side is padded with zero's, which makes the numbers look consistent, no matter what the "real" length is.
No, for both. You can still store up to the maximum value allowed for that column type, no matter what you set as the "display width." Also, the "display width" does not affect the number of bytes of storage required. For example, if your column is declared like this:
... and you want to store the number 6543210, which is 7 characters, it will still be accepted. Here is a partial list of numeric column type ranges:
More information can be found at the Numeric Data Types section of the MySQL Reference Manual.
Comments/Mentions
|
Editor Picks
Email NewsletterSubscribe to the digest newsletter to receive posts by email: Recent Comments
Advertisements
|
If the unsigned range of TINYINT is -128 to 127, should the display width be TINYINT(3) or TINYINT(4)?
I understand that the unsigned range would be 0 - 255 so three digits is the max. I'm trying to find out if the minus sign needs to be accounted for.