Search code examples
mysqlmariadbsql-order-bysql-limitsql-max

Select multiple max values in mysql


Lets say i have two columns with diffrent values like this:

id  |val
1   |  9
7   |  6
7   |  8

I want to return the max id, and then find the max value according to the id. The row I return would be id: 7 and val: 8.

How would I write this in Mysql? I am aware of MAX() but I cant find any solution to use this with multiple columns.


Solution

  • Sort the table by id descending and then by val descending and pick the top row with LIMIT 1:

    SELECT *
    FROM tablename
    ORDER BY id DESC, val DESC
    LIMIT 1