问题描述
我在SQL数据库中有一个字符串,表示一个URL。有些网址很短,有些很长。我真的不知道waht是我可能遇到的最长的URL,因此,为了安全起见,我会采用较大的值,例如256或512。
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 to be on the safe side, I'll take a large value, such as 256 or 512.
当我定义最大字符串长度时(例如,使用SQLAlchemy):
When I define the maximal string length (using SQLAlchemy for example):
url_field = Column(String(256))
即使实际字符串较短,这是否占用每一行的空间(存储空间)?
Does this take up space (storage) for each row, even if the actual string is shorter?
我假设这与实现细节有关。我正在使用postgreSQL,但对sqlite和mysql也很感兴趣。
I'm assuming this has to do with the implementation details. I'm using postgreSQL, but am interested in sqlite, mysql also.
推荐答案
通常,数据库存储引擎可以做很多您不愿意做的事情没想到。但基本上,有两种文本字段可以提示内部将发生什么。
Usually database storage engines can do many thing you don't expect. But basically, there are two kinds of text fields, that give a hint what will go on internally.
char和varchar。 Char将为您提供一个固定的字段列,并且根据sql会话中的选项,您是否会收到空格填充的字符串。 Varchar用于不超过一定最大长度的文本字段。
char and varchar. Char will give you a fixed field column and depending on the options in the sql session, you may receive space filled strings or not. Varchar is for text fields up to a certain maximum length.
Varchar字段可以作为指针存储在块外部,这样,该块在查询中保持可预测的大小-但这是一个实现细节,并且可能因数据库而异D b。
Varchar fields can be stored as a pointer outside the block, so that the block keeps a predictable size on queries - but that is an implementation detail and may vary from db to db.
这篇关于Postgres SQL中的字符串字段长度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!