Indexing Null Values in PostgreSQL

后端 未结 5 1914
暗喜
暗喜 2021-02-12 03:32

I have a query of the form:

select m.id from mytable m
left outer join othertable o on o.m_id = m.id
    and o.col1 is not null and o.col2 is not null and o.col3         


        
5条回答
  •  日久生厌
    2021-02-12 04:25

    Partial indexes aren't going to help you here as they'll only find the records you don't want. You want to create an index that contains the records you do want.

    CREATE INDEX findDaNulls ON othertable ((COALESCE(col1,col2,col3,'Empty')))
    WHERE col1 IS NULL AND col2 IS NULL AND col3 IS NULL;
    
    SELECT * 
    FROM mytable m
    JOIN othertable o ON m.id = o.m_id
    WHERE COALESCE(col1,col2,col3,'Empty') = 'Empty';
    

    BTW searching for null left joins generally isn't as fast as using EXISTS or NOT EXISTS in Postgres.

提交回复
热议问题