4

I've got Postgres 11 version and production server. A procedure is rather slow and query (a piece of code in procedure) is something like that:

    create temp table tmp_pos_source as
        with ... (
            ...
        )
        , cte_emp as (
            ...
        )
        , cte_all as (
            ...
        )
        select  ...
        from    cte_all;
        analyze tmp_pos_source;

The query is slow and I want to create an index to improve speed.

create index idx_pos_obj_id on tmp_pos_source(pos_obj_id);

Where should I put it? After command ANALYZE or before?

5
  • A forgot to mention that this temporary table is used in further code in several join on filed pos_obj_id. So thats why i want to create index Commented Dec 12, 2022 at 8:23
  • Could you please share the DDL for the tables involved and the results from EXPLAIN(ANALYZE, VERBOSE, BUFFERS, COSTS) for the slow query? (in plain text). When a query is slow, you need the query plan to see where the time is spent and how to improve this. An index might help, but it's not a magic bullet: You need the right index. Commented Dec 12, 2022 at 8:36
  • Ok, I'll try. It is on production server and I can't retrieve it immediately) I was told that this piece of procedure (with further joins) lasts much time. But in theory - if index is needed, where should i put ANALYZE - after or before index? Commented Dec 12, 2022 at 8:43
  • You have to analyze anyway and an index doesn't improve the speed of analyze. The statistics aren't used by the index either. Commented Dec 12, 2022 at 8:49
  • Ok. I mean if I start analyze before creating index then statistics of temp table will not use the statistic of index...maybe I am wrong Commented Dec 12, 2022 at 8:54

1 Answer 1

5

It doesn't matter. The only time when it helps to ANALYZE a table after creating an index is when the index is on an expression rather than on a plain column. The reason is that PostgreSQL automatically collects statistics for each column, but statistics on expressions are only collected if there is an index or extended statistics on the expression.

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

1 Comment

Thanks, man! Helped much. Now I've understood the theoretic part of this situation

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.