SQL: Combine multiple columns into one for sorting (output only)

You may want to use the GREATEST() function:

With two or more arguments, returns the largest (maximum-valued) argument.

This code snippet does what you wanted for score2 and score3 columns in your example:

SELECT name, GREATEST( score2, score3 ) AS max_score, rating
FROM db
ORDER BY max_score DESC , rating DESC

Orders by combined scores, and if they are equal then orders by result (both highest to lowest).

For more columns, simply add them as arguments to GREATEST() function.

Tags:

Mysql

Sql

Sorting