locked
Sql query RRS feed

  • Question

  • User-1458744719 posted

    Sql query to get latest row added in the table

    Wednesday, June 6, 2012 7:24 AM

Answers

  • User1648350404 posted

    if ID is primary key and identity column

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

    OR

    select top 1 * from TABLE_NAME  order by ID desc

    OR

    SELECT *
    FROM    TABLE
    WHERE  ID = IDENT_CURRENT('TABLE')

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Wednesday, June 6, 2012 7:33 AM

All replies

  • User1648350404 posted

    if ID is primary key and identity column

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

    OR

    select top 1 * from TABLE_NAME  order by ID desc

    OR

    SELECT *
    FROM    TABLE
    WHERE  ID = IDENT_CURRENT('TABLE')

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Wednesday, June 6, 2012 7:33 AM
  • User681036950 posted

    There's a lot you're not telling us.  Do you have a primary key?  Is that key a sequential int?

    If so you can use this to get the last one entered:

    SELECT TOP 1 * FROM TABLE order by Primary_Key_ID desc



    Wednesday, June 6, 2012 7:36 AM
  • User-1598965247 posted

    if you have set primary key as an identity column then use

    select @@IDENTITY

    to get the last inserted identity value

    Wednesday, June 6, 2012 7:37 AM
  • User-1590429200 posted

    Look at this example:

    1. CREATE TABLE [dbo].[EmpTbl]([Eid] [int] IDENTITY(1,1) NOT NULL,[Ename] [varchar](50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL) ON [PRIMARY]

    2. Insert into Emptbl values('sen')
    3. select * from emptbl where Eid=@@identity

       
    Wednesday, June 6, 2012 7:42 AM
  • User-665004399 posted

    hi,

    if you have any data r datetime column in your table you can give order by that column desending

    for ex:

    SELECT top 1 *
        FROM  your_table_name
        ORDER BY your_date_time_column DESC

    Wednesday, June 6, 2012 8:12 AM
  • User-116196265 posted

    select  scope_identity()

    Wednesday, June 6, 2012 2:33 PM