title: Composite primary key and slow queries
body: <p>I have a table which looks like this:</p>
  <pre><code>  CREATE TABLE IF NOT EXISTS codes (
      code       character varying(255) NOT NULL,
      used       boolean NOT NULL DEFAULT FALSE,
      user_id    integer NOT NULL,
      order_id   integer,
      created    timestamp without time zone,
      CONSTRAINT pk_code PRIMARY KEY (code, user_id)
    );
  </code></pre>
  <p>And I have simple query:</p>
  <pre><code>SELECT COUNT(*) as &quot;count&quot; 
  FROM &quot;codes&quot; &quot;code&quot; 
  WHERE &quot;code&quot;.&quot;user_id&quot; = {some_id} 
   AND &quot;code&quot;.&quot;order_id&quot; IS NULL;
  </code></pre>
  <p>Which is very slow, explain analyze:</p>
  <pre class="lang-none prettyprint-override"><code>'Aggregate  (cost=3576.10..3576.11 rows=1 width=8) (actual time=1471.870..1471.871 rows=1 loops=1)'
  '  -&gt;  Seq Scan on codes (cost=0.00..3323.89 rows=50443 width=17) (actual time=0.139..203.139 rows=49998 loops=1)'
  '        Filter: ((order_id IS NULL) AND (user_id = 10))'
  '        Rows Removed by Filter: 116498'
  'Planning Time: 1.450 ms'
  'Execution Time: 1471.981 ms'
  </code></pre>
  <p>How can I optimize this query?</p>