create or replace function random_available_on_location(loc integer)
  returns integer
language sql as
$$
  with valid as
  (
    select
        batch
      from
        itemsonshelf
      where
        itemsonshelf.location = $1 and itemsonshelf.quantity > 0
      order by
        random()
      limit 1
  )
  select
    "batches".sku as sku
  from
    valid
  join
    "batches"
  on
    "batches".id = valid.batch
  limit
    1;
$$;
