# Problems with "Top N" SQL query

**URL:** <https://discuss.elastic.co/t/problems-with-top-n-sql-query/199146>\
**Category:** Elasticsearch\
**Tags:** elastic-stack-sql\
**Created:** [September 11, 2019, 9:03pm UTC](https://discuss.elastic.co/t/problems-with-top-n-sql-query/199146 "2019-09-11T21:03:51Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![Brian\_Frantz](https://sea2.discourse-cdn.com/elastic/user_avatar/discuss.elastic.co/brian_frantz/32/15787_2.png) [@Brian\_Frantz](https://discuss.elastic.co/u/Brian_Frantz)\
**Post date:** [September 11, 2019, 9:03pm UTC](https://discuss.elastic.co/t/problems-with-top-n-sql-query/199146/1 "2019-09-11T21:03:51Z")

</div>

I'm using Elasticsearch 6.7.1. From what I can tell in the [documentation](https://www.elastic.co/guide/en/elasticsearch/reference/6.7/sql-limitations.html#_sorting_by_aggregation), what I want to do should be possible, but it's not working for me:

Here's my query:  
`SELECT location.country, COUNT(*) AS count FROM my_index GROUP BY location.country ORDER BY count DESC LIMIT 10`

This returns:  
|location.country |count |  
|Australia|2256|  
|Argentina|639|  
|Albania|46|  
|Angola|14|  
|Aruba|5|  
...

However the top results should be as follows (same query as above but without the LIMIT):  
|location.country |count |  
|United States|60105|  
|China|43388|  
|Mexico|25472|  
|India|10117|  
|United Kingdom|8681|  
...

In other words, it appears to be applying the limit before the sort. What am I doing wrong?

---

<div class="post-metadata">

**Author:** ![Andrei\_Stefan](https://sea2.discourse-cdn.com/elastic/user_avatar/discuss.elastic.co/andrei_stefan/32/47533_2.png) [@Andrei\_Stefan](https://discuss.elastic.co/u/Andrei_Stefan)\
**Post date:** [September 12, 2019, 6:39am UTC](https://discuss.elastic.co/t/problems-with-top-n-sql-query/199146/2 "2019-09-12T06:39:58Z")

</div>

@Brian_Frantz this is a [bug](https://github.com/elastic/elasticsearch/issues/42851) which has been fixed already and is (should) be available in the versions set as labels in [this PR](https://github.com/elastic/elasticsearch/pull/43154).

---

<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:** [October 10, 2019, 6:40am UTC](https://discuss.elastic.co/t/problems-with-top-n-sql-query/199146/3 "2019-10-10T06:40:04Z")

</div>

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