I have this table:
and I need to get the last written value, that is, the last id of the table
How can I get it?
I have this table:
and I need to get the last written value, that is, the last id of the table
How can I get it?
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;
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.
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