Setting Definition Query on ArcPy layer from shapefile for ArcMap

The code below will create, from a shapefile, a layer file called test_A.lyr which has a Definition Query of "testField" = 'A' saved into it.

import arcpy

arcpy.MakeFeatureLayer_management(r"C:\temp\testLines.shp","test_lyr")
lyr = arcpy.mapping.Layer("test_lyr")
lyr.name = "test"
lyr.definitionQuery = '"testField" = ' + "'A'"
lyr.saveACopy(r"C:\temp\test_A.lyr")

del lyr

If required, you could also add this layer file,or the Layer object (lyr) from prior to it being saved as a layer file, into your map via arcpy.mapping.AddLayer.

To see whether a where_clause on MakeFeatureLayer gets passed through as a Definition Query, which I think is undocumented behaviour, I performed a second test below to verify the Answer of @John, and he is quite correct.

arcpy.MakeFeatureLayer_management(r"C:\temp\testLines.shp","test_lyr2",'"testField" = ' + "'A'")
lyr2 = arcpy.mapping.Layer("test_lyr2")
lyr2.name = "test2"
lyr2.saveACopy(r"C:\temp\test_2.lyr")

del lyr2

Yes, it should definitely be possible for you as that is what the optional "where_clause" parameter is for - see its documentation for details and examples, but basically you just need to include the definition query as the where_clause param and it should work. Only thing to note, if you are using a layer that doesn't have an ObjectID/FID field, ArcGIS has issues running SQL expressions against it, but any regular ArcGIS layer will.


If you are loading layers into Arcmap using the MakeFeatureLayer geoprocessing tool, you can set the definitionQuery on existing arcmap layers using the arcpy.mapping class layers - definitionQuery.