How to extract top 5 records in search cursor, not in SQL server

477
4
Jump to solution
11-16-2022 05:45 PM
Aнастасия88
Occasional Contributor

Hello, I am seeking a way to extract top 5 records from a sorted search cursor. According to ESRI, we can use top for sql clause but it is only supported by SQL server. I tried range function (please see below) but it did not work unfortunately.

Thank you in advance for any coding advice!

with arcpy.da.SearchCursor(data, fieldName, sql_clause=(None,'ORDER BY IDA DESC')) as cursor:
    for i in range(5):                 
        for row in cursor:
            print("IDA value: ", row[1])
Tags (2)
0 Kudos
1 Solution

Accepted Solutions
DanPatterson
MVP Esteemed Contributor
# assuming numeric data
# fc = your featureclass
# field = your field
a = [row[0] for row in arcpy.da.SearchCursor(fc, field)]
# assume:  a = [9, 5, 3, 2, 10, 22]

sorted(a, reverse=True)[:5]
[22, 10, 9, 5, 3]

... sort of retired...

View solution in original post

4 Replies
DanPatterson
MVP Esteemed Contributor
# assuming numeric data
# fc = your featureclass
# field = your field
a = [row[0] for row in arcpy.da.SearchCursor(fc, field)]
# assume:  a = [9, 5, 3, 2, 10, 22]

sorted(a, reverse=True)[:5]
[22, 10, 9, 5, 3]

... sort of retired...
Aнастасия88
Occasional Contributor

Thanks DanPatterson for the solution!

It works well🙂

0 Kudos
JoshuaBixby
MVP Esteemed Contributor

You were close with your original code, just a couple issues:

with arcpy.da.SearchCursor(data, fieldName, sql_clause=(None,'ORDER BY IDA DESC')) as cursor:
    for i in range(5):                 
        print("IDA value: ", next(cursor)[0])

 

Aнастасия88
Occasional Contributor

Hi @JoshuaBixby ,

I apology for late reply for your solution - I have realized your message just now. 

Kudos for your solution as well🙂

0 Kudos