Home > Enterprise >  why should we set field length while creating sql table?
why should we set field length while creating sql table?

Time:12-21

I can't understand why should we set field length while creating SQL table fields.

INT(11),
VARCHAR(255),

CodePudding user response:

Data lengths are another form of data validation - they allow you to easily constrain the data in the table and not allow values that are larger than your program's logic would allow.

CodePudding user response:

These are two different cases.

INT(11)

The "length" of an integer is almost meaningless, and MySQL 8.0 deprecates this syntax. An INT is always a 32-bit integer, regardless of the length argument. The only practical use of the length argument is if you use:

INT(11) ZEROFILL

This pads the number with zeroes when you fetch it, not as it is stored. The number is still stored exactly the same as INT(2) or INT(50), as a 32-bit integer. See my answer to Types in MySQL: BigInt(20) vs Int(20)

VARCHAR(255)

It's necessary to define a length because that's how data types must work in relational theory. The definition of a data type is "a named, finite set of values." It can't be a finite set if the strings have infinite length.

There is also the practical reason: to store a string, MySQL precedes it with one or two bytes encoding the length, so it knows how many characters to read. One byte of length information is used if the length is up to 255. Two bytes of length information is used if the length is up to 65535. That's the maximum length supported for VARCHAR in MySQL.

  • Related