The length of varchar storage in mysql
P粉455093123
P粉455093123 2024-04-01 15:50:34
0
1
407

Sorry, English is not my native language...:(

I want to understand how the actual length of varchar is stored in mysql .ibd file. So I decided to do a test like this:

CREATE TABLE record_format_demo (
         c1 VARCHAR(10),
        c2 VARCHAR(10) NOT NULL,
         c3 CHAR(10),
         c4 VARCHAR(10)
     ) CHARSET=ascii ROW_FORMAT=COMPACT;

INSERT INTO record_format_demo(c1, c2, c3, c4) VALUES('aaaa', 'bbb', 'cc', 'd');

SELECT * FROM record_format_demo;
+------+-----+------+------+
| c1   | c2  | c3   | c4   |
+------+-----+------+------+
| aaaa | bbb | cc   | d    |
+------+-----+------+------+

I open the ibd file through ultraEdit, and the hexadecimal varchar length is as follows:

  • HEX 01 is the length of c4, decimal is 1
  • HEX 03 is the length of c2, decimal is 3
  • HEX 04 is the length of c1, decimal is 4

But the values ​​of these columns are too short and only require one byte to count, so I did another test like this:

CREATE TABLE record_format_demo2 (
         c1 VARCHAR(10),
        c2 VARCHAR(256) NOT NULL,
         c3 CHAR(10),
         c4 VARCHAR(357)
     ) CHARSET=ascii ROW_FORMAT=COMPACT;
         
         
INSERT INTO record_format_demo2(c1, c2, c3, c4) VALUES('aaaa', REPEAT('a',127), 'cc', REPEAT('a', 356));

Its ibd file is as follows:

  • HEX 04 is the length of c1 because 'aaaa' is only 4 characters
  • HEX 7F is the length of c2, which is 127 in decimal, because c2 = REPEAT('a',127)

But the length of C4 in hexadecimal is 64 81 and in decimal it is 25729. More than 356. I tried adding two hexes, but 64 81 = E5 decimal is 229, which is not equal to 356.

This confuses me so I want to know why the hex for c4 shows up like this and how to find out 356

P粉455093123
P粉455093123

reply all(1)
P粉744691205

Maybe this:

  • x81 is 01, the high bit is turned on
  • The high bit means "this number is continuous"
  • The continuation is x64
  • Putting the parts together gives x0164 = decimal 356

Did you find where/how the NULL flag appears?

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template