1

for example if i have a field name slug = models.CharField(null=True, db_index=True,max_length=50) and while saving data if left slug empty. will database index this saved null value?

2
  • This is database-dependent. For PostgreSQL, as far as I remember, it does save it in a bitmap, not in the btree, but yes it is indexed, and thus search should be boosted searching for null values: patshaughnessy.net/2014/11/11/… Commented Apr 16, 2020 at 19:00
  • @WillemVanOnsem you are right for PostgreSQL it does index null from version 8.3 ( 12 years old one) Commented Apr 16, 2020 at 19:33

1 Answer 1

3

Yes Postgresql does index NULL values.

Here is a small test case:

select version();
                                                  version                                                  
-----------------------------------------------------------------------------------------------------------
 PostgreSQL 9.5.21 on x86_64-pc-linux-gnu, compiled by gcc (GCC) 4.8.5 20150623 (Red Hat 4.8.5-39), 64-bit
(1 row)

create table t(c1 serial, c2 text);
CREATE TABLE

insert into t(c2) select generate_series(1,1000000);
INSERT 0 1000000

create index on t(c2);
CREATE INDEX

analyze t;
ANALYZE

update t set c2=null where c1=123456;
UPDATE 1

explain analyze select count(*) from t where c2 is null;
                                                      QUERY PLAN                                                

----------------------------------------------------------------------------------------------------------------
-------
 Aggregate  (cost=5.76..5.77 rows=1 width=0) (actual time=0.009..0.009 rows=1 loops=1)
   ->  Index Only Scan using t_c2_idx on t  (cost=0.42..5.76 rows=1 width=0) (actual time=0.006..0.006 rows=1 lo
ops=1)
         Index Cond: (c2 IS NULL)
         Heap Fetches: 1
 Planning time: 0.271 ms
 Execution time: 0.035 ms
(6 rows)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.