Check last record of an sql table

Asked

Viewed 2,936 times

0

Good guys, next ... I’m trying to get the last record of a table with an id

SELECT * FROM tabela WHERE id = ? ORDER BY id DESC LIMIT 1

Except he’s not returning the last record, he’s going through the entire table behind a record, can anyone tell me how I do it? Thank you in advance!

3 answers

2

The clause WHERE will restrict the search to the number you put in ?. To query correct in that case would be:

SELECT * FROM tabela ORDER BY id DESC LIMIT 1;

2

The above answer is correct, when you define the id (or any field in the table), the query will only bring whatever has that specified value.

There are some alternatives to the proposed solution that you can see there on w3schools:

TOP:

SELECT TOP 1 * FROM tabela ORDER BY id;

ROWNUM:

SELECT * FROM tabela WHERE ROWNUM = 1;

1


this works well but add a column repeating the id you can delete or use subquery

SELECT MAX(collummID),* FROM tabela
  • Thank you! It worked the way I wanted it to!

Browser other questions tagged

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