Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does VARCHAR need length specification?

Why do we always need to specify VARCHAR(length) instead of just VARCHAR? It is dynamic anyway.

UPD: I'm puzzled specifically by the fact that it is mandatory (e.g. in MySQL).

like image 807
Fixpoint Avatar asked Jul 01 '10 10:07

Fixpoint


People also ask

Does varchar require length?

A VARCHAR column uses one length byte if values require no more than 255 bytes, two length bytes if values may require more than 255 bytes.

What length should I set varchar?

The length can be specified as a value from 0 to 65,535. The effective maximum length of a VARCHAR is subject to the maximum row size (65,535 bytes, which is shared among all columns) and the character set used.

Does varchar length affect performance?

Declared varchar column length will not affect the physical (on-disk) or data cache storage. It will affect the performance of actually using that index.

What does varchar length mean in SQL?

2. VARCHAR Datatype: It is a datatype in SQL which is used to store character string of variable length but a maximum of the set length specified. If the length of the string is less than set or fixed-length then it will store as it is without padded with extra blank spaces.


2 Answers

The "length" of the VARCHAR is not the length of the contents, it is the maximum length of the contents.

The max length of a VARCHAR is not dynamic, it is fixed and therefore has to be specified.

If you don't want to define a maximum size for it then use VARCHAR(MAX).

like image 75
Robin Day Avatar answered Sep 21 '22 16:09

Robin Day


First off, it does not needed it in all databases. Look at SQL Server, where it is optional.

Regardless, it defines a maximum size for the content of the field. Not a bad thing in itself, and it conveys meaning (for example - phone numbers, where you do not want international numbers in the field).

like image 32
Oded Avatar answered Sep 18 '22 16:09

Oded