Що таке VARCHAR у SQL

0 Comments

How are varchar values stored in a SQL Server database?

My fellow programmer has a strange requirement from his team leader; he insisted on creating varchar columns with a length of 16*2 n . What is the point of such restriction? I can suppose that short strings (less than 128 chars for example) a stored directly in the record of the table and from this point of view the restriction will help to align fields in the record, larger strings are stored in the database “heap” and only the reference to this string is saved in the table record. Is it so? Is this requirement has a reasonable background? BTW, the DBMS is SQL Server 2008.

5,787 72 72 gold badges 60 60 silver badges 131 131 bronze badges
3,255 3 3 gold badges 33 33 silver badges 43 43 bronze badges

3 Answers 3

Completely pointless restriction as far as I can see. Assuming standard FixedVar format (as opposed to the formats used with row/page compression or sparse columns) and assuming you are talking about varchar(1-8000) columns

All varchar data is stored at the end of the row in a variable length section (or in offrow pages if it can’t fit in row). The amount of space it consumes in that section (and whether or not it ends up off row) is entirely dependant upon the length of the actual data not the column declaration.

SQL Server will use the length declared in the column declaration when allocating memory (e.g. for sort operations). The assumption it makes in that instance is that varchar columns will be filled to 50% of their declared size on average so this might be a better thing to look at when choosing a size.

445k 89 89 gold badges 755 755 silver badges 860 860 bronze badges

I have heard of this practice before, but after researching this question a bit I don’t think there is a practical reason for having varchar values in multiples of 16. I think this requirement probably comes from trying to optimize the space used on each page. In SQL Server, pages are set at 8 KB per page. Rows are stored in pages, so perhaps the thinking is that you could conserve space on the pages if the size of each row divided evenly into 8 KB (a more detailed description of how SQL Server stores data can be found here). However, since the amount of space used by a varchar field is determined by its actual content, I don’t see how using lengths in multiples of 16 or any other scheme could help you optimize the amount of space used by each row on the page. The length of the varchar fields should just be set to whatever the business requirements dictate.

Additionally, this question covers similar ground and the conclusion also seems to be the same:
Database column sizes for character based data

27.2k 9 9 gold badges 71 71 silver badges 75 75 bronze badges
It could maybe also have to do with storage or indexing concerns.

You should always store the data in the data size that matches the data being stored. It is part of how the database can maintain integrity. For instance suppose you are storing email addresses. If your data size is the size of the maximum allowable emailaddress, then you will not be able to store bad data that is larger than that. That is a good thing. Some people want to make everything nvarchar(max) or varchar(max). However, this causes only indexing problems.

Personally I would have gone back to the person who make this requirement and asked for a reason. Then I would have presented my reasons as to why it might not be a good idea. I woul never just blindly implement something like this. In pushing back on a requirement like this, I would first do some research into how SQL Server organizes data on the disk, so I could show the impact of the requirement is likely to have on performance. I might even be surprised to find out the requirement made sense, but I doubt it at this point.

95.6k 15 15 gold badges 116 116 silver badges 188 188 bronze badges

Linked

Related

Hot Network Questions

Subscribe to RSS

To subscribe to this RSS feed, copy and paste this URL into your RSS reader.

Site design / logo © 2024 Stack Exchange Inc; user contributions licensed under CC BY-SA . rev 2024.3.8.5973

Разница между VARCHAR и VARCHAR2

Все кто имел дело с БД Oracle, знают, что объявлять символьные поля и переменные надо как VARCHAR2 , а не VARCHAR . Но эти типы данных вроде синонимы:

CREATE TABLE table1 ( id number, text VARCHAR(10), text2 VARCHAR2(10) ); Name Null Type ----- ---- ------------ ID NUMBER TEXT VARCHAR2(10) TEXT2 VARCHAR2(10) 

Никакой разницы. А придумали чтобы было что спрашивать на собеседованиях.

3 ответа 3

На данный момент они синонимы.

VARCHAR зарезервирован Oracle для поддержки, в будущем, различия между NULL и пустой строкой, как описано в стандарте ANSI .

VARCHAR2 не делает различий между NULL и пустой строкой, и никогда не будет делать.

Если вы полагаетесь на то, что пустая строка и NULL – одно и то же, используйте VARCHAR2 .

5,209 4 4 золотых знака 28 28 серебряных знаков 52 52 бронзовых знака
81.4k 9 9 золотых знаков 78 78 серебряных знаков 136 136 бронзовых знаков

В настоящее время, никакой разницы. Тип VARCHAR является псевдонимом VARCHAR2 и будет при объявлении заменён на VARCHAR2 .

VARCHAR зарезервирован для использования в будущих релизах для соответствия стандарту ANSI/ISO-SQL и Oracle не рекомендует этот тип к применению. Поэтому, все пользуются типом VARCHAR2 потому, что его поведение никогда не изменится.

В чём отличие VARCHAR2 от стандарта, их два:

  • пустая строка интерпретируется как NULL с длиной NULL (не 0)
  • NULL при конкантинации строк игнорируется, в стандарте результатом такой конкантинации будет NULL

Почему так вышло (сокращённо перефразирую@JustinCave):

Oracle очень старый производитель на рынке БД. Во времена, когда ещё SQL не был стандартизирован, теоретики Oracle приняли дизайнерское решение, что пустая строка в полях БД не содержит информации и по сути есть NULL .
Со временем, когда появился стандарт SQL и было решено, что NULL и пустая строка по сущности различны, уже было много пользователей со старым кодом, который эту разницу не учитывал. Так Oracle был поставлен перед выбором, делать существующий код не действительным или нарушать стандарт SQL. Был принято, по мнению Oracle, менее деструктивное решение, зарезервировать тип данных VARCHAR для изменения и соответствия стандарту SQL и введению нового типа данных VARCHAR2 , неизменность поведения которого гарантируется.

Когда будут произведены намеченые изменения в поведении VARCHAR ?

Так было в версии 7, заметьте фразу – “в следующей версии Oracle7”:

The VARCHAR datatype is currently synonymous with the VARCHAR2 datatype. It is recommended that you use VARCHAR2 rather than VARCHAR. In a future version of Oracle7, VARCHAR might be a separate datatype used for variable length character strings compared with different comparison semantics.

И, более чем 20 лет спустя, в релизе 19c:

Do not use the VARCHAR data type. Use the VARCHAR2 data type instead. Although the VARCHAR data type is currently synonymous with VARCHAR2, the VARCHAR data type is scheduled to be redefined as a separate data type used for variable-length character strings compared with different comparison semantics.