Home > Database > Mysql Tutorial > How to Retrieve the Last Inserted Row in a MySQL Table with Auto-Increment?

How to Retrieve the Last Inserted Row in a MySQL Table with Auto-Increment?

DDD
Release: 2024-12-13 15:57:11
Original
687 people have browsed it

How to Retrieve the Last Inserted Row in a MySQL Table with Auto-Increment?

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;
Copy after login

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)
);
Copy after login

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');
Copy after login

Running the SELECT query will return the following result:

| id | data  |
|-----|-------|
| 3   | Row 3 |
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template