Monday, 22 May 2023

Custom sort function in BigQuery

Is there a way to pass a comparison function to sort by a column in BigQuery? I am fine, if required, using a SQL or JS udf. This would be similar to something like Javascript's localeCompare function, returning a -number, 0, or +number depending on if the first value is less than or equal to the second value.

This would allow doing something like:

const comparisonFunction = (val1, val2) => ...
MyValues.sort(comparisonFunction)

For example, if I have the following data:

with tbl as (
  select "date" val union all 
  select "time" union all 
  select "number"
)
select * from tbl order by comparisonFunction(tbl.val)

And for arguments sake, let's say the comparison function is something like:

const RANK_MAP = {"number": 1, "time": 2, "date": 3}
function comparisonFunction(val1, val2) {
    return RANK_MAP[val1] - RANK_MAP[val2];
}

Note that I want this signature (or something like it). I'm not looking for 'converting this into an inline sql function' with something like:

with tbl as (
  select "date" val union all 
  select "time" union all 
  select "number"
)
select
  tbl.val,
  case tbl.val
    when 'number' then 1
    when 'time' then 2
    when 'date' then 3
  end rank
from tbl
order by rank

How could this be done with a udf function similar to the js approach above?



from Custom sort function in BigQuery

No comments:

Post a Comment