Re: [SQL] query with subquery abnormally slow?

From: Oskar Liljeblad <osk(at)hem(dot)passagen(dot)se>
To: Moray McConnachie <moray(dot)mcconnachie(at)computing-services(dot)oxford(dot)ac(dot)uk>
Cc: pgsql-sql(at)postgresql(dot)org
Subject: Re: [SQL] query with subquery abnormally slow?
Date: 1999-11-01 20:36:53
Message-ID: 19991101213653.A8213@oskar
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-sql

On Mon, Nov 01, 1999 at 07:59:20PM -0000, Moray McConnachie wrote:
> > select *
> > from items
> > where package in
> > (select package
> > from items
> > where ...blah...
> > group by package)
>
> Can't see why you don't rewrite this as one query:
>
> select * from items where ... blah ... order by package;
> (is it aggregates in the where clause?)

The items table consists of some columns `performer', `title',
and `package'. Each row corresponds to a song (or similar),
and a `package' is the album (or similar) the song is on.
(This design could certainly be improved with multiple tables,
but it wasn't created that way.)

My query is supposed to list all songs on all albums (packages)
which has at least one song by a specific artist (performer).
("Can you show me some stats on the albums which artist X
has participated in?".)

> Assuming you do need to do it the way you have done it ,
...
> should do it. itemid should be replaced by whatever the primary key of the
> items table is. Note that in blah, fields must be referred to as
> itemcopy.field1,itemcopy.field2, etc.

This query works:

select *
from items i1
where exists
(select package
from items i2
where i2.performer ~ '...'
and i1.package = i2.package
group by i2.package)

However this was also very slow (>30 seconds). When I replaced
"and i1.package = i2.package" with "and i1.id = i2.id" only some
songs from the matching albums were returned. (The songs which
matched performer ~ '...'.)

Oskar Liljeblad (osk(at)hem(dot)passagen(dot)se)

In response to

Browse pgsql-sql by date

  From Date Subject
Next Message Tom Lane 1999-11-01 22:10:28 Re: [SQL] query with subquery abnormally slow?
Previous Message Bill Brandt 1999-11-01 20:35:40 Re: [SQL] query with subquery abnormally slow?