Filtering records with a where clause

By default, SearchCursor will contain all rows in a table or feature class. However, in many cases, you will want to restrict the number of rows returned by some sort of criteria. Applying a filter through the use of a where clause limits the records returned.

Getting ready

By default, all rows from a table or feature class will be returned when you create a SearchCursor object. However, in many cases, you will want to restrict the records returned. You can do this by creating a query and passing it as a where clause parameter when calling the SearchCursor() function. In this recipe, you'll build on the script you created in the previous recipe by adding a where clause that restricts the records returned.

How to do it…

Follow these steps to apply a filter to a SearchCursor object that restricts the rows returned from a table or feature class:

  1. Open IDLE and load the SearchCursor.py script that you created in the previous recipe.
  2. Update the SearchCursor() function by adding a where clause that queries the facility field for records that have the HIGH SCHOOL text:
    with arcpy.da.SearchCursor("Schools.shp",("Facility","Name"), '"FACILITY" = 'HIGH SCHOOL'') as cursor:
  3. You can check your work by examining the C:ArcpyBookcodeCh8SearchCursor_Step2.py solution file.
  4. Save and run the script. The output will now be much smaller and restricted to high schools only:
    High school name: AKINS
    High school name: ALTERNATIVE LEARNING CENTER
    High school name: ANDERSON
    High school name: AUSTIN
    High school name: BOWIE
    High school name: CROCKETT
    High school name: DEL VALLE
    High school name: ELGIN
    High school name: GARZA
    High school name: HENDRICKSON
    High school name: JOHN B CONNALLY
    High school name: JOHNSTON
    High school name: LAGO VISTA
    

How it works…

We covered the creation of queries in Chapter 7, Querying and Selecting Data, so hopefully you now have a good grasp of how these are created along with all the rules you need to follow when coding these structures. The where clause parameter accepts any valid SQL query, and is used in this case to restrict the number of records that are returned.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset