0

I have this table:

enter image description here

and I need to get the last written value, that is, the last id of the table

How can I get it?

Community
  • 1
  • 1
  • 2
    By the `id` or by the `create_date`? You could just `ORDER BY [id] DESC` and `LIMIT 1`, among other solutions. – Cᴏʀʏ Oct 30 '18 at 02:06
  • any option is valid, I need the last –  Oct 30 '18 at 02:07
  • 1
    Possible duplicate of [Select last row in MySQL](https://stackoverflow.com/questions/4073923/select-last-row-in-mysql) – Cᴏʀʏ Oct 30 '18 at 02:08

3 Answers3

1

In MySQL or Postgres, you can do:

select t.*
from t
order by t.create_date desc
limit 1;

This assumes that you want one row, even if more than one row has the same maximum create_date in the table.

Normally, id would increase along with the create_date, so this probably does what you want:

select max(id)
from t;
Gordon Linoff
  • 1,242,037
  • 58
  • 646
  • 786
0

We can find the latest record in your table using a correlated subquery:

SELECT *
FROM yourTable
WHERE create_date = (SELECT MAX(create_date) FROM yourTable);

This would return multiple records, in the case of two or more records being tied for having the latest create_date.

If you are using Postgres or MySQL version 8 or later, then we can also use analytic functions here:

SELECT *
FROM
(
    SELECT *, ROW_NUMBER() OVER (ORDER BY create_date) DESC rn
    FROM yourTable
) t
WHERE rn = 1;

We can also replace ROW_NUMBER with RANK in case we want to get ties here as well.

Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360
-1

you can use juery ajax to get the last inserted id in mysql table like the query as

$sql="INSERT INTO users(firstname, lastname, email) VALUES ('khan', 'shan', 
'john@example.com')"

if($conn->query($sql))  // $conn as connection link
$last_id = $conn->insert_id; //will return last id
Masood Bhat
  • 74
  • 1
  • 9