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
- 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.
- 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.

