I am trying to determine options to set a layer definition query using ArcPy.

I know that it is possible when using arcpy.mapping.ListLayers().

However, in this scenario I am loading in shapefiles, and using arcpy.MakeFeatureLayer_management() in ArcPy.

How do I set a definition query on the layer that I create from using this geoprocessor?

I am using ArcMap 10.2.


3 Answers 3


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

lyr = arcpy.mapping.Layer("test_lyr")
lyr.name = "test"
lyr.definitionQuery = '"testField" = ' + "'A'"

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"

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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