ArcPy – Creating Queries to Select by Attribute with ArcPy

arcgis-proarcpyselect-by-attributewhere-clause

I'm quite new with arcpy and I'm finding selecting by attribute a bit of a nightmare. There's a problem with my query on the script below [query = "\'Location\' = observer"], but I can't tell what it is. 'Location' is a field of the feature class I'm dealing with (fc_copy).

with arcpy.da.UpdateCursor(fc_copy,field_names) as cursor:   
    for row in cursor:
        observer = row[0]
        arcpy.MakeFeatureLayer_management(fc_copy, 'fl_copy_OBS')
        arcpy.MakeFeatureLayer_management(fc_copy, 'fl_copy_TAR')
        query = "\'Location\' = observer"
        arcpy.SelectLayerByAttribute_management('fl_copy_OBS', 'NEW_SELECTION', query)
        arcpy.SelectLayerByAttribute_management('fl_copy_TAR', 'NEW_SELECTION', query, invert_where_clause = 'INVERT')

This is the error I get => Invalid expression
Failed to execute (SelectLayerByAttribute).

Is there any documentation to learn the rules to follow to build queries for arcpy?

Best Answer

The expression format depends on the data type and value being queried:

Shapefile querying text field:

query = "\"Location\" = '{}'".format(observer)

Geodatabase feature class querying text field:

query = "Location = '{}'".format(observer)
Related Question