Return only the last record inserted in the Mysql database

Asked

Viewed 8,718 times

1

Hello guys I’m with a project but I have to make a query and return the "last line" or last record inserted in the database.

  • if you have id autoincrement select id..... order by DESC limit 1

  • 1

    If your table has a "created in" type field that is timestamp SELECT MAX(criado_em) FROM tabela

  • 1

    https://answall.com/q/97453/91

1 answer

2

There are two ways to return the last record of a table in the mysql database.

By the higher primary key value of the table or ID field, for example: SELECT MAX(ID) FROM table
Where the ID variable is the primary key and table is the name of your table.

In descending order of selection, for example: SELECT ID FROM table ORDER BY ID DESC LIMIT 1 Where the ID variable is the primary key and table is the name of your table.

For the last record added from the INSERT command, for example: INSERT INTO table (name) VALUES ($name)

SELECT LAST_INSERT_ID() Commands must be executed together, otherwise LAST_INSERT_ID will return 0 as a result.

Browser other questions tagged

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