# Conditional Sort Using Two Fields

**URL:** <https://discuss.elastic.co/t/conditional-sort-using-two-fields/287352>\
**Category:** Elasticsearch\
**Created:** [October 21, 2021, 6:40pm UTC](https://discuss.elastic.co/t/conditional-sort-using-two-fields/287352 "2021-10-21T18:40:11Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![cruzmoan](https://sea2.discourse-cdn.com/elastic/user_avatar/discuss.elastic.co/cruzmoan/32/80330_2.png) [@cruzmoan](https://discuss.elastic.co/u/cruzmoan)\
**Post date:** [October 21, 2021, 6:40pm UTC](https://discuss.elastic.co/t/conditional-sort-using-two-fields/287352/1 "2021-10-21T18:40:11Z")

</div>

We have a document that has the following fields:

field1  
field2  
valueType

We want to include both fields in the sort. We do NOT want to sort field1, then field2. We want the sort to use both fields at the same sort level based on the value in another field. If I were to write this in SQL I would write it like this:

```auto
select *
from 
(
-- create some dummy data
select 8 as value1, 1 as value2, 'val1' as valueType, 1 as sortValue union all
select 6 as value1, 3 as value2, 'val2' as valueType, 4 as sortValue union all
select 4 as value1, 5 as value2, 'val1' as valueType, 3 as sortValue union all
select 2 as value1, 7 as value2 , 'val2' as valueType, 2 as sortValue
) t
order by case valueType when 'val1' then value2 else value1 end -- use a case to handle the sort based on valueType field

```

Is there a way to do a similar case statement in the sort clause of an Elasticsearch query?

---

<div class="post-metadata">

**Author:** ![system](https://us1.discourse-cdn.com/elastic/original/3X/1/a/1ac57faf039f6b580b3f104ef42a2a89e41014de.png) [@system](https://discuss.elastic.co/u/system)\
**Post date:** [November 18, 2021, 6:40pm UTC](https://discuss.elastic.co/t/conditional-sort-using-two-fields/287352/2 "2021-11-18T18:40:20Z")

</div>

This topic was automatically closed 28 days after the last reply. New replies are no longer allowed.
