
- Learn MySQL
- MySQL - Home
- MySQL - Introduction
- MySQL - Installation
- MySQL - Administration
- MySQL - PHP Syntax
- MySQL - Connection
- MySQL - Create Database
- MySQL - Drop Database
- MySQL - Select Database
- MySQL - Data Types
- MySQL - Create Tables
- MySQL - Drop Tables
- MySQL - Insert Query
- MySQL - Select Query
- MySQL - Where Clause
- MySQL - Update Query
- MySQL - Delete Query
- MySQL - Like Clause
- MySQL - Sorting Results
- MySQL - Using Join
- MySQL - NULL Values
- MySQL - Regexps
- MySQL - Transactions
- MySQL - Alter Command
- MySQL - Indexes
- MySQL - Temporary Tables
- MySQL - Clone Tables
- MySQL - Database Info
- MySQL - Using Sequences
- MySQL - Handling Duplicates
- MySQL - SQL Injection
- MySQL - Database Export
- MySQL - Database Import
Select last record and update it in MySQL?
For this, you can use ORDER BY DESC LIMIT. Let us first create a table −
mysql> create table DemoTable -> ( -> Id int NOT NULL AUTO_INCREMENT PRIMARY KEY, -> Name varchar(100) -> ); Query OK, 0 rows affected (0.59 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable(Name) values('John'); Query OK, 1 row affected (0.12 sec) mysql> insert into DemoTable(Name) values('Sam'); Query OK, 1 row affected (0.19 sec) mysql> insert into DemoTable(Name) values('Carol'); Query OK, 1 row affected (0.34 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable;
Output
+----+-------+ | Id | Name | +----+-------+ | 1 | John | | 2 | Sam | | 3 | Carol | +----+-------+ 3 rows in set (0.00 sec)
Following is the query to select last record and update it −
mysql> update DemoTable -> set Name='Robert' -> order by Id DESC limit 1; Query OK, 1 row affected (0.18 sec) Rows matched: 1 Changed: 1 Warnings: 0
Let us check the table records once again −
mysql> select *from DemoTable;
This will produce the following output displaying we have successfully updated the last record −
Output
+----+--------+ | Id | Name | +----+--------+ | 1 | John | | 2 | Sam | | 3 | Robert | +----+--------+ 3 rows in set (0.00 sec)
- Related Articles
- How to select first and last row record using LIMIT in MySQL?
- How to select record from last 6 months in a news table using MySQL?
- Insert record using MySQL SELECT?
- MySQL select * and find record with current date
- MySQL SELECT last few days?
- How to select last row in MySQL?
- Select text after last slash in MySQL?
- How to get the first and last record of the table in MySQL?
- Remove and update the existing record in MongoDB?
- How to select record except the lower value record against a specific value in MySQL?
- Select last day of current year in MySQL?
- How to select last two rows in MySQL?
- SELECT last entry without using LIMIT in MySQL?
- Update record on a specific date matching the current date in MySQL
- How to delete last record (on condition) from a table in MySQL?

Advertisements