108

What is the most efficient way to read the last row with SQL Server?

The table is indexed on a unique key -- the "bottom" key values represent the last row.

Victor Zakharov
  • 25,801
  • 18
  • 85
  • 151
rp.
  • 17,483
  • 12
  • 63
  • 79

18 Answers18

203

If you're using MS SQL, you can try:

SELECT TOP 1 * FROM table_Name ORDER BY unique_column DESC 
EggyBach
  • 4,148
  • 1
  • 18
  • 21
23
select whatever,columns,you,want from mytable
 where mykey=(select max(mykey) from mytable);
Adam Pierce
  • 33,531
  • 22
  • 69
  • 89
18

You'll need some sort of uniquely identifying column in your table, like an auto-filling primary key or a datetime column (preferably the primary key). Then you can do this:

SELECT * FROM table_name ORDER BY unique_column DESC LIMIT 1

The ORDER BY column tells it to rearange the results according to that column's data, and the DESC tells it to reverse the results (thus putting the last one first). After that, the LIMIT 1 tells it to only pass back one row.

willurd
  • 11,745
  • 5
  • 28
  • 23
  • 5
    Wow, harsh, the original question didn't even say SQL Server specifically. The above solution is perfectly legitimate even though SQL Server uses different words to describe the same concept. +1 – Greg Hewgill Oct 07 '08 at 06:08
  • @VinkoVrsalovic it doesn't mean the answer is useless contrarily, even after a decade. Do you concur with me, sir? – Soner from The Ottoman Empire Dec 07 '20 at 14:52
  • 1
    This is the problem with written communication - it's easy to read it much more harshly than what's intended, especially when it's brief! I now know that and I understand the onus is on the writer. So, if I were to write that today I'd say: "That's the idea, although you'd need to use TOP instead of LIMIT for SQL Server, as that's the DMBS engine tagged in the question. See https://learn.microsoft.com/en-us/sql/t-sql/queries/top-transact-sql?view=sql-server-ver15" @snr – Vinko Vrsalovic Dec 07 '20 at 15:14
13

If some of your id are in order, i am assuming there will be some order in your db

SELECT * FROM TABLE WHERE ID = (SELECT MAX(ID) FROM TABLE)

lionelmessi
  • 1,116
  • 2
  • 10
  • 17
5

I think below query will work for SQL Server with maximum performance without any sortable column

SELECT * FROM table 
WHERE ID not in (SELECT TOP (SELECT COUNT(1)-1 
                             FROM table) 
                        ID 
                 FROM table)

Hope you have understood it... :)

ConsiderItDone
  • 166
  • 1
  • 5
4
SELECT TOP 1 id from comission_fees ORDER BY id DESC 
Hans Kesting
  • 38,117
  • 9
  • 79
  • 111
Ashish Pathak
  • 827
  • 8
  • 16
3

I tried using last in sql query in SQl server 2008 but it gives this err: " 'last' is not a recognized built-in function name."

So I ended up using :

select max(WorkflowStateStatusId) from WorkflowStateStatus 

to get the Id of the last row. One could also use

Declare @i int
set @i=1
select WorkflowStateStatusId from Workflow.WorkflowStateStatus
 where WorkflowStateStatusId not in (select top (
   (select count(*) from Workflow.WorkflowStateStatus) - @i ) WorkflowStateStatusId from .WorkflowStateStatus)
Neha Verma
  • 29
  • 1
3

You can use last_value: SELECT LAST_VALUE(column) OVER (PARTITION BY column ORDER BY column)...

I test it at one of my databases and it worked as expected.

You can also check de documentation here: https://msdn.microsoft.com/en-us/library/hh231517.aspx

Gil Gomes
  • 86
  • 1
  • 5
2

OFFSET and FETCH NEXT are a feature of SQL Server 2012 to achieve SQL paging while displaying results.

The OFFSET argument is used to decide the starting row to return rows from a result and FETCH argument is used to return a set of number of rows.

SELECT *
FROM table_name
ORDER BY unique_column desc
OFFSET 0 Row
FETCH NEXT 1 ROW ONLY
Cody Gray - on strike
  • 239,200
  • 50
  • 490
  • 574
2

In order to retrieve the last row of a table for MS SQL database 2005, You can use the following query:

select top 1 column_name from table_name order by column_name desc; 

Note: To get the first row of the table for MS SQL database 2005, You can use the following query:

select top 1 column_name from table_name; 
Victor Zakharov
  • 25,801
  • 18
  • 85
  • 151
  • 2
    `select top 1` without an order by is not a reliable way to get the first record. If you don't put in an order by, you give permission for SQL to give you any record it pleases. – Code Magician Feb 09 '12 at 17:35
1

If you don't have any ordered column, you can use the physical id of each lines:

SELECT top 1 sys.fn_PhysLocFormatter(%%physloc%%) AS [File:Page:Slot], 
              T.*
FROM MyTable As T
order by sys.fn_PhysLocFormatter(%%physloc%%) DESC
Sylvain Rodrigue
  • 4,751
  • 5
  • 53
  • 67
  • this is a really good answer for abstractions whereby a key field may not be known or may not even exist. However, %%physloc%% is ascending and sorting by the formatted field causes errors e.g. (1:2:30) appears less than (1:2:4). Suggest changing the query to remove the formatter and instead use %%physloc%% directly, e.g. ---- order by %%physloc%% desc ---- – MoustacheDangerous Jan 12 '21 at 12:24
0

This is how you get the last record and update a field in Access DB.

UPDATE compalints SET tkt = addzone &'-'& customer_code &'-'& sn where sn in (select max(sn) from compalints )

Rathakrishnan Ramasamy
  • 1,612
  • 2
  • 25
  • 46
0

If you have a Replicated table, you can have an Identity=1000 in localDatabase and Identity=2000 in the clientDatabase, so if you catch the last ID you may find always the last from client, not the last from the current connected database. So the best method which returns the last connected database is:

SELECT IDENT_CURRENT('tablename')
c00kiemon5ter
  • 16,994
  • 7
  • 46
  • 48
0

Well I'm not getting the "last value" in a table, I'm getting the Last value per financial instrument. It's not the same but I guess it is relevant for some that are looking to look up on "how it is done now". I also used RowNumber() and CTE's and before that to simply take 1 and order by [column] desc. however we nolonger need to...

I am using SQL server 2017, we are recording all ticks on all exchanges globally, we have ~12 billion ticks a day, we store each Bid, ask, and trade including the volumes and the attributes of a tick (bid, ask, trade) of any of the given exchanges.

We have 253 types of ticks data for any given contract (mostly statistics) in that table, the last traded price is tick type=4 so, when we need to get the "last" of Price we use :

select distinct T.contractId,
LAST_VALUE(t.Price)over(partition by t.ContractId order by created ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING)
from [dbo].[Tick] as T
where T.TickType=4

You can see the execution plan on my dev system it executes quite efficient, executes in 4 sec while the exchange import ETL is pumping data into the table, there will be some locking slowing me down... that's just how live systems work. execution plan against 85,697,659 rows

Walter Verhoeven
  • 3,867
  • 27
  • 36
0
SELECT * from Employees where [Employee ID] = ALL (SELECT MAX([Employee ID]) from Employees)
musefan
  • 47,875
  • 21
  • 135
  • 185
manas
  • 11
  • 1
    Best answer similarly we can get the first row SELECT * from Employees where [Employee ID] = ALL (SELECT MIN([Employee ID]) from Employees) – manas Jul 01 '11 at 18:22
0

It is very simple

select top 10 * from TableName order by 1 desc

Vintage Coder
  • 441
  • 1
  • 6
  • 9
-1
SELECT * FROM TABLE WHERE ID = (SELECT MAX(ID) FROM TABLE)
gung - Reinstate Monica
  • 11,583
  • 7
  • 60
  • 79
  • Welcome to the site. This could be a comment (if you had the rep), would you mind expanding it by adding some text to explain how it solves the problem & to differentiate it from the 10 preceding answers? – gung - Reinstate Monica Jul 19 '14 at 14:36
-6

I am pretty sure that it is:

SELECT last(column_name) FROM table

Becaause I use something similar:

SELECT last(id) FROM Status
Taryn
  • 242,637
  • 56
  • 362
  • 405