Question

How would I get sql to order the same column differently depending on conditions? Like in the example below, if n/s is n, then order by distfromc desc, if not then order by distfromc asc, so to appear like the table below.

name  n/s  distfromc
BH    n    2
FV    n    1
C     c    0
RS    s    1
MTN   s    2
Was it helpful?

Solution

SELECT tablename.*
FROM tablename
ORDER BY
  `n/s` = 'n' DESC,
  CASE WHEN `n/s` = 'n' THEN distfromc END DESC,
  CASE WHEN `n/s` != 'n' THEN distfromc END ASC

Please see fiddle here.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top