Is there a good reason I see VARCHAR(255) used so often (as opposed to another length)?

后端 未结 10 638
Happy的楠姐
Happy的楠姐 2020-12-12 10:38

In multiple courses, books, and jobs, I have seen text fields defined as VARCHAR(255) as kind of the default for \"shortish\" text. Is there any good reason that a length o

相关标签:
10条回答
  • 2020-12-12 11:21

    Historically, 255 characters has often been the maximum length of a VARCHAR in some DBMSes, and it sometimes still winds up being the effective maximum if you want to use UTF-8 and have the column indexed (because of index length limitations).

    0 讨论(0)
  • 2020-12-12 11:21

    Another reason may be that in very old data access libraries on Windows such as RDO and ADO (COM version not ADO.NET) you had to call a special method, GetChunk, to get data from a column with more than 255 chars. If you limited a varchar column to 255, this extra code wasn't necessary.

    0 讨论(0)
  • 2020-12-12 11:23

    Note: I found this question (varchar(255) v tinyblob v tinytext), which says that VARCHAR(n) requires n+1 bytes of storage for n<=255, n+2 bytes of storage for n>255. Is this the only reason? That seems kind of arbitrary, since you would only be saving two bytes compared to VARCHAR(256), and you could just as easily save another two bytes by declaring it VARCHAR(253).

    No. you don't save two bytes by declaring 253. The implementation of the varchar is most likely a length counter and a variable length, nonterminated array. This means that if you store "hello" in a varchar(255) you will occupy 6 bytes: one byte for the length (the number 5) and 5 bytes for the five letters.

    0 讨论(0)
  • 2020-12-12 11:24

    I'm going to answer the literal question: no, there isn't a good reason you see VARCHAR(255) used so often (there are indeed reasons, as discussed in the other answers, just not good ones). You won't find many examples of projects that have failed catastrophically because the architect chose VARCHAR(300) instead of VARCHAR(255). This would be an issue of near-total insignificance even if you were talking about CHAR instead of VARCHAR.

    0 讨论(0)
提交回复
热议问题