Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NULL in MySQL (Performance & Storage)

Tags:

sql

null

mysql

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?

like image 637
Steve Avatar asked Oct 23 '08 10:10

Steve


People also ask

Is NULL SQL performance?

NOT NULL vs NULL performance is negligible and as per this article from 2016 (SQL SERVER), performance shouldn't be a consideration when deciding NOT NULL vs NULL. Even though that field will default to 'N', a command could still set it to NULL if nulls were allowed.

IS NULL Optimization in MySQL?

1.15 IS NULL Optimization. MySQL can perform the same optimization on col_name IS NULL that it can use for col_name = constant_value . For example, MySQL can use indexes and ranges to search for NULL with IS NULL .

IS NOT NULL performance MySQL?

MySQL doesn't recognize field = NULL because, remember, NULL means invalid, not empty. Thus using it will not return any rows. As much as NULL value will never be equal to another NULL , when using ORDER BY , GROUP BY and DISTINCT , the server interprets the values as equal.

Can NULLs improve your database queries performance?

that NULLs can potentially speed up your research because the index will have fewer rows. you can still index the NULL rows if you add another NOT NULL column to the index or even a constant.


1 Answers

It depends on which storage engine you use.

In MyISAM format, each row header contains a bitfield with one bit for each column to encode NULL state. A column that is NULL still takes up space, so NULL's don't reduce storage. See https://dev.mysql.com/doc/internals/en/myisam-introduction.html

In InnoDB, each column has a "field start offset" in the row header, which is one or two bytes per column. The high bit in that field start offset is on if the column is NULL. In that case, the column doesn't need to be stored at all. So if you have a lot of NULL's your storage should be significantly reduced. See https://dev.mysql.com/doc/internals/en/innodb-field-contents.html

EDIT:

The NULL bits are part of the row headers, you don't choose to add them.

The only way I can imagine NULLs improving performance is that in InnoDB, a page of data may fit more rows if the rows contain NULLs. So your InnoDB buffers may be more effective.

But I would be very surprised if this provides a significant performance advantage in practice. Worrying about the effect NULLs have on performance is in the realm of micro-optimization. You should focus your attention elsewhere, in areas that give greater bang for the buck. For example adding well-chosen indexes or increasing database cache allocation.

like image 59
Bill Karwin Avatar answered Nov 09 '22 04:11

Bill Karwin