<p>I have a postgres database with a user table (userid, firstname, lastname) and a usermetadata table (userid, code, content, created datetime). I store various information about each user in the usermetadata table by code and keep a full history. so for example, a user (userid 15) has the following metadata:</p>

<pre><code>15, 'QHS', '20', '2008-08-24 13:36:33.465567-04'  
15, 'QHE', '8', '2008-08-24 12:07:08.660519-04'  
15, 'QHS', '21', '2008-08-24 09:44:44.39354-04'  
15, 'QHE', '10', '2008-08-24 08:47:57.672058-04'  
</code></pre>

<p>I need to fetch a list of all my users and the most recent value of each of various usermetadata codes. I did this programmatically and it was, of course godawful slow. The best I could figure out to do it in SQL was to join sub-selects, which were also slow and I had to do one for each code.</p>

[{'answer_id': 25248, 'author': 'Henrik Gustafsson', 'author_id': 2010, 'author_profile': 'https://Stackoverflow.com/users/2010', 'pm_score': 2, 'selected': True, 'text': '<p>I suppose you\'re not willing to modify your schema, so I\'m afraid my answe might not be of much help, but here goes...</p>\n\n<p>One possible solution would be to have the time field empty until it was replaced by a newer value, when you insert the \'deprecation date\' instead. Another way is to expand the table with an \'active\' column, but that would introduce some redundancy.</p>\n\n<p>The classic solution would be to have both \'Valid-From\' and \'Valid-To\' fields where the \'Valid-To\' fields are blank until some other entry becomes valid. This can be handled easily by using triggers or similar. Using constraints to make sure there is only one item of each type that is valid will ensure data integrity.</p>\n\n<p>Common to these is that there is a single way of determining the set of current fields. You\'d simply select all entries with the active user and a NULL \'Valid-To\' or \'deprecation date\' or a true \'active\'.</p>\n\n<p>You might be interested in taking a look at the Wikipedia entry on <a href="http://en.wikipedia.org/wiki/Temporal_database" rel="nofollow noreferrer">temporal databases</a> and the article <a href="http://www.cs.arizona.edu/~rts/pubs/SIGMODRecordMarch94p52.pdf" rel="nofollow noreferrer">A consensus glossary of temporal database concepts</a>.</p>\n'}, {'answer_id': 27159, 'author': 'Neall', 'author_id': 619, 'author_profile': 'https://Stackoverflow.com/users/619', 'pm_score': 2, 'selected': False, 'text': '<p>This is actually not that hard to do in PostgreSQL because it has the <a href="http://www.postgresql.org/docs/8.3/static/sql-select.html#SQL-DISTINCT" rel="noreferrer">"DISTINCT ON"</a> clause in its SELECT syntax (DISTINCT ON isn\'t standard SQL).</p>\n\n<pre><code>SELECT DISTINCT ON (code) code, content, createtime\nFROM metatable\nWHERE userid = 15\nORDER BY code, createtime DESC;\n</code></pre>\n\n<p>That will limit the returned results to the first result per unique code, and if you sort the results by the create time descending, you\'ll get the newest of each.</p>\n'}, {'answer_id': 30312, 'author': 'Mark Brackett', 'author_id': 2199, 'author_profile': 'https://Stackoverflow.com/users/2199', 'pm_score': 0, 'selected': False, 'text': '<p>A subselect is the standard way of doing this sort of thing. You just need a Unique Constraint on UserId, Code, and Date - and then you can run the following:</p>\n\n<pre><code>SELECT * \nFROM Table\nJOIN (\n   SELECT UserId, Code, MAX(Date) as LastDate\n   FROM Table\n   GROUP BY UserId, Code\n) as Latest ON\n   Table.UserId = Latest.UserId\n   AND Table.Code = Latest.Code\n   AND Table.Date = Latest.Date\nWHERE\n   UserId = @userId\n</code></pre>\n'}]
['https://Stackoverflow.com/questions/25224', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2462/']