Retrieve Last Row in MySQL
When working with MySQL databases, it is often necessary to retrieve the last row inserted in a table. This can be achieved to access recent data or compare it with previous entries.
Using Auto-Increment
You mentioned that your table has an auto-increment column, which makes finding the last row straightforward. The auto-increment field ensures that each newly inserted row has a unique ID that increments sequentially.
SQL Query to Select Last Row
To select the last row, you can use the following SQL query:
SELECT fields FROM table ORDER BY id DESC LIMIT 1;
This query sorts the table in descending order based on the id column and then retrieves only the first row from the sorted result. As the id column is auto-incrementing, the first row in the sorted result will be the last row inserted into the table.
Example
For instance, if you have the following table:
CREATE TABLE my_table ( id INT AUTO_INCREMENT PRIMARY KEY, data VARCHAR(255) );
And you insert the following data:
INSERT INTO my_table (data) VALUES ('Row 1'); INSERT INTO my_table (data) VALUES ('Row 2'); INSERT INTO my_table (data) VALUES ('Row 3');
Running the SELECT query will return the following result:
| id | data | |-----|-------| | 3 | Row 3 |
This indicates that Row 3 is the last row inserted in the my_table.
The above is the detailed content of How to Retrieve the Last Inserted Row in a MySQL Table with Auto-Increment?. For more information, please follow other related articles on the PHP Chinese website!