Search code examples
sqlmysqlgroup-byaggregate-functions

MySQL - Is it possible to achieve this using SQL?


Imagine you've got a table with 2 columns: ID and NAME. ID is simply a number, incrementing for each row (as you'd expect). NAME is some random varchar string. NAME can be same for different rows. Now, imagine you want to get the 3 latest occurences in this table, where NAME only may occur once.

For example, if you've got this data:

ID  NAME
1   HELLO
2   TEST
3   HELLO
4   HELLO
5   QWERTY
6   HELLO

Then the result of the question should be:

6   HELLO
5   QWERTY
2   TEST

Is it possible achieve this on SQL level?


Solution

  • SELECT 
       MAX(ID), 
       Name
    FROM 
       table
    GROUP BY 
       Name
    ORDER BY
       MAX(ID) desc
    LIMIT 3