On the contrary, "top" in the sql server, without using order, there are no keys / indexes

I want to get the bottom 10 results from sql server table. I want them to be the last 10 entries that have been inserted, how can I do this?

I want to write select bottom 10 * from mytable , however this does not exist (afaik).

I want the last 10 lines to be inserted. No timestamp.

+6
source share
5 answers

You can not.

There is no guarantee that the last 10 records returned by select * from mytable will be the last 10 inserted. The default order is not used.

You need ORDER BY in the corresponding column reflecting the insertion order.

+15
source

If there is an auto-increment identifier (primary key) for this table, you can do this:

 select top 10 * from mytable order by id desc 
+5
source

fooobar.com/questions/904982 / ...

with a bottom like (
select top 4 * from tbl sort by n desc) Select * bottom order by n

Data source:

| N | | ---- | | 1 | | 2 | | 3 | | 4 | | 5 | | 6 | | 7 | | 8 | | 9 | | 10 |

Conclusion:

| N | | ---- | | 7 | | 8 | | 9 | | 10 |

+2
source

In MySQL you can use select * from table LIMIT 0,10

0
source

You can do this with a trigger.

Save the PK for the row just inserted in the audit table along with an increasing index of some type (identification is probably sufficient). Remove the oldest when there are more than 10.

Then attach the audit table to the source table to get the full 10 rows.

0
source

Source: https://habr.com/ru/post/904980/


All Articles