Wednesday, October 8, 2014

Working with NULLABLE fields in SQL Queries

This post describes possible problems and resolutions on how to "Work with NULLABLE fields in SQL Queries"

Assumptions :

Retrieving column information from a table with some search criteria

Table Name : MARS_ALLOCATION_DATA
Columns : ALLOCATION_NUMBER, ZONE_CODE and ZONE_DESCRIPTION

Sample Query :

SELECT ALLOCATION_NUMBER,ZONE_CODE,ZONE_DESCRIPTION FROM MARS_ALLOCATION_DATA
WHERE MONTH='JUN' AND YEAR=2014

Retrieves ALLOCATION_NUMBER, ZONE_CODE and ZONE_DESCRIPTION from table mentioned whose MONTH is 'JUN' and YEAR is 2014


We wanted to add one more condition as to "Retrieve those records in which ZONE_CODE and ZONE_DESCRIPTION are not same hence we add one more extra condition in query as 
' AND ZONE_CODE != ZONE_DESCRIPTION' which ideally should give the response we deserve but it would give a response which is shown below


Where as ideally a record with ZONE_CODE as 'S' and ZONE_DESCRIPTION is NULL should be retrieved by adding the filter in the query as ZONE_CODE != ZONE_DESCRIPTION. 

Reason :

When adding a search filter which involves NULLABLE fields the filter won't work if one of the columns have NULL in the data as even NULL is not equal to NULL, hence resulting in the response which involves only non-null records in the two columns which are used for filter.

In Such cases it is suggested to add the filter as 
'ISNULL(ZONE_CODE,'') != ISNULL(ZONE_DESCRIPTION,'')'

Hence entire query will be changed accordingly,

SELECT ALLOCATION_NUMBER,ZONE_CODE,ZONE_DESCRIPTION FROM MARS_ALLOCATION_DATA
WHERE MONTH='JUN' AND YEAR=2014 AND ISNULL(ZONE_CODE,'') != ISNULL(ZONE_DESCRIPTION,'')

Which results in the below expected response,


No comments:

Post a Comment