SELECT i.country AS "Country", count( t.ipfrom ) AS "Count" FROM geoipcountry AS i, ( SELECT distinct(ipfrom) FROM loglines WHERE ptype = 1000 ) AS t WHERE t.ipfrom >= i.startip AND t.ipfrom <= i.endip GROUP BY i.country ORDER BY "Count" DESC; Sort (cost=948072.30..948072.68 rows=149 width=45) Sort Key: count(t.ipfrom) -> HashAggregate (cost=948065.06..948066.93 rows=149 width=45) -> Nested Loop (cost=639162.42..936532.45 rows=2306523 width=45) Join Filter: ("outer".ipfrom <= "inner".endip) -> Unique (cost=639162.42..643188.25 rows=251 width=11) -> Sort (cost=639162.42..641175.33 rows=805165 width=11) Sort Key: loglines.ipfrom -> Seq Scan on loglines (cost=0.00..560180.06 rows=805165 width=11) Filter: (ptype = 1000) -> Index Scan using geoipcountry_startip on geoipcountry i (cost=0.00..755.17 rows=27568 width=35) Index Cond: ("outer".ipfrom >= i.startip)(12 rows)