When working with record filters in AL for Microsoft Dynamics 365 Business Central, developers often wonder: Should I use SetRange or SetFilter?
Although both functions achieve similar results by restricting the dataset, there are important differences in syntax, flexibility, and performance.
Let’s break it down.
SetRange – The Simplest Way to Filter
SetRange is the most straightforward way to filter a field for a single value or a continuous range.
Let's apply SetRange on OnOpenPage trigger on Items Page.
Example 01: Rec.SetRange("No.", '1000', '1500');
Output: Returns Items with “No.” between 1000 and 1500.
Example 02: Rec.SetRange("Inventory Posting Group", 'FINISHED');
Output: Returns Items with “Inventory Posting Group” as ‘FINISHED’.
Best for: Simple filters, equality checks, and continuous ranges.
SetFilter – The More Flexible Option
SetFilter allows you to use filter expressions with placeholders and special symbols (.., |, <>, >, < etc.).
Let’s take the same filters that we took for setrange to understand the difference between the
syntax of both if we want to apply range filters –
Example 01: Rec.SetFilter(“No.”, ‘1000|1500’);
Output: Returns Items with “No.” between 1000 and 1500.
Example 02: Rec.SetFilter(Inventory, '>0');
Output: Returns Items with “Inventory” greater than 0.
Which One Should You Use?
- Use SetRange whenever possible → it’s cleaner, easier to read, and optimized.
- Use SetFilter when you need → multiple values, operators, or complex conditions.
Think of it this way:
- SetRange = Simple, Safe, Fast
- SetFilter = Flexible, Powerful, Complex
Performance Considerations:
- SetRange is slightly faster because it is internally optimized for equality and simple ranges.
- SetFilter is more versatile but requires parsing the filter string, so performance can be marginally slower in large datasets.
- In most real-world cases, the difference is negligible unless you’re processing very large records in tight loops.
SQL Comparison behind SetRange and SetFilter (for Clarity)
Behind the scenes, both functions generate SQL WHERE clauses.
- Example for SetRange: Customer.SetRange("Balance", 1000, 5000);
➔ SQL equivalent: WHERE Balance BETWEEN 1000 AND 5000
- Example for SetFilter: Customer.SetFilter("Balance", '>1000&<5000');
➔ SQL equivalent: WHERE Balance > 1000 AND Balance < 5000
Conclusion:
Both SetRange and SetFilter are essential tools for Business Central developers. By mastering both, you’ll write cleaner, faster, and more maintainable AL code.