Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

OData filter options (handle null or empty values)

Tags:

odata

We are using $filter system query option in OData to execute filters where the filter value is sent in at runtime.

As an example the OData URL would be like this:

http://services.odata.org/Northwind/Northwind.svc/Customers?$filter=CustomerID eq @InCustomerID and Country eq @InCountry

where @InCustomerID & @InCountry are the input values for the equal filter.

At run time when the user enters some value for Customer ID (say 'ABCD') we would replace the @InCustomerID by 'ABCD'

At runtime the query would be as follows:

http://services.odata.org/Northwind/Northwind.svc/Customers?$filter=CustomerID eq 'ABCD' and Country eq 'US'

In the above case the user has entered the following values: CustomerID => 'ABCD' and Country => 'US'

My question is regarding handling of null values in OData $filter. If the user does not enter any value for CustomerID then we want to select all customers from specific country.

In sql case this would be something like:

select * from Customers where ((CustomerID = @InCustomerID) or (@CustomerID is null)) and (Country = @Country).

Essentially how to handle null or empty values so that the specific predicate in the logical condition would always be true.

Does OData filtering enables this option?

like image 874
Venki Avatar asked Jan 31 '11 01:01

Venki


People also ask

Is null in OData?

OData does not define an ISNULL or COALESCE operator. Instead, there is a null literal that can be used in comparisons. Unlike SQL, there is no special operator for testing whether a property is null.

Is OData filter case sensitive?

OData API filter value which you are selecting for $FILTER parameter is always case sensitive.

How do I filter OData query?

You can use filter expressions in OData requests to filter and return only those results that match the expressions specified. You do this by adding the $filter system query option to the end of the OData request.

How do you handle special characters in OData query?

Do not use the “JavaScript String replace() Method”. It will replace the first occurrence of the special characters. If you have 2 occurance of the same special characters in the filtering parameter, it will fail. So use the regular expression to replace the characters.


1 Answers

You can compare to null using the equality operator like this:

$filter=CustomerID eq null 

In your case the query would degenerate to something like:

$filter=(CustomerID eq null) or (null eq null) 

Which should work, but it's not very nice. Did you consider removing the predicate completely in such case?

like image 62
Vitek Karas MSFT Avatar answered Oct 04 '22 05:10

Vitek Karas MSFT