简体   繁体   中英

Does Big Query support custom sorting?

I am trying to sort data by applying case when statement in the order by clause but looks like Big Query doesn't support even though it worked fine in other SQL environments. Can somebody share your thoughts on this.

select x 
from (
  select x ,
  case when x = 'a' then 'z' else x end as y
  from 
    (select 'a' as x),
    (select 'b' as x),
    (select 'c' as x),
    (select 'd' as x)
  )
order by y desc

I think the documentation is pretty clear:

ORDER BY clause

... ORDER BY field1|alias1 [DESC|ASC], field2|alias2 [DESC|ASC] ...

The ORDER BY clause sorts the results of a query in ascending or descending order of one or more fields. Use DESC (descending) or ASC (ascending) to specify the sort direction. ASC is the default.

You can sort by field names or by aliases from the SELECT clause. To sort by multiple fields or aliases, enter them as a comma-separated list. The results are sorted on the fields in the order in which they are listed.

So, BigQuery doesn't allow expressions in the ORDER BY . However, you can include the expression in the SELECT and then refer to it by the alias. So, BigQuery does support "custom sorting", but only by expressions in the SELECT .

Interestingly, Hive has a similar limitation.

Update (2021) - Bigquery now does support ORDER BY with expressions, eg


    SELECT event_type, COUNT(*) as event_count
    FROM events
    GROUP BY event
    ORDER BY (
        CASE WHEN event='generated' THEN 1
             WHEN event='sent' THEN 2
             WHEN event='paid' THEN 3
             ELSE 4
        END
    )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM