Writing IS NULL/IS NOT NULL SQL statements in python/acrpy

3663
10
06-06-2019 10:29 AM
DoratheaBlock
New Contributor II

I am trying to write a search cursor that looks through the fields in a Feature Class and if there is a NULL value in any of the fields prints the statement "NULL values present". I am having trouble getting my where_clause to work. 

Here is what I have:

import arcpy

inFeature = 'SCRIPT_PARAMETERS_TEST'

inField = 'Prov'  
inField1 = 'Rd_Symbol'
inField2 = 'Name_Type'

nul = 'NULL'
where_clause = inField + " IS " + nul + " or " + inField1 + " IS " + nul + " or " + inField2 + " IS " + nul

with arcpy.da.SearchCursor(inFeature, (inField, inField1, inField2), where_clause) as cursor:
print("NULL values present")

The code runs however, there are two problems. First it prints NULL values present always, even when I change the fields to fields that are fully populated. Second I feel like there is probably a cleaner way to write the where clause... I have looked into things like:

where_clause = 'field_name' is None

where_clause =  'field_name' is 'NULL'

where_clause =  'field_name' IS Null'

but have not had success either getting a syntax error message. Or for 'field_name' is None there was no error message but when I checked the statement this is what I get:

>>>> print(where_clause)

FALSE

If you have any suggestions or if there is a resource anyone recommends to help better understand writing SQL statements with python/arcpy that would be much appreciated. 

0 Kudos
10 Replies
RandyBurton
MVP Alum

Assuming you are trying to determine

if  any value/row in any of the fields are NULL

you can try something like:

import arcpy

inFeature = r'C:\path\to\file.gdb\SCRIPT_PARAMETER_TEST' # path to feature
fields = ['Prov', 'Rd_symbol', 'Name_type' ]

# create where_clause
wc = []
for f in fields:
    wc.append('{} IS NULL'.format(f)) # search for null fields
where_clause = ' OR '.join(wc) # join to make OR statement
print where_clause # print where clause for test
# Prints: 'Prov IS NULL OR Rd_symbol IS NULL OR Name_type IS NULL'

rows = [row for row in arcpy.da.SearchCursor(inFeature, fields, where_clause)]
if len(rows): # if len(rows) > 0
    print('{} has null values'.format(inFeature))
else:
    print('{} does not have null values'.format(inFeature)) # but may also be empty feature
del rows‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍

You could also use Select Layer By Attribute and Get Count in place of the search cursor (lines 14+).