title: Selecting batches of rows
body: <p>I have a table <code>widget_events</code> that records <code>event_what</code> events occurring to
  widget <code>widget_id</code> on date <code>event_when</code>.  It's possible for the same event to
  occur multiple times to the same widget on the same day.  For this reason,
  column <code>event_id</code> is used as primary key to distinguish such rows.  Here is
  the table declaration:</p>
  
  <pre><code>CREATE TABLE widget_events
  (
  event_id    int4 UNIQUE NOT NULL,
  event_when  date NOT NULL,
  event_what  text NOT NULL,
  widget_id   int4 REFERENCES widgets (widget_id) NOT NULL,
  PRIMARY KEY (event_id)
  );
  </code></pre>
  
  <p>The client application processes events in batches, where each batch consists
  of all events for one widget on one date.  However, the application has no
  previous knowledge of which widgets and dates are stored in <code>widget_events</code>.</p>
  
  <p>One possible solution is to start by selecting one random row from 
  <code>widget_events</code> (using SQL's <code>LIMIT</code>), and then do another query for all
  rows with the same <code>widget_id</code> and <code>widget_when</code>.  After this batch is
  processed, those rows can be deleted from <code>widget_events</code>, and we go back
  to the first step.  The algorithm stops when the first step reports that
  there is no more random row to return.</p>
  
  <p>My question is whether there is a faster, more elegant way to do this.
  Is it possible in SQL (in particular the SQL understood by PostgreSQL) 
  to return each distinct batch in a single query?</p>