String field length in Postgres SQL

后端 未结 3 2003
半阙折子戏
半阙折子戏 2021-01-15 04:55

I have a string filed in an SQL database, representing a url. Some url\'s are short, and some very long. I don\'t really know waht\'s the longest URL I might encounter, so t

3条回答
  •  终归单人心
    2021-01-15 05:26

    Both postgreSQL, sqllite and mysql applies the sql standard for storing varchar and chars. Which is basiclly this:

    SQL defines two primary character types: character varying(n) and character(n), where n is a positive integer. Both of these types can store strings up to n characters in length. An attempt to store a longer string into a column of these types will result in an error, unless the excess characters are all spaces, in which case the string will be truncated to the maximum length. (This somewhat bizarre exception is required by the SQL standard.) If the string to be stored is shorter than the declared length, values of type character will be space-padded; values of type character varying will simply store the shorter string.

    If one explicitly casts a value to character varying(n) or character(n), then an over-length value will be truncated to n characters without raising an error. (This too is required by the SQL standard.)

    The notations varchar(n) and char(n) are aliases for character varying(n) and character(n), respectively. character without length specifier is equivalent to character(1). If character varying is used without length specifier, the type accepts strings of any size. The latter is a PostgreSQL extension.

    Reference:

    • Pg docs: Character Types

提交回复
热议问题