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"')

3
  • 5
    Possible duplicate of Invalid Expression ERROR 000358: Select by Attribute Commented Aug 23, 2018 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. Commented Aug 23, 2018 at 17:59
  • It's a string, so text even though it is a number. Ex: '13245', '13015', etc... Commented Aug 23, 2018 at 18:04

1 Answer 1

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.

4
  • 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'") Commented Aug 23, 2018 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. Commented Aug 23, 2018 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)? Commented Aug 23, 2018 at 18:10
  • (id is a function so dont name it id). Use format: """FIPS_CODE = '{0}'""".format(idnumber) Commented Aug 23, 2018 at 18:15

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.