How to get in SQL the last record inserted according to its date

Asked

Viewed 50,072 times

8

I need to get a record from a table, where this record is what in date terms was last entered.

Gender:

SELECT Ped.Quantidade
FROM ped
WHERE data <= @data

But since I have several records it returns to me all, when I just want the last one entered by date.

  • Friend, what would be the DBMS? Mysql, Postgre, MS Sql?

  • 1

    Good is SQL SERVER !

1 answer

12


Select the last record by sorting by the date decreasing and restricting the number of lines with limit or top

SELECT Ped.Quantidade
FROM ped
WHERE data <=@data
ORDER BY data DESC limit 1

or

SELECT TOP 1 Ped.Quantidade
FROM ped
WHERE data <=@data
ORDER BY data DESC
    • 1 for the second consultation, but I believe they can be varied according to the DBMS. The ideal would be to have this information for more accurate information
  • @Reiksiel, for the @data has a sql server face.

  • lost, the first query could not run, could confirm it? rode in MS Sql Server

  • 1

    @Reiksiel, no sql server o limit is top in the most recent versions there are other keywords to make the results pagination, see this question

Browser other questions tagged

You are not signed in. Login or sign up in order to post.