📜  SQL 中的 CHAR 与 VARCHAR

📅  最后修改于: 2021-09-09 10:50:55             🧑  作者: Mango

1. CHAR 数据类型:
它是在SQL数据类型,其用于存储指定的固定长度的。如果字符串的长度小于设置或固定长度,则用额外的空格填充它,使其长度等于设置的长度。 CHAR 数据类型的存储大小为 n 字节(设置长度)。当我们期望列中的数据值具有相同长度时,我们应该使用这种数据类型。

例子:

考虑查询:

CREATE TABLE Student(Name VARCHAR(30), Gender CHAR(6));
INSERT into Student VALUES('Herry', 'Male');
INSERT into Student VALUES('Mahi', 'Female');
SELECT LENGTH(Gender) FROM Student;

输出:

LENGTH(Gender)
6
6

2. VARCHAR 数据类型:
它是在SQL数据类型是用来指定的一组的长度变长,但最大的存储。如果字符串的长度小于设置或固定长度,则它将按原样存储,而无需填充额外的空格。 VARCHAR 数据类型的存储大小等于输入字符串的实际长度(以字节为单位)。当我们期望列中的数据值是可变长度时,我们应该使用这种数据类型。

例子:

考虑查询:

CREATE TABLE Student(Name VARCHAR(20), Gender CHAR(6));
INSERT into Student VALUES('Herry', 'Male');
INSERT into Student VALUES('Mahi', 'Female');
SELECT LENGTH(Name) FROM Student;

输出:

LENGTH(Name)
5
4

CHAR 和 VARCHAR 数据类型之间的区别

SR.NO. CHAR VARCHAR
1. CHAR datatype is used to store character string of fixed length VARCHAR datatype is used to store character string of variable length
2. In CHAR, If the length of string is less than set or fixed length then it is padded with extra memory space. In VARCHAR, If the length of string is less than set or fixed length then it will store as it is without padded with extra memory spaces.
3. CHAR stands for “Character” VARCHAR stands for “Variable Character”
4. Storage size of CHAR datatypes is equal to n bytes i.e. set length Storage size of VARCHAR datatype is equal to the actual length of the entered string in bytes.
5. We should use CHAR datatype when we expect the data values in a column are of same length. We should use VARCHAR datatype when we expect the data values in a column are of variable length.
6. CHAR take 1 byte for each character VARCHAR take 1 byte for each character and some extra bytes for holding length information
9. Better performance than VARCHAR Performance is not good as compared to CHAR

结论:当值的长度发生变化时,VARCHAR 可以节省空间,但 CHAR 可能在性能方面更好。