31

I have the following table:

key | date         | flag
--------------------------
1    now()           true
2    now() - 1 hour  true
3    now() + 1 hour  true
4    now()           false
5    now() - 1 hour  false
6    now() + 1 hour  false

I want the following sorting:

  • First, all rows with flag = false. These rows must be sorted with date asc.
  • Then, all other rows (flag = true). However, these rows must be sorted with date desc.

Is the following query correct?

(
    select *
    from test
    where flag = false
    order by date asc
)
union all
(
    select *
    from test
    where flag = true
    order by date desc
)

Is there a better way to do this? Will the union all keep the rows sorted, and therefore just concatenate the output of the two inner queries?

I don't know how to repeat the columns in the order by, based on a condition.

update

Fiddle can be found here: http://rextester.com/FFOSS79584

2
  • 1
    conditional ordering is done with CASE Commented Apr 10, 2017 at 11:37
  • 1
    smth like order by flag,case when flag then date end desc, case when not flag then date end asc rextester.com/FDAY76293 Commented Apr 10, 2017 at 11:40

1 Answer 1

57

conditional order can be performed with CASE, like here:

select *
    from test
order by 
    flag
  , case when flag then date end desc
  , case when not flag then date end asc
Sign up to request clarification or add additional context in comments.

1 Comment

But won't this always order by flag? In my case, I'd like to either make all cases optional or have a default sort field. The cases should be exclusive

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.