How to find a query layer in a map document using arcpy

06-11-2021 02:03 PM
New Contributor III

I have a bunch of map documents with gobs of layers in each. I have a script the goes through each map document, and each dataframe, and then inspects each layer in the dataframe. I am trying to determine if the layer is a query layer, but I do not know how to determine that.

import arcpy
import os

tfolder = r"\\tstvmmapservb\f$\ArcGIS\MXDs\NISC"
for f in os.listdir(tfolder):
    map_document = os.path.join(r"\\tstvmmapservb\f$\ArcGIS\MXDs\NISC", f)
    print("mxd: {}").format(map_document)
    mxd = arcpy.mapping.MapDocument(map_document)
    for df in arcpy.mapping.ListDataFrames(mxd, "*"):
        lyrs = arcpy.mapping.ListLayers(mxd, "", df)
        for lyr in lyrs:
            if lyr.isBroken:
                #print("{} is broken. Skipping".format(
            desc = arcpy.Describe(lyr)
            if desc.dataType == "GroupLayer":
                #print("{} is a group layer. Skipping".format(
            if desc.dataElement.dataType == "FeatureClass":
                print("{} is a feature class. Skipping".format(
            if lyr.supports("SERVICEPROPERTIES"):
                #print("{} is a service. Skipping".format(


0 Kudos
6 Replies
MVP Esteemed Contributor

would "supports" "definition query" help?

Layer—ArcGIS Pro | Documentation

supports (layer_property)

DEFINITIONQUERY A layer's definition query string.


... sort of retired...
New Contributor III

Not really; most layers have definition queries. It is similar, but I am looking for a query layer's definition, and not a layer's definition query. 

0 Kudos
MVP Frequent Contributor

A query layer for me in Oracle returns a '%' in the dataSource and datasetName properties.


if '%' in lyr.datasetName:
0 Kudos
New Contributor III

Thanks; I am not getting a "%" and might be getting an underscore, but looking for that character will turn up many false positives.

MVP Alum

Per @DanPatterson's suggestion, if the layer supports DEFINITIONQUERY, then check the definition property for a string with length.  If it has length, the layer is using a query.


for lyr in lyrs:
    if lyr.supports("DEFINITIONQUERY"):
        if len(lyr.definitionQuery.strip()): # a string with length
            print, lyr.definitionQuery


(My version of ArcMap allowed spaces as a definition query, so stripping them before checking length is advised.)

0 Kudos
New Contributor III

Similarly, I have an XY Event Layer (In layer properties, Source tab, Data Type: XY Event Source) and desc.dataElement.dataType == "FeatureClass" is true for an XY Event Layer, though it is clearly not an SDE Feature Class. 

0 Kudos