-1

I've searched for long time for getting last entered data in a table. But I got same answer.

SELECT TOP 1 CustomerName FROM Customers
ORDER BY CustomerID DESC;

My scenario is, how to get last data if that Customers table is having CustomerName column only? No other columns such as ID or createdDate I entered four names in following order.

James
Arun
Suresh
Bryen

Now I want to select last entered CustomerName, i.e., Bryen. How can I get it..?

Sakthi
  • 103
  • 2
  • 13
  • 2
    There is no order in tables. There is no first or last row. If you want a specific order, you have to specify it with an `ORDER BY` clause. While you *could* use change tracking or CDC to get a list of all changes, this would be a serious abuse of change tracking and rather costly – Panagiotis Kanavos Feb 23 '16 at 13:48
  • Possible duplicate of [Find last row entered in a table](http://stackoverflow.com/questions/19982804/find-last-row-entered-in-a-table) – Tab Alleman Feb 23 '16 at 13:54

2 Answers2

0

If the table is not properly designed (IDENTITY, TIMESTAMP, identifier generated using SEQUENCE etc.), INSERT order is not kept by SQL Server. So, "last" record is meaningless without some criteria to use for ordering.

One possible workaround is if, by chance, records in this table are linked to some other table records (FKs, 1:1 or 1:n connection) and that table has a timestamp or something similar and you can deduct insertion order.

More details about "ordering without criteria" can be found here and here.

Community
  • 1
  • 1
Alexei - check Codidact
  • 22,016
  • 16
  • 145
  • 164
-1

; with cte_new as ( select *,row_number() over(order by(select 1000)) as new from tablename ) select * from cte_new where new=4

kumar
  • 1
  • 1
  • 1