Amar Kumar
Amar Kumar

Reputation: 97

Conditional Order By in sql

I have a sample data, which I want to sort. If User is 1,then sort views in descending, otherwise if User is not 1,then sort normally. I have written below sql,and I am getting required result. My Question is Why and How it works?

with data as (
    select 2 as User,   1 as Views UNION ALL
    select 1,3 UNION ALL 
    select 4,1 UNION ALL
    select 1,5 UNION ALL
    select 1,6 UNION ALL
    select 2,6 UNION ALL
    select 7,2 UNION ALL
    select 8,3 UNION ALL
    select 3,9
    
    )
    select ARRAY_AGG(struct(User,Views) order by if(User=1,1,0) desc   ,Views desc  ) 
    from data
  1. I am confused with if(User=1,1,0), if User=1,then 1.Is this 1,the column number? If its column number,then ,when User is not equal to 1,then the value will be 0 ,which is not any column.
  2. I was researching on this,and found that,if I write, if(User=1,100,0) desc ,Views desc ,then also I am getting correct result ,mean numbers in that IF() are not columns, otherwise 100 will produce error ,becoz there is no 100th column.

Can Anyone explain me,how its working? Image 1 Image 2

Upvotes: 2

Views: 902

Answers (1)

Mikhail Berlyant
Mikhail Berlyant

Reputation: 172993

Can Anyone explain me,how its working?

I think below is the simplest way to explain/show what is happening here

Consider below slightly modified/simplified example - I eliminated aggregation to focus on ordering aspect only

with data as (
  select 2 as user, 1 as views union all
  select 1,3 union all 
  select 4,1 union all
  select 1,5 union all
  select 1,6 union all
  select 2,6 union all
  select 7,2 union all
  select 8,3 union all
  select 3,9
)
select *, if(user=1,1,0) sort 
from data
order by sort desc, views desc       

output of above is

enter image description here

I don't think you have any doubts why above result is as is - it is just straightforward!!

Now - if you use if(user=1,100,0) - you get

enter image description here

Obviously, exactly same output (in terms of ordering) and I still don't think you have any doubts why it is as it is

So, finally to streamline query - users (or at least power users) would use the shortcut - instead of introducing sort column to use in order by - they would move this into order by itself

Hope this is clear now for you!

Upvotes: 1

Related Questions