title: How to round to nearest X minutes with PL/pgSQL?
body: <p>How I can round to nearest X minutes? </p>
  
  <p>Here's my attempt:</p>
  
  <pre><code>DECLARE
    _stamp ALIAS FOR $1; -- timestamp
    _nearest ALIAS FOR $2; -- minutes (integer)
    _minutes decimal;
    _ret timestamp;
  BEGIN
    _ret := date_trunc('minute', _stamp);
  
    SELECT EXTRACT (minute FROM _ret)::integer INTO _minutes;
  
   IF (_minutes % _nearest &lt; (_nearest / 2)) THEN
      RETURN _ret + _minutes * interval '1 minute';
    ELSE
      RETURN _ret - _minutes * interval '1 minute';
    END IF;
  
    RETURN _ret;
  END;
  </code></pre>
  
  <p>Example:</p>
  
  <pre><code>SELECT round_to_nearest_minute ('2010-01-01 12:34:56', 15);
  </code></pre>
  
  <p>Should return</p>
  
  <pre><code>2010-01-01 12:30:00
  </code></pre>