Ekaterina Amez <ekaterina.amez@xxxxxxxxxxx> writes: > I've tested the query with psql and DBeaver and it takes only milliseconds: > it returns 39 records and now there's only 16000 records on the table but > I've tested it with <100K. When I've tested my php script the same query > takes 14 minutes to return (more or less). A plausible theory is that it's not really the same query, but differs in having some values presented as parameters not literal constants. Depending on exactly how you do it, that can confuse the planner leading to a poor execution plan and a long runtime. I'd first try enabling log_statement on the server to see if the query is really being presented exactly the same way. Another thing worth trying is auto_explain, to capture the plans actually being used. regards, tom lane