I am currently wondering what is the fastest way of using Select By Attributes in arcpy. I have a GDB with a feature class that is quite big. This feature class has a field called CODE with values of type LONG.

I want to select 3 types of these features, namely the ones that have either 5020, 5601 or 8002 in the CODE field.

I tried running the following code:

SelectByAttribute=' "CODE" = ' 5020 ' OR "CODE" = ' 5601 ' OR "CODE" = ' 8002
arcpy.SelectLayerByAttribute_management("Bat_StudyArea", "NEW_Selection", SelectByAttribute)

I am getting a syntax error, but I am too blind to find the error.

  • 2
    Your SelectByAttribute string is not properly build. Try using this one: 'CODE = 5020 OR CODE = 5601 OR CODE = 8002'. Your values are numeric so you don't need to wrap quotes around them. – Marcelo Villa May 31 at 15:29
  • 4
    For a pick list, use CODE in (5020, 5601, 8002) – Vince May 31 at 15:35
  • 2
    If this is a database you use often, you may want to add an attribute/secondary index for the DB on the Code field. That will cost a small amount of disk space but should in theory speed up selects in ArcMap or ArcPy. And I echo what Vince said: it is a lot easier to read and avoid typos when you use IN for selects. – danak May 31 at 15:38
  • Ok thanks for your input! Did not thought it was that easy! – Cliff May 31 at 16:24

Use IN in your SQL query, and don't include single quotes for numeric field values.

CODE in (5020, 5601, 8002)


Check your quotation marks, also look at the ESRI SQL reference page

Try this:
SelectByAttribute = """CODE = '5020' OR CODE = '5601' OR CODE = '8002'""" arcpy.SelectLayerByAttribute_management("Bat_StudyArea", "NEW_Selection", SelectByAttribute)

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.