Skip to main content
1 of 6
umut
  • 285
  • 3
  • 7

postgresql performance issues on inherited tables with indices

I have a postgresql database with a master table and 2 child tables. My master table;

CREATE TABLE test_table (
    id serial,
    date timestamp without time zone,
    PRIMARY KEY (id)
);
CREATE INDEX ON test_table(date);

My child tables;

CREATE TABLE test_table_20150812 (
    CHECK ( date >= DATE '2015-08-12' AND date < DATE '2015-08-13' )
) INHERITS (test_table);

CREATE TABLE test_table_20150811 (
    CHECK ( date >= DATE '2015-08-11' AND date < DATE '2015-08-12' )
) INHERITS (test_table);

CREATE INDEX ON test_20150812(date);
CREATE INDEX ON test_20150811(date);

When I execute query like;

select * from test_table_20150812 where date > '2015-08-12' order by date desc;

It returns very quickly (20-30 miliseconds).

However if I execute query like;

select * from test_table where date > '2015-08-12' order by date desc;

It takes a long time (10-15 seconds). Constraint_exclusion is set to ON in my postgresql.conf . Therefore it should only be executed on test_table_20150812.

Explain result of two queries;
 Limit  (cost=196687.06..196687.19 rows=50 width=212)
   ->  Sort  (cost=196687.06..203617.51 rows=2772180 width=212)
         Sort Key: public.test_table.date
         ->  Result  (cost=0.00..104597.24 rows=2772180 width=212)
               ->  Append  (cost=0.00..104597.24 rows=2772180 width=212)
                     ->  Seq Scan on test_table  (cost=0.00..0.00 rows=1 width=1857)
                           Filter: (date > '2015-08-12 00:00:00'::timestamp without time zone)
                     ->  Seq Scan on test_table_20150812 test_table  (cost=0.00..104597.24 rows=2772179 width=212)
                           Filter: (date > '2015-08-12 00:00:00'::timestamp without time zone)
------
 Limit  (cost=0.00..2.69 rows=50 width=212)
   ->  Index Scan Backward using test_table_20150812_date_idx on test_table_20150812  (cost=0.00..149538.92 rows=2782286 width=212)
         Index Cond: (date > '2015-08-12 00:00:00'::timestamp without time zone)

I see that, if a query is executed on master table, indices are never used. How can I improve it? I want to make all my queries on my master table. When querying for a specific date I expect no performance difference between querying on the master table or the child table.

umut
  • 285
  • 3
  • 7