[mysql] MySQL - Select the last inserted row easiest way

I simply need to select the last entered row specified by condition, e.g:

SELECT ID from bugs WHERE user=Me

I need to return only the very last ID entered by user 'Me'. Is there a simple way to do this? Thank you.

This question is related to mysql select

The answer is


MySqlCommand insert_meal = new MySqlCommand("INSERT INTO meals_category(Id, Name, price, added_by, added_date) VALUES ('GTX-00145', 'Lunch', '23.55', 'User:Username', '2020-10-26')", conn);
if (insert_meal .ExecuteNonQuery() == 1)
{
    long Last_inserted_id = insert_meal.LastInsertedId;
    MessageBox.Show(msg, "Success", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            else
            {
                MessageBox.Show("Failed to save meal");
            }

SELECT MAX(ID) from bugs WHERE user=Me

SELECT ID from bugs WHERE user=Me ORDER BY CREATED_STAMP DESC; BY CREATED_STAMP DESC fetches those data at index first which last created.

I hope it will resolve your problem


You can use ORDER BY ID DESC, but it's WAY faster if you go that way:

SELECT * FROM bugs WHERE ID = (SELECT MAX(ID) FROM bugs WHERE user = 'me')

In case that you have a huge table, it could make a significant difference.

EDIT

You can even set a variable in case you need it more than once (or if you think it is easier to read).

SELECT @bug_id := MAX(ID) FROM bugs WHERE user = 'me';
SELECT * FROM bugs WHERE ID = @bug_id;

Just after running mysql query from php

get it by

$lastid=mysql_insert_id();

this give you the alst auto increment id value


SELECT * FROM `table_name` 
ORDER BY `table_name`.`column_name` DESC
LIMIT 1 

One way to accomplish that is to order you records and limit to 1. For example if you have the following table ('data').

    id | user | price
   -------------------
    1  |  me  | 40.23
    2  |  me  | 10.23

Try the following sql query

  select * from data where user='me' order by id desc limit 1

It would be best to have a TIMESTAMP column that defaults to CURRENT_TIMESTAMP .. it is the only true predictive behavior you can find here.

The second-best thing you can do is ORDER BY ID DESC LIMIT 1 and hope the newest ID is the largest value.


In concurrency, the latest record may not be the record you just entered. It may better to get the latest record using the primary key.

If it is a auto increment field, use SELECT LAST_INSERT_ID(); to get the id you just created.