Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PreparedStatement very slow, but manual query quick

I have a preparedstatement from a framework as followed:

SELECT OH.ORDER_ID, MAX(OS.STATUS_DATETIME) FROM public.ORDER_HEADER OH, public.ORDER_STATUS OS WHERE ((OH.ORDER_ID = OS.ORDER_ID AND OH.STATUS_ID = ? AND OS.STATUS_ID = ?)) GROUP BY OH.ORDER_
ID HAVING (MAX(OS.STATUS_DATETIME) <= ?) ORDER BY OH.ORDER_ID ASC

OrderHeader has 300 000 rows, OrderStatus has roughly 5-6 million. All queried fields have an index on them. The database is Postgres 9.1

SELECT OH.ORDER_ID, MAX(OS.STATUS_DATETIME) FROM ORDER_HEADER OH INNER JOIN ORDER_STATUS OS 
    ON ((OH.ORDER_ID = OS.ORDER_ID AND OH.STATUS_ID = 'ORDER_PARTIALLY_RECEIVED' AND OS.STATUS_ID = 'ORDER_PARTIALLY_RECEIVED'))
     GROUP BY OH.ORDER_ID HAVING (MAX(OS.STATUS_DATETIME) <= '2015-01-27 00:00:00') ORDER BY OH.ORDER_ID ASC

This is the query string when the parameters are substitued in.

Running the query from Java, as a PreparedStatement and parameters set in there is making the query to run for minutes (5-6 minutes). When i run the SQL manually, it takes 10 seconds. How is this possible, how can i explain it?

like image 747
Zsolt János Avatar asked Jan 30 '15 13:01

Zsolt János


1 Answers

Prepared statements are optimized without knowledge of actual parameters. In PostgreSQL 9.1 a prepared statements are optimized only for most common values. When prepared statements is slow, then you have to use a dynamic SQL. PostgreSQL has nice API - parametric queries - it is some between prepared statements and usual queries - It is safe against SQL injection, and it is immune against a problems with blind optimization.

like image 162
Pavel Stehule Avatar answered Oct 19 '22 22:10

Pavel Stehule