Combine sorted queries

For example, I have devices and owners. Not all devices belong to the owners

uuid: string @index(hash) .
name: string @index(exact, trigram) .
number: string @index(exact, trigram) .
owner: uid @reverse .

type Owner {
    uuid: string
    name: string
    <~owner>
}

type Device {
    uuid: string
    number: string
    owner: Owner
}

And I want to sort devices by owner’s name, but in result, I want to get all devices.
So I sort devices

var(func: type(Device)) {
     owner {
       ownerName as name
     }
     x as min(val(ownerName))
}

withOwner(func: type(Device)), orderasc: val(x), orderasc: number) {
    uuid
    number
    owner {
      uuid
      name
    }
}

Result contains only devices with owners.

But how can I get all devices?

I can get only devices without owners

withoutOwner as var(func: type(Device), orderasc: number) @filter(not has(owner))

Is it possible to combine sorted withOwner and withoutOwner in one result?

Can devices have multiple owners?

Also looks like this has been asked earlier as well without a solution. Going back to the issue here, I think we require all the values to be present on which you want to sort otherwise they get filtered out.

No, there can only be one owner

I would suggest appending the query answers inside the app-logic. Or you can try something like this:

{
  devices as var(func: type(Device)) {
     owner {
       ownerName as name
     }
     x as min(val(ownerName))
  }

  withOwner as var(func: uid(devices), orderasc: val(x)){
    uuid
    owner{
      uuid
      name
    }
  }

  withoutOwner as var(func: type(Device)) @filter(not has(owner) )
    
  allDevices(func: uid(withoutOwner, withOwner)) {
      uuid
      owner{
        uuid
        name
      }
    }
}

@MichelDiz do you have a better solution?

Unfortunately, in case of allDevices sorting is broken

Yes, I realized. That is because the uids in the variables are sorted as per their order (ascending order with respect to each uid) and not by the order we specify.

I thought to add a dummy owner to which devices without an owner belonged, but this solution is really ugly.
I also can’t append the query answers inside the app-logic because of a large number of devices and pagination.
Maybe there are some other solutions?

I see @poketulhu. Let me get back in sometime if I can find a better solution for you.

Ok, thank you for your help

Hey @poketulhu
Added some notes on sort queries here. For your specific case, we do not yet support adding nodes that point to nodes on which you want to sort.

Thanks
Anurag