Select to view content in your preferred language

DA Search Cursor Ignoring sql_clause

45
2
5 hours ago
Labels (2)
RandyMcGregor_BMcD
Frequent Contributor

A search curser was ignoring the ORDER BY command I had plugged in and I thought I'd enter a nonsense sql_clause just to see what error it threw. The uncommented one below is the cursor command with the nonsense sql_clause

RandyMcGregor_BMcD_0-1785945996964.png

It ... runs fine. It doesn't do the ordering I want it to do, of course, but it runs. No error. When I run the line with the ORDER BY clause it completely ignores the order also. The 'order_field' is a field that exists. I've tried hard- coding the field name in the clause. It just won't work.

Throwing this out in the off chance that the problem here is obvious to someone. I suspect I may have to do lots and lots of troubleshooting/error trapping. Something is off here.

Thank you,

Randy McGregor

0 Kudos
2 Replies
D_Atkins
Frequent Contributor

Your commented out code is missing a comma (after the fields list) , and it also uses parentheses instead of the list-bracket notation for the SQL clause.  Here is a minimum working example, tested both with and without the where_clause:

import arcpy

# URL must point to the specific sublayer index (e.g., /0, /1)
url = "https://sampleserver6.arcgisonline.com/arcgis/rest/services/Wildfire/FeatureServer/2"
layer_name = "Wildfire Polygons"

# Create the feature layer
featureLayer = arcpy.management.MakeFeatureLayer(url, layer_name)

count = 0
print("UNORDERED")
with arcpy.da.SearchCursor(featureLayer, ['objectid', 'symbolID', 'Shape__Area'], where_clause = "symbolID IN (0, 1)") as sCursor:
    for row in sCursor:
        if count < 10:
            # rounded fire boundary area:
            print(  str(round(row[2]) ).rjust(20) )
            count += 1

print("ORDERED:")
count = 0
with arcpy.da.SearchCursor(featureLayer, ['objectid', 'symbolID', 'Shape__Area'], where_clause = "symbolID IN (0, 1)", sql_clause=[None, 'ORDER BY Shape__Area DESC']) as sCursor:
    for row in sCursor:
        if count < 10:
            # rounded fire boundary area:
            print(  str(round(row[2]) ).rjust(20) )
            count += 1



** EDIT: Just for fun, I traded out the brackets for parentheses, and it still ran!

0 Kudos
RandyMcGregor_BMcD
Frequent Contributor

Thank you for that catch. Yes, I noticed that and corrected, but the problem remained. It turns out, The input layer was a route event layer, not a gdb feature class. The sql_query doesn't work on those, apparently. I exported it as a feature class. It's all good now. Working as it's supposed to. 

0 Kudos