title: Slow Postgres JOIN Query
body: <p>I'm trying to optimize a slow query that was generated by the Django ORM.  It is a many-to-many query.  It takes over 1 min to run.</p>
  
  <p>The tables have a good amount of data, but they aren't huge (400k rows in sp_article and 300k rows in sp_article_categories)</p>
  
  <pre><code>#categories.article_set.filter(post_count__lte=50)
  
  EXPLAIN ANALYZE SELECT * 
                    FROM "sp_article" 
              INNER JOIN "sp_article_categories" ON ("sp_article"."id" = "sp_article_categories"."article_id") 
                  WHERE ("sp_article_categories"."category_id" = 1081  
                    AND "sp_article"."post_count" &lt;= 50 )
  
  Nested Loop  (cost=0.00..6029.01 rows=656 width=741) (actual time=0.472..25.724 rows=1266 loops=1)
    -&gt;  Index Scan using sp_article_categories_category_id on sp_article_categories  (cost=0.00..848.82 rows=656 width=12) (actual time=0.015..1.305 rows=1408 loops=1)
          Index Cond: (category_id = 1081)
    -&gt;  Index Scan using sp_article_pkey on sp_article  (cost=0.00..7.88 rows=1 width=729) (actual time=0.014..0.015 rows=1 loops=1408)
          Index Cond: (sp_article.id = sp_article_categories.article_id)
          Filter: (sp_article.post_count &lt;= 50)
  Total runtime: 26.536 ms
  </code></pre>
  
  <p>I have an index on:</p>
  
  <pre><code>sp_article_categories.article_id (type: btree)
  sp_article_categories.category_id
  sp_article.post_count (type: btree)
  </code></pre>
  
  <p>Any suggestions on how I can tune this to get the query speedy?</p>
  
  <p>Thanks!</p>