2

I tried to analyze why a certain query takes quite a long time. It runs on a partitioned PostgreSQL (v9.1) table. It is partitioned monthly. The rule is based on the a column which holds an integer representation of the date (so in example 20130801).

If I write a query like this one:

EXPLAIN     SELECT DISTINCT (user_id)
FROM users
WHERE
    date_tk >= 20130801

Only the relevant partitions get selected. But, when I run something like this, it scans all the partitions:

EXPLAIN     SELECT DISTINCT (user_id)
FROM users 
WHERE
    date_tk >= TO_CHAR(CURRENT_DATE - '30 days'::INTERVAL, 'yyyyMMdd')::INT

Now I casted the constraint date to int, so it seems to be ok I would assume, but unfortunately it isn't. Does somebody have an idea on how to improve this query so that only the relevant partitions get scanned?

Thanks, Diddy

2
  • 1
    here is some explanations and solution stackoverflow.com/questions/5973030/… Commented Oct 18, 2013 at 12:15
  • Thanks a lot! This explained it: "At the end of the day it looks like you're trying to index a "YYYY-MM-DD" representation of create_time. Why not just INDEX create_time? The problem is to_char() is MUTABLE because the locale environment variable could change, which changes the output of to_char()." Commented Oct 18, 2013 at 13:49

1 Answer 1

1

The expression you're using isn't considered immutable by Postgres (for the same reason now() isn't), so Postgres won't use it to consider when optimizing the lookup. Toss in an extra where clause that is constant and far enough in the past.

Alternatively, wouldn't using time stamps directly when partitioning avoid the issue altogether?

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for your help! I can supply constants as parameters to the query at runtime, so at least I have a workaround.

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.