Using CHAR and VARCHAR in MySQL

Asked 1 years ago, Updated 1 years ago, 382 views

How do I use CHAR and VARCHAR differently in MySQL 5.7?
I understood the following, but is it okay to put fixed length strings in VARCHAR and all VARCHAR?

  • CHAR is a fixed length, so it stores a fixed length string
  • VARCHAR is variable length, so it contains non-fixed length strings

mysql database

2022-12-05 11:24

1 Answers

The differences between varchar and char in mysql 5.7 are as follows:
https://dev.mysql.com/doc/refman/5.7/en/char.html

training spaces are removed from CHAR columns upon retrieval.

As you can see, there are the following differences:

create table example(avarchar(10), bchar(10));
insert into example values ('A', 'B');
insert into example values ('A', 'B');
insert into example values ('A', 'B');
select a, length(a), b, length(b) from example;
+------------------------------------------------------------------------------------------------
| a | length(a) | b | length(b) |
+------------+-----------+------------+-----------+
| A | 1 | B | 1 |
|          A | 10 | B | 10 |
| A | 10 | B | 1 |
+------------+-----------+------------+-----------+

Char is fine if you want to handle fixed-length data that is not a trailing blank, but if you have enough capacity to include length information in varchar, it is almost the same.

Personally speaking, except for fixed-length data from outside (such as general-purpose machines), I think I usually use varchar (oracle varchar2).


2022-12-05 11:37

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.