How to read the last row with SQL Server

后端 未结 17 747
别那么骄傲
别那么骄傲 2020-11-29 03:40

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.

相关标签:
17条回答
  • 2020-11-29 04:27

    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.

    0 讨论(0)
  • 2020-11-29 04:27

    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)
    
    0 讨论(0)
  • 2020-11-29 04:27
    SELECT * FROM TABLE WHERE ID = (SELECT MAX(ID) FROM TABLE)
    
    0 讨论(0)
  • 2020-11-29 04:28
    select whatever,columns,you,want from mytable
     where mykey=(select max(mykey) from mytable);
    
    0 讨论(0)
  • 2020-11-29 04:28

    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)

    0 讨论(0)
提交回复
热议问题