I want to retrieve the bottom 10 results from a sql server table. I want them to be the last 10 records that were inserted, how can I do this ?
I want to write
If there is a auto-increment id (primary key) for that table then you can do that:
select top 10 *
from mytable
order by id desc
https://stackoverflow.com/a/10636585/2858777
with bottom as(
select top 4 *
from tbl
order by n desc
)
select *
from bottom
order by n
Data source:
| N | |----| | 1 | | 2 | | 3 | | 4 | | 5 | | 6 | | 7 | | 8 | | 9 | | 10 |
Output:
| N | |----| | 7 | | 8 | | 9 | | 10 |
In MySQL you could use select * from table LIMIT 0,10
You can do it using a trigger.
Save the PKs for the just-inserted row in an audit table, along with an increasing index of some kind (identity is probably enough). Delete the oldest when there are more than 10 rows.
Then join the audit table to the original table to get the full 10 rows.
You can't.
There is no guarantee at all that the last 10 records returned by select * from mytable
will be the last 10 inserted. There is no default ordering that is used.
You need an ORDER BY
on an appropriate column reflecting insert order.