This question already has an answer here:

I have a table which roughly looks like this

uuid uuid, 
id id, 
data text,
last_updated timestamp

Each row has an associated unique uuid. However, the key of interest is the id (indexed). Whenever we do an update, it happens that a row with the same id is inserted, the timestamp is the moment of putting it in the database, and it gets its own uuid. I would like to retrieve several of these rows in one query, but retrieving only the latest version.

So far I have

SELECT * FROM table WHERE id IN (16638051, 14727883) 
GROUP BY id, uuid;

(ids are examples). However, I'm curious how to efficiently retrieve only the rows with the latest timestamp in that query?

Or would doing a single row at a time and retrieving it as a transaction be better?


This seems to do the trick (from another question).

   FROM   table
   WHERE  id IN (14727883, 16638051) 
   ORDER  BY id, last_updated DESC NULLS LAST
   ) sub

However, I wonder if a materialized view wouldn't be easier. It's a read heavy & low write database with a couple million rows, with the updates only happening daily.

marked as duplicate by Andriy M, Max Vernon, James Anderson, mustaccio, RolandoMySQLDBA May 16 '16 at 17:49

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

  • If your workload is read-biased, as you say, and especially if you most often are interested in the latest record for each ID, consider using a "history table" approach: keep only the most recent record in your "main" table and move older records to the history table as new records are inserted. It will affect write performance, of course, but it sounds like in your case it may be an acceptable price to pay for efficient reads. – mustaccio May 16 '16 at 17:54