NULL in MySQL (Performance & Storage)

后端 未结 4 794
北荒
北荒 2020-11-22 12:31

What exactly does null do performance and storage (space) wise in MySQL?

For example:

TINYINT: 1 Byte TINYINT w/NULL 1 byte + somehow stores NULL?

4条回答
  •  谎友^
    谎友^ (楼主)
    2020-11-22 12:32

    Bill's answer is good, but a little bit outdated. The use of one or two bytes for storing NULL applies only to InnoDB REDUNDANT row format. Since MySQL 5.0.3 InnoDB uses COMPACT row format which uses only one bit to store a NULL (of course one byte is the minimum), therefore:

    Space Required for NULLs = CEILING(N/8) bytes where N is the number of NULL columns in a row.

    • 0 NULLS = 0 bytes
    • 1 - 8 NULLS = 1 byte
    • 9 - 16 NULLS = 2 bytes
    • 17 - 24 NULLS = 3 bytes
    • etc...

    According to the official MySQL site about COMPACT vs REDUNDANT:

    The compact row format decreases row storage space by about 20% at the cost of increasing CPU use for some operations. If your workload is a typical one that is limited by cache hit rates and disk speed, compact format is likely to be faster.

    Advantage of using NULLS over Empty Strings or Zeros:

    • 1 NULL requires 1 byte
    • 1 Empty String requires 1 byte (assuming VARCHAR)
    • 1 Zero requires 4 bytes (assuming INT)

    You start to see the savings here:

    • 8 NULLs require 1 byte
    • 8 Empty Strings require 8 bytes
    • 8 Zeros require 32 bytes

    On the other hand, I suggest using NULLs over empty strings or zeros, because they're more organized, portable, and require less space. To improve performance and save space, focus on using the proper data types, indexes, and queries instead of weird tricks.

    More on: https://dev.mysql.com/doc/refman/5.7/en/innodb-physical-record.html

提交回复
热议问题