pg.ddx.io  pgsql-sql@postgresql.org mailing list archive  
help / color / mirror / Atom feed
From: James Cloos <cloos@jhcloos.com>
To: pgsql-sql@postgresql.org
Subject: A more efficient way?
Date: Sun, 31 Oct 2010 02:59:20 -0400
Message-ID: <m3sjzm4zkv.fsf@jhcloos.com> (raw)

I've a third-party app which is slower than it ought to be.

It does one operation in particular by doing a query to get a list of
rows, and then iterates though them to confirm whether it actually wants
that row.  As you can imagine that is very slow.

This query gets the correct data set in one go, but is also slow:

 select p from m where s = 7 and p not in (select p from m where s != 7);

The p column is not unique; the goal is the set of p for which *every*
row with a matching p also has s=7.  (s and p are both integer columns,
if that matters.)

That takes about 38 seconds with this (explain analyze) plan:

                                                        QUERY PLAN
------------------------------------------------------------------------------------------------------------------------
 Index Scan using m_5 on m  (cost=8141.99..11519.73 rows=1 width=4) (actual time=564.689..37964.163 rows=243 loops=1)
   Index Cond: (s = 7)
   Filter: (NOT (SubPlan 1))
   SubPlan 1
     ->  Materialize  (cost=8141.99..13586.24 rows=523955 width=4) (actual time=0.003..80.734 rows=523948 loops=243)
           ->  Seq Scan on m  (cost=0.00..7413.34 rows=523955 width=4) (actual time=0.023..259.901 rows=523948 loops=1)
                 Filter: (s <> 7)
 Total runtime: 38121.781 ms

The index m_5 is btree (s).  

Can that be done is a way which requires only 1 loop?

My understanding is that:

 select p from m where s = 7  except select p from m where s != 7;

will return the same results as a simple 'select p from m where s = 7', yes?

Is there a way to do it with a self join which requires just a single loop?

-JimC
-- 
James Cloos <cloos@jhcloos.com>         OpenPGP: 1024D/ED7DAEA6



view thread (2+ messages)  latest in thread

Message-ID: <m3sjzm4zkv.fsf@jhcloos.com>
Permalink:  ../m3sjzm4zkv.fsf@jhcloos.com/
Also on:    postgresql.org/message-id/m3sjzm4zkv.fsf@jhcloos.com

 · 

reply

Reply instructions:

You may reply publicly to this message via plain-text email
using any one of the following methods:

* Reply to all the recipients using the --to and --cc options:
  reply via email

  To: pgsql-sql@postgresql.org
  Cc: cloos@jhcloos.com
  Subject: Re: A more efficient way?
  In-Reply-To: <m3sjzm4zkv.fsf@jhcloos.com>

* Save the following mbox file, import it into your mail client,
  and reply-to-all from there: mbox

This inbox is served by DDX for PostgreSQL; see mirroring instructions
for how to clone and mirror all data and code used for this inbox