I am writing analytics software that generates complicated queries. When building the where clause, it may happen that multiple constraints are added on the same database field. I was wondering if PostgreSQL rewrites multiple constraints into simpler ones. I did some tests:
SELECT COUNT(id) FROM employee WHERE age BETWEEN 18 AND 40;
I ran this 10 times and the average time spent was 65ms. Now I make the query a bit longer but trivial to optimize:
SELECT COUNT(id) FROM employee WHERE
(age BETWEEN 18 AND 40) AND
(age BETWEEN 18 AND 40) AND
(age BETWEEN 18 AND 40);
This query takes 100ms on average, which is a lot slower. Also, the following query:
SELECT COUNT(id) FROM employee WHERE
(age BETWEEN 28 AND 70) AND
(age BETWEEN 25 AND 40) AND
(age BETWEEN 22 AND 33) AND
(age BETWEEN 18 AND 30);
takes 105ms on average, while it is equivalent to:
SELECT COUNT(id) FROM employee WHERE age BETWEEN 28 AND 30;
which runs twice as fast.
These queries are semantically equivalent and I was expecting them to be optimized into the very same query before even the planner touches them. This seems like low-hanging fruit for the query rewriter. Is there any hidden configuration option I'm missing? I'm using postgresql 9.4.5.
Thank you!