Nick Goloborodko
Nick Goloborodko

Reputation: 3053

SQL OrderBy two columns as one

I have a table that has two columns: Height and Width

What is the easiest way to sort this table incrementally based on either Height or Width

In other words, it would pick the smallest value from Height and Width for each row and sort it based on this number?

Thanks in advance!

Upvotes: 0

Views: 47

Answers (2)

Doug Knudsen
Doug Knudsen

Reputation: 954

If you want to only sort on whichever column value is smallest and ignore the other column:

SELECT
    *
FROM
    SomeTable
ORDER BY
    CASE
        WHEN Height < Width THEN Height
        ELSE Width
    END

Upvotes: 1

Aducci
Aducci

Reputation: 26634

You can use a case statement in your order by clause like this:

select *
from table
order by 
   case when Width > Height then Height else Width end,
   case when Width > Height then Width else Height end

Upvotes: 5

Related Questions