Search code examples
mysqllimitmax

How can I use MAX and LIMIT together in MySQL


I have a table with the following structure:

ID | Color

1 | red
2 | blue
3 | yellow
8 | purple
10| green
.
.
.
100|yellow

I would like to be able to grab the MAX ID value for the first 5 rows.

For example, I would like to do something like so: Select MAX(ID) From Table LIMIT 5

Hoping this would return the value 10

But, MySQL keeps returning 100...its like MySQL does not even see the LIMIT clause.


Solution

  • It sounds like you want to select the top 5 records (ordered by ID) and then get the highest value of that group? If so:

    SELECT
        MAX(ID)
    FROM
        ( 
             SELECT ID 
             FROM YourTable
             ORDER BY ID
             LIMIT 5
        ) as T1