Note that there are some explanatory texts on larger screens.

plurals
  1. POPostgresql: inner join takes 70 seconds
    primarykey
    data
    text
    <p>I have two tables - </p> <p>Table A : 1MM rows, AsOfDate, Id, BId (foreign key to table B)</p> <p>Table B : 50k rows, Id, Flag, ValidFrom, ValidTo</p> <p>Table A contains multiple records per day between 2011/01/01 and 2011/12/31 across 100 BId's. Table B contains multiple non overlapping (between validfrom and validto) records for 100 Bids. </p> <p>The task of the join will be to return the flag that was active for the BId on the given AsOfDate.</p> <pre><code>select a.AsOfDate, b.Flag from A a inner Join B b on a.BId = b.BId and b.ValidFrom &lt;= a.AsOfDate and b.ValidTo &gt;= a.AsOfDate where a.AsOfDate &gt;= 20110101 and a.AsOfDate &lt;= 20111231 </code></pre> <p>This query takes ~70 seconds on a very high end server (+3Ghz) with 64Gb of memory.</p> <p>I have indexes on every combination of field as I'm testing this - to no avail.</p> <p>Indexes : a.AsOfDate, a.AsOfDate+a.bId, a.bid Indexes : b.bid, b.bid+b.validfrom</p> <p>Also tried the range queries suggested below (62seconds)</p> <p>This same query on the free version of Sql Server running in a VM takes ~1 second to complete.</p> <p>any ideas?</p> <p>Postgres 9.2</p> <p>Query Plan</p> <pre><code>QUERY PLAN --------------------------------------------------------------------------------------- Aggregate (cost=8274298.83..8274298.84 rows=1 width=0) -&gt; Hash Join (cost=1692.25..8137039.36 rows=54903787 width=0) Hash Cond: (a.bid = b.bid) Join Filter: ((b.validfrom &lt;= a.asofdate) AND (b.validto &gt;= a.asofdate)) -&gt; Seq Scan on "A" a (cost=0.00..37727.00 rows=986467 width=12) Filter: ((asofdate &gt; 20110101) AND (asofdate &lt; 20111231)) -&gt; Hash (cost=821.00..821.00 rows=50100 width=12) -&gt; Seq Scan on "B" b (cost=0.00..821.00 rows=50100 width=12) </code></pre> <p>see <a href="http://explain.depesz.com/s/1c5" rel="nofollow noreferrer">http://explain.depesz.com/s/1c5</a> for the analyze output </p> <p><img src="https://i.stack.imgur.com/2CWWU.png" alt="here is the query plan from sqlserver for the same query"></p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload