- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
MySQL query to select distinct order by id
For this, use ORDER BY MAX(). Let us first create a table −
mysql> create table DemoTable -> ( -> Id int, -> Name varchar(100) -> ); Query OK, 0 rows affected (0.81 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable values(10,'John'); Query OK, 1 row affected (0.51 sec) mysql> insert into DemoTable values(10,'John'); Query OK, 1 row affected (0.10 sec) mysql> insert into DemoTable values(20,'Sam'); Query OK, 1 row affected (0.17 sec) mysql> insert into DemoTable values(20,'Sam'); Query OK, 1 row affected (0.11 sec) mysql> insert into DemoTable values(30,'David'); Query OK, 1 row affected (0.13 sec) mysql> insert into DemoTable values(30,'David'); Query OK, 1 row affected (0.11 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable;
Output
This will produce the following output −
+------+-------+ | Id | Name | +------+-------+ | 10 | John | | 10 | John | | 20 | Sam | | 20 | Sam | | 30 | David | | 30 | David | +------+-------+ 6 rows in set (0.00 sec)
Following is the query to select distinct order by id −
mysql> select Name from DemoTable -> group by Name -> order by max(Id) DESC -> limit 2;
Output
This will produce the following output −
+-------+ | Name | +-------+ | David | | Sam | +-------+ 2 rows in set (0.06 sec)
- Related Articles
- MySQL query to group concat distinct by Id?
- MySQL select * with distinct id?
- MySQL query to select records beginning from a specific id
- MySQL query to select average from distinct column of table?
- MySQL - SELECT … WHERE id IN (..) order with particular column?
- How can you order the result obtained by select query in MySQL?
- SELECT DISTINCT vs GROUP BY in MySQL?
- Select last 3 rows from database order by id ASC?
- How to order and select query with conditions in MySQL?
- MySQL query to order by NULL values
- MongoDB query to select distinct and count?
- How to order last 5 records by ID in MySQL
- Order MySQL query by multiple ids?
- MySQL query to select rows except first row in descending order?
- MySQL query to order by current day and month?

Advertisements