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 ;

```
```
Please try this :

SELECT * FROM 
(SELECT ID,
       VALUE,
    ROW_NUMBER() OVER(PARTITION BY ID ORDER BY TIMESTAMP DESC) AS TIMESTAMP
    FROM
    TABLE )
    WHERE TIMESTAMP=1 ;

If your DB supports QUALIFY statement you can try below also :

SELECT * FROM
        TABLE
    QUALIFY ROW_NUMBER() OVER(PARTITION BY ID ORDER BY TIMESTAMP DESC)=1 ;`enter code here`

```