Book Image

PostgreSQL 9 Administration Cookbook - Second Edition

Book Image

PostgreSQL 9 Administration Cookbook - Second Edition

Overview of this book

Table of Contents (19 chapters)
PostgreSQL 9 Administration Cookbook Second Edition
Credits
About the Authors
About the Reviewers
www.PacktPub.com
Preface
Index

Why a query is not using an index


This recipe explains what to do if you think your query should use an index, but it does not.

There can be several reasons for this, but most often, the reason is that the optimizer believes that, based on the available distribution statistics, it is cheaper and faster to use a query plan that does not use an index.

How to do it…

Force index usage and compare plan costs with an index and without, like this:

mydb=# CREATE TABLE itable(id int PRIMARY KEY);
NOTICE:  CREATE TABLE / PRIMARY KEY will create implicit index "itable_pkey" for table "itable"
CREATE TABLE
mydb=# INSERT INTO itable SELECT generate_series(1,10000);
INSERT 0 10000
mydb=# ANALYZE;
ANALYZE
mydb=# EXPLAIN ANALYZE SELECT count(*) FROM itable WHERE id > 500;
                         QUERY PLAN
---------------------------------------------------------------------Aggregate  (cost=188.75..188.76 rows=1 width=0)
            (actual time=37.958..37.959 rows=1 loops=1)
    ->  Seq Scan on itable...