title: PostgreSQL - Smallint overflowing when creating index on multiple columns. Is this a bug?
body: <p>I was having an issue inserting the value 32767 into a <code>smallint</code> column in Postgres, which would yield the error <em>smallint out of range</em>.  This was odd because I could do:</p>
  
  <pre><code>SELECT 32767::int2;
  </code></pre>
  
  <p>Which would work just fine.  After a little hair pulling, I finally tracked this down to an index on the column in question.  First, here's the schema (Well, not really but I've simplified this down to a repro case):</p>
  
  <pre><code>CREATE TABLE Test
  (
    id uuid NOT NULL,
    cooktime smallint,
    preptime smallint,
    CONSTRAINT test_pkey PRIMARY KEY (id )
  )
  WITH (
    OIDS=FALSE
  );
  </code></pre>
  
  <p>I now create the following index:</p>
  
  <pre><code>CREATE INDEX idx_test_totaltime
    ON Test
    USING btree
    ((cooktime + preptime) );
  </code></pre>
  
  <p>Next, I try to create the following row:</p>
  
  <pre><code>INSERT INTO Test (CookTime, PrepTime, Id)
  VALUES (
    (32767)::int2,
    (10)::int2,
    (E'fd47dc1e-c3c6-42c1-b058-689e926a72a4')::uuid
  );
  </code></pre>
  
  <p>I get the error:</p>
  
  <blockquote>
    <p>ERROR: smallint out of range SQL state: 22003</p>
  </blockquote>
  
  <p>It seems that <code>idx_test_totaltime</code> is expecting a maximum value of <code>int2</code>, even though the index is applied on the sum of two smallints.</p>
  
  <p>Is this a Postgres bug, or am I missing something simple?  Is there a way to work around this <em>limitation</em>, or would I need to make these columns <code>int4</code> and use a CHECK constraint to limit each value to 32767?  I'm using Postgres 9.0.0 (Yes, I need to upgrade!) but I've created a <a href="http://sqlfiddle.com/#!1/734d7/1" rel="noreferrer">SQL Fiddle</a> which demonstrates this error on 9.1.4.</p>