0

Ok. I have a very large table used for statistics. I have a less data-dense version of the table also, which provides a backup and a way to clear down the main table. They are identical as far as columns, indexes, constraints.

The second table gets updated with specific anomolies from the main table, so if and when we clear down the data, the anomolies remain on record.

So I created a view which does a UNION between the 2 in order to query the data,

A cut-down version of the table...

ID
TIMESTAMP
KEY_1
KEY_2

There is a unique constraint on KEY_1,KEY2,TIMESTAMP

and an index on TIMESTAMP

If I query either table for a timestamp range and a single key_1,key_2, it uses the constraint. If I query the view, it uses the timestamp index and thus reads through all key_1,key_2 values. Even with another index TIMESTAMP, KEY_1, KEY_2 does it read using the TIMESTAMP index (the KEY_1 and KEY_2 are received from a JOINED table)

Thus, reading the VIEW for a lot of data takes ages as it scans 10000's more rows than reading the table directly.

It seems I cannot add a constraint to a view, so what can I do?

6
  • 2
    Please edit your question and add the query you are using and the execution plan generated using explain (analyze, buffers) (not just a "simple" explain). Formatted text please, no screen shots or upload the plan to explain.depesz.com
    – user330315
    Dec 13, 2018 at 9:35
  • Hi, I can't paste the explain in as I am prevented from showing publically, details of our database. Thus the generalised data above :(
    – gorf
    Dec 13, 2018 at 9:55
  • 1
    You can upload the plan to explain.depesz.com and choose to anonymize the table names
    – user330315
    Dec 13, 2018 at 9:59
  • Aha, ok useful. Query from view explain.depesz.com/s/gnoL Query from single table explain.depesz.com/s/6tfJ
    – gorf
    Dec 13, 2018 at 11:14
  • You must have made a mistake. The slow query returns way more rows. The queries seem to be different. Dec 13, 2018 at 20:58

0

Your Answer

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

Browse other questions tagged or ask your own question.