title: PostgreSQL: Query for tstzrange that contains last instant of a quarter
body: <p>Given a PostgreSQL table that is supposed to contain rows with continuous, non-overlapping <code>valid_range</code> ranges such as:</p>
  
  <pre><code>CREATE TABLE tracking (
      id INT PRIMARY KEY,
      valid_range TSTZRANGE NOT NULL,
      EXCLUDE USING gist (valid_range WITH &amp;&amp;)
  );
  
  INSERT INTO tracking (id, valid_range) VALUES
      (1, '["2017-03-01 13:00", "2017-03-31 14:00")'),
      (2, '["2017-03-31 14:00", "2017-04-01 00:00")'),
      (3, '["2017-04-01 00:00",)');
  </code></pre>
  
  <p>That creates a table that contains:</p>
  
  <pre><code> id |                     valid_range                     
  ----+-----------------------------------------------------
    1 | ["2017-03-01 13:00:00-07","2017-03-31 14:00:00-06")
    2 | ["2017-03-31 14:00:00-06","2017-04-01 00:00:00-06")
    3 | ["2017-04-01 00:00:00-06",)
  </code></pre>
  
  <p>I need to query for the row that was the valid row at the end of a given quarter, where I'm defining "at the end of a quarter" as "the instant in time right before the date changed to be the first day of the new quarter."  In the above example, querying for the end of Q1 2017 (Q1 ends at the end of 2017-03-31, and Q2 begins 2017-04-01), I want my query to return only the row with ID 2.</p>
  
  <p>What is the best way to express this condition in PostgreSQL?</p>
  
  <p><code>SELECT * FROM tracking WHERE valid_range @&gt; TIMESTAMPTZ '2017-03-31'</code> is wrong because it returns the row that contains midnight on 2017-03-31, which is ID 1.</p>
  
  <p><code>valid_range @&gt; TIMESTAMPTZ '2017-04-01'</code> is also wrong because it skips over the row that was actually valid right at the end of the quarter (ID 2) and instead returns the row with ID 3, which is the row that starts the new quarter.</p>
  
  <p>I'm trying to avoid using something like <code>...ORDER BY valid_range DESC LIMIT 1</code> in the query.</p>
  
  <p>Note that the end of the ranges must always be exclusive, I cannot change that.</p>