I have a query like this
select Count(1) as Count, pt.Name as TypeName, pt.ID as TypeID, pc.ID as CatID,
o.Name as OffName, o.ID as OffID, pc.Color as Color, s.ID, s.ActionType,
s.EndTime, pt.Size, pt.Price, pt.Unit, pt.OffID as ProdOffID
from sess s
inner join off o on o.id = s.offid
inner join act a on a.sessid = s.id
inner join prod p on p.tagid = a.prodid
inner join ProdType pt on pt.id = p.prodtypeid and pt.offid = p.Offid
left join prodcat pc on pc.id = pt.prodcatid and pc.offid = pt.offid
where s.offid = ? and s.acttype in (?, ?)
Group By pt.Name, pt.ID, pc.ID, o.Name,
o.ID, pc.Color, s.ID, s.ActType,
s.EndTime, pt.Size, pt.Price, pt.Unit, pt.OffID
If I use bindValue for parameters, code block below takes lots of time (about 2 seconds)
QSqlQuery newQuery(db);
newQuery.prepare(queryString);
for (int parameterIndex=0;parameterIndex<values.count();parameterIndex++) {
newQuery.bindValue(parameterIndex,values[parameterIndex]);
}
newQuery.exec();
But if I replace ?‘s with values and if I don’t use bindValue code block below takes about 50ms.
QSqlQuery newQuery(db);
newQuery.prepare(queryString);
newQuery.exec();
Is this normal? What makes this difference?
Note that these tables have btree indexes for their FK’s.
Using Qt 4.7.4 compiled with VC2008SP1. Database is PostgreSQL.
Answering to my own question (thanks to Mat):
PostgreSQL optimizes this query’s plan according to values. So, prepared statements block these kind of optimizations and gives this query plan:
But ordinary queries changes query plan in optimized way: