1

I have a layer called 'Colorado' that has an attribute 'FIPS_CODE'. The values are numbers as a string. I am trying to use arcpy.SelectLayerByAttribute_management inside my Python script to select the features that have code '13245', but I keep getting an error:

Invalid expression Failed to execute

The problem is essentially the where_clause or SQL Expression. What am I doing wrong here?

arcpy.SelectLayerByAttribute_management('Colorado','NEW_SELECTION','"FIPS_CODE" = "13245"')

  • 5
    Possible duplicate of Invalid Expression ERROR 000358: Select by Attribute – ycartwhelen Aug 23 '18 at 17:59
  • 2
    Is FIPS_CODE numeric or text? The double-quotes are incorrect either way, but should be single-quotes if text, and not present if numeric. – Vince Aug 23 '18 at 17:59
  • It's a string, so text even though it is a number. Ex: '13245', '13015', etc... – gwydion93 Aug 23 '18 at 18:04
3

Use AddFieldDelimiters:

The field delimiters used in an SQL expression differ depending on the format of the queried data. For instance, file geodatabases and shapefiles use double quotation marks (" "), personal geodatabases use square brackets ([ ]), and enterprise geodatabases don't use field delimiters. The function can take away the guess work in ensuring that the field delimiters used with your SQL expression are the correct ones.

and three double quotes:

sql = """{0} = '13245'""".format(arcpy.AddFieldDelimiters('Colorado','FIPS_CODE'))
arcpy.SelectLayerByAttribute_management(in_layer_or_view='Colorado', where_clause=sql)

'Colorado' needs to be a layer, for example created with MakeFeatureLayer.

  • I think I found the problem. The syntax was just a little off. Here is the correct application: arcpy.SelectLayerByAttribute_management("Georgia", "NEW_SELECTION", "FIPS_CODE = '13245'") – gwydion93 Aug 23 '18 at 18:05
  • @gwydion93 nice!. But if you use addfielddelimiters you will never have this problem. Some other time the field name will have to be enclosed in quotation marks. – BERA Aug 23 '18 at 18:06
  • Hypothetically, in Python3.6, say I had a variable id = '13245' and I wanted to insert that variable into my code. How would I do that? arcpy.SelectLayerByAttribute_management("Georgia", "NEW_SELECTION", "FIPS_CODE = " + id)? – gwydion93 Aug 23 '18 at 18:10
  • (id is a function so dont name it id). Use format: """FIPS_CODE = '{0}'""".format(idnumber) – BERA Aug 23 '18 at 18:15

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.