The difference between char, varchar, and nvarchar data types

1. char

     Fixed length, up to n characters.

     Advantages: CHAR is very convenient to store fixed-length data, and the index on the CHAR field is highly efficient. For example, if you define char(10), no matter whether the data you store reaches 10 bytes or not, it will take up 10 bytes of space .

2. varchar

     A variable string of maximum length n. (n is an integer, different databases, the maximum length n is different)

     The difference between char and varchar:

     Varchar must char to save space, but it is slightly less efficient than char.

     It is said that varchar is more space-saving than char because varchar is a variable string. For example, storing the string "abc" with varchar(5) only takes up 3 bytes of storage space, while storing with char(5) takes up 5 bytes ("abc").

     It is said that varchar is slightly less efficient than char because, when modifying varchar data, it may cause data migration (ie: redundant I/O) due to different data lengths. Among them, oracle's expression for this redundant I/O description is: "row migration" (Row Migration).

Row Migration:

      "When a row of records is initially inserted, it can be stored in a block. Due to the update operation, the row is increased, and the free space of the block is completely full. At this time, row migration occurs. In this case, oracle The entire row of data will be migrated to a new block, and Oracle will retain the original pointer of the migrated row to point to the new block that stores the row data, which means that the ROW ID of the migrated row will not change."

3. nvarchar

     The characteristics of nvarchar need to be compared with varchar.

     The difference between nvarchar and varchar is mainly in the way of storing data:

     1). varchar: store data in bytes

          varchar(6), can store up to 6 bytes of data, such as: "hahaha", "abcdef"...

Remarks: How many bytes a Chinese character occupies in the database depends on the encoding method of unicode, for example: utf8 occupies 3 bytes on mysql, Chinese_PRC_CI_AS of sqlserver occupies 2 bytes...

     2). nvarchar: store data by character

          nvarchar(6), can store up to 6 characters/Chinese data, such as: "hahahahahaha", "abcdef"...

          The maximum actual byte length stored in nvarchar(m) = n*m (n depends on the encoding method). If nvarchar stores English characters, the byte length of n is also stored according to the encoding method. In other words, if nvarchar is used to store English characters, more than half of the storage space will be wasted....

Summarize:

     1. The performance gap between char and varchar is very small and can be considered negligible.

     2. In applications with large amounts of data, using char and nvarchar may lead to a large waste of storage space.

 

Guess you like

Origin blog.csdn.net/qq_38481055/article/details/86433124