Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does MySQL index NULL values?

I have a MySQL table where an indexed INT column is going to be 0 for 90% of the rows. If I change those rows to use NULL instead of 0, will they be left out of the index, making the index about 90% smaller?

like image 742
too much php Avatar asked Nov 14 '08 01:11

too much php


People also ask

Can indexes be NULL in MySQL?

For example, MySQL can use indexes and ranges to search for NULL with IS NULL .

Can index have NULL values?

By default, relational databases ignore NULL values (because the relational model says that NULL means "not present"). So, Index does not store NULL value, consequently if you have null condition in SQL statement, related index is ignored (by default).

What are the disadvantages of indexes in MySQL?

The Drawbacks of Using IndexesIndexes consume disk space – an index occupies its own space, so indexed data will consume more disk space too; Redundant and duplicate indexes can be a problem – MySQL allows you to create duplicate indexes on a column and it does not “protect you” from doing such a mistake.

Does SQL Server index nulls?

Yep, SQL Server stores the nulls in the index. That makes sense, really, because sooner or later, you're going to want to find the rows with nulls, and when you've only got a few nulls in a big table, the index can help a lot there.


2 Answers

http://dev.mysql.com/doc/refman/5.0/en/is-null-optimization.html

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.

like image 52
Chu Khanh Van Avatar answered Sep 28 '22 06:09

Chu Khanh Van


It looks like it does index the NULLs too.

Be careful when you run this because MySQL will LOCK the table for WRITES during the index creation. Building the index can take a while on large tables even if the column is empty (all nulls).

Reference.

like image 34
Bill the Lizard Avatar answered Sep 28 '22 07:09

Bill the Lizard