Re: mysterious difference in speed when combining two queries with OR

From: Theo Kramer <theo(at)flame(dot)co(dot)za>
To: pgsql-performance(at)postgresql(dot)org
Subject: Re: mysterious difference in speed when combining two queries with OR
Date: 2008-04-23 11:00:07
Message-ID: 07D098C5-D260-4E23-B56D-7A017A9139D6@flame.co.za
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-performance


On 23 Apr 2008, at 9:23AM, Hans Ekbrand wrote:

> I cannot understand why the following two queries differ so much in
> execution time (almost ten times)
>
> Query A (two queries)
>
> select distinct moment.mid from moment,timecard where parent = 45
> and (pid=17 and timecard.mid = moment.mid) order by moment.mid;
> select distinct moment.mid from moment,timecard where parent = 45
> and (pbar = 0) order by moment.mid;
>
> Query B (combining the two with OR)
>
> select distinct moment.mid from moment,timecard where parent = 45
> and ((pid=17 and timecard.mid = moment.mid) or (pbar = 0)) order by
> moment.mid;
>
> $ time psql -o /dev/null -f query-a.sql fektest
>
> real 0m2.016s
> user 0m1.532s
> sys 0m0.140s
>
> $ time psql -o /dev/null -f query-b.sql fektest
>
> real 0m28.534s
> user 0m1.516s
> sys 0m0.156s
>
> I have tested this in two different computers with different amount of
> RAM, fast or slow CPU, and the difference is persistent, almost ten
> times.
>
> I should say that this is on postgresql 7.4.16 (debian stable).
>
> Can query B be rewritten so that it would execute faster?

Try
select distinct moment.mid from moment,timecard where parent = 45 and
(pid=17 and timecard.mid = moment.mid) order by moment.mid
union all
select distinct moment.mid from moment,timecard where parent = 45 and
(pbar = 0) order by moment.mid;
--
Regards
Theo

In response to

Browse pgsql-performance by date

  From Date Subject
Next Message PFC 2008-04-23 12:56:56 Re: mysterious difference in speed when combining two queries with OR
Previous Message Hans Ekbrand 2008-04-23 09:22:09 Re: mysterious difference in speed when combining two queries with OR