Looking for proper syntax for SQL expression in Python to select features by attribute

2509
3
04-19-2017 09:36 AM
deleted-user-AOHsGDn8SRw7
New Contributor

I am trying to create a simple code that will select features in a shapefile based on the query {anything within the ATTRIBUTE field that starts with the letter 'P'}. Here the problematic line:

arcpy.SelectLayerByAttribute_management("NJ_Wetlands", "NEW_SELECTION", """"ATTRIBUTE" LIKE P%""")

I know I could do this simply in the toolbox GUI, but I'm trying to learn arcpy. I'm obviously doing something wrong, and it shouldn't be very complicated. I get the error: 

Runtime error Traceback (most recent call last): File "<string>", line 1, in <module> File "c:\program files (x86)\arcgis\desktop10.5\arcpy\arcpy\management.py", line 7713, in SelectLayerByAttribute raise e ExecuteError: ERROR 000358: Invalid expression Failed to execute (SelectLayerByAttribute).

I've already tried searching through various forums and some help guides on Esri.com, but no dice. I guess I need this help to be explained very explicitly, otherwise I am lost.

0 Kudos
3 Replies
JoshuaBixby
MVP Esteemed Contributor

How about:

arcpy.SelectLayerByAttribute_management("NJ_Wetlands", "NEW_SELECTION", "ATTRIBUTE LIKE 'P%'")

Since you are wanting to learn Python, I encourage you to read String literals section of the Lexical analysis Python documentation.

deleted-user-AOHsGDn8SRw7
New Contributor

Thank you, it worked like a charm!

0 Kudos
JoshuaBixby
MVP Esteemed Contributor

Please mark an answer correct to close out the question, thanks.

0 Kudos