Skip to content
Advertisement

How to increase performance of COUNT SQL query in PostgreSQL?

I have a table with multiply columns. But for simplicity purpose, we can consider the following table:

I want to execute this request:

It works fine, when I send string to string_to_array function with a few values (like 1-20). But when I try to send 500 elements, it works too slow. Unfortunately, I really need 100-500 elements.

Advertisement

Answer

For this query:

I would recommend an index on tmp_table(entity_1_id, entity_2_id, status).

However, you might find this faster:

Then you want an index on tmp_table(entity_2_id, entity_1_id, status).

In most databases, this would be faster, because the index is a covering index and this avoids the final aggregation over the entire result set. However, Postgres stores locking information on the data pages, so they still need to be read. It is still worth trying.

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement