<?xml version="1.0" encoding="UTF-8" standalone="yes"?><oembed><version><![CDATA[1.0]]></version><provider_name><![CDATA[Occasionally Coherent]]></provider_name><provider_url><![CDATA[http://blog.bimajority.org]]></provider_url><author_name><![CDATA[Garrett Wollman]]></author_name><author_url><![CDATA[https://blog.bimajority.org/author/garrettwollman/]]></author_url><title><![CDATA[Simple database tricks]]></title><type><![CDATA[link]]></type><html><![CDATA[<p>I&#8217;ve been keeping an inventory of my personal library in a database for more than a decade.  It was thus easy, when writing the previous post, to find out the exact number of books I had bought from SFBC.  I used the following SQL query:</p>
<pre>
SELECT EXTRACT(YEAR FROM purchase_date), COUNT(DISTNCT title)
    FROM inventory
    WHERE purchased_from = 'SFBC'
    GROUP BY EXTRACT(YEAR FROM purchase_date)
</pre>
<p>The results looked like this:</p>
<pre>
 date_part | count 
-----------+-------
      2001 |     1
      2002 |    11
      2003 |    24
      2004 |    18
      2005 |    24
      2006 |     8
      2007 |    10
      2008 |     6
      2009 |     4
      2010 |     5
      2011 |     5
      2012 |     9
      2013 |     3
           |   106
(14 rows)
</pre>
<p>I might ordinarily have used an <code>ORDER BY</code> clause to force the results into a useful order, but in this case the query planner decided to implement the <code>GROUP BY</code> using a sort so I didn&#8217;t need to.  The last row in the results shows all the books I bought before I started the inventory database in 2001; it corresponds to books whose <code>purchase_date</code> is <code>NULL</code> because I didn&#8217;t have any record of when they were purchased.</p>
]]></html></oembed>