Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does the number in parenthesis really mean?

Tags:

sql

mysql

ddl

I always thought that the number in the parenthesis represented the field length?

However, I understand that is not always the case. Maybe it's a MySQL issue? Someone told me if I set a field to 9 characters long, I can add a value that's more than 9 characters but only the first 9 will be saved.

Example:

CREATE TABLE `person` (     id INT,     age INT(2) ); 

If that's the case, shouldn't I select something like TINYINT instead of INT for age?

like image 280
sdot257 Avatar asked Oct 29 '10 20:10

sdot257


People also ask

Does the number or word go in parentheses?

Don't put numbers in parentheses after words. Two readers recently asked whether they need to repeat a number in parentheses after they write out the word. Note that I did not write two (2) readers.

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.


1 Answers

INT(2) will generate an INT with the minimum display width of 2:

MySQL supports an extension for optionally specifying the display width of integer data types in parentheses following the base keyword for the type. For example, INT(4) specifies an INT with a display width of four digits. This optional display width may be used by applications to display integer values having a width less than the width specified for the column by left-padding them with spaces. (That is, this width is present in the metadata returned with result sets. Whether it is used or not is up to the application.)

The display width does not constrain the range of values that can be stored in the column. Nor does it prevent values wider than the column display width from being displayed correctly. For example, a column specified as SMALLINT(3) has the usual SMALLINT range of -32768 to 32767, and values outside the range permitted by three digits are displayed in full using more than three digits.

this does not affect the range of possible values that can be stored in the field; neither is it the number of bytes used to store it. It seems to be only a recommendation for applications how to show the value, unless ZEROFILL is used (see the linked page).

A unsigned TINYINT (0...255) would probably do as well, unless cryopreservation takes a big step forward during the lifetime of your application.

like image 87
Pekka Avatar answered Sep 21 '22 08:09

Pekka