Aneeez
Aneeez

Reputation: 1452

Find the last inserted row that matches a query

I want to find the last inserted row that matches a query (ie, find the row that has the largest id among the matching rows.)

for instance, suppose the following query matches 3 rows. with ids, 1,2,and 3. I want to get only the row with id 3.

SELECT * FROM `table` WHERE `mail` = '[email protected]'

How do I do this?

Upvotes: 0

Views: 77

Answers (3)

Ullas
Ullas

Reputation: 11556

Query

SELECT * FROM tbl
WHERE `mail` = '[email protected]'
AND id=
(
    SELECT MAX(id) FROM tbl 
    WHERE `mail` = '[email protected]'
);

Fiddle demo

Upvotes: 1

Ankit Kumar
Ankit Kumar

Reputation: 180

Simply use Order By. You sort your result with Id values in decreasing order (that way, you would have maximum ID at the top, in this case 3) and then just limit your result with value 1. That would give you only one row, with max ID. So,

here goes the query:

SELECT * FROM *YourTableName* where mail = '*YourMail*'ORDER BY id DESC LIMIT 1;

Upvotes: 1

nobalG
nobalG

Reputation: 4620

You need to write your query like this

SELECT * 
FROM table_name
WHERE `mail` = '[email protected]'
ORDER BY id DESC
LIMIT 1

Upvotes: 1

Related Questions