Using Sqlite, I\'d like to fetch the collection of rows each with the greatest timestamp. The table contains the properties of items, which are key-value pairs and timestamp
In SQLite 3.7.11 or later, you can simply use MAX() to select one row from a group:
SELECT key, value, MAX(timestamp)
FROM Properties
WHERE thing = 'watermelon'
GROUP BY key;
Use HAVING
for simple and readable solution:
SQLFiddleDemo
SELECT *
FROM Properties
WHERE thing = "watermelon"
GROUP BY thing, key
HAVING timestamp = MAX(timestamp)
Tweaking the query found here, I've come up with the following:
SELECT a.*
FROM Properties AS a
INNER JOIN (
SELECT key, MAX(timestamp) AS max_timestamp
FROM Properties
WHERE thing='watermelon'
GROUP BY key) b
ON a.key = b.key AND a.timestamp = b.max_timestamp
WHERE thing='watermelon';
Seems to work, though I'd be interested in comments the pros/cons of this query.