Question: I have got a table with the following syntax:

```
ID, VALUE, TIMESTAMP

```

`(ID,TIMESTAMP)` is primary key, so there might be more than one row for each ID. There are 5000 unique ids.

I want to retrieve the most recent entry for each ID.

My naive way to do was:
 `SELECT * FROM table ORDER BY TIMESTAMP DESC LIMIT 5000;` 

For most cases this will give the correct result, but it is not guaranteed.

Because there might be 100k to 500k entries in the Table I would like to take performance into account.

What do you suggest?

Answer: 
TRY THIS

```
SELECT ID, VALUE, TIMESTAMP 
  FROM table 
  GROUP BY ID 
  HAVING MAX(TIMESTAMP)
  ORDER BY TIMESTAMP DESC ;

```

OR

```
SELECT ID, VALUE, TIMESTAMP 
  FROM table 
  GROUP BY ID 
  ORDER BY TIMESTAMP DESC ;

```
You would find the latest date for each ID entry, try this

```
SELECT *
FROM table AS a
WHERE TIMESTAMP = (
    SELECT MAX(TIMESTAMP)
    FROM table AS b
    WHERE a.ID = b.ID
  )

```