📜  char varchar nvarchar sql (1)

📅  最后修改于: 2023-12-03 14:40:03.780000             🧑  作者: Mango

char, varchar and nvarchar in SQL

When working with data in SQL, it's important to understand the difference between char, varchar, and nvarchar data types. These types are used to define the length and type of data that can be stored in a specific column.

char

char is a data type in SQL that is used to store fixed-length strings. When you create a char column, you specify the maximum number of characters that can be stored in that column. If the actual string is shorter than the maximum length, the remaining space is filled with empty spaces.

-- create a char column with a maximum length of 10 characters
CREATE TABLE MyTable (
  MyColumn char(10)
)

For example, if you insert the string 'hello' into this column, it will be stored as 'hello ' (with six empty spaces at the end to fill up the full length of the column).

varchar

varchar is similar to char, but instead of storing fixed-length strings, it stores variable-length strings. When you create a varchar column, you also specify a maximum length, but the actual length of the string can be shorter (or longer, up to a maximum of the specified length) than that maximum.

-- create a varchar column with a maximum length of 10 characters
CREATE TABLE MyTable (
  MyColumn varchar(10)
)

For example, if you insert the string 'hello' into this column, it will be stored as 'hello' (without any extra empty spaces).

nvarchar

nvarchar is similar to varchar, but it's used to store Unicode characters (which can be more than one byte long). Like varchar, you specify a maximum length for the column, but the actual length of the string can be shorter or longer.

-- create an nvarchar column with a maximum length of 10 characters
CREATE TABLE MyTable (
  MyColumn nvarchar(10)
)

For example, if you insert the string '您好' (which means "hello" in Chinese) into this column, it will take up two characters but still fit within the maximum length.

Conclusion

In summary, char, varchar, and nvarchar are all data types that are used to store strings in SQL. char is used for fixed-length strings, varchar for variable-length strings, and nvarchar for Unicode strings. When creating tables in SQL, it's important to choose the appropriate data type for each column to ensure optimal storage and performance.