wobsoriano
wobsoriano

Reputation: 13434

Select highest value from a column SQL

I'm trying to get the highest value in a column. For now this is my code..

SELECT MAX(ID) FROM tablename

This code works, but what if I want to echo all the data in the column and add 1 to the highest ID? For example the highest ID is 10, and the value of the column is 5, so 5+1?. Looks like this:

foreach ($result as $r) {
   echo $r['someColumn'];
}

5 + 1
4
3
2
1

Thank you. I am using PHP btw. Is that possible?

Upvotes: 1

Views: 68

Answers (1)

Anonymous
Anonymous

Reputation: 12090

You can do something like this:

SELECT
    CASE WHEN val = (SELECT MAX(val) FROM my_table) THEN
        val + 1
    ELSE
        val
    END AS val
FROM my_table

It does a single query to find the maximum value like you did, and then compares each value to it. When it finds the maximum, one is added. Note that if there is more than one value tied for max, they will all get the one added.

Upvotes: 1

Related Questions