Query Objects in Business Central

Earn 25 points (50 with Pro) in two steps

  1. ① Read through the lesson — each section gets a ✓ as you scroll through it.
  2. ② When every section has a ✓, tap Complete lesson.

0 of 12 read · keep scrolling

✦ See fewer ads and earn double points — 50 a lesson instead of 25 — with Pro

Advanced AL Programming: Mastering Query Objects in Business Central

Introduction: Why Query Objects Matter

In the ecosystem of Microsoft Dynamics 365 Business Central, developers are frequently tasked with retrieving, aggregating, and analyzing data. While standard table lookups and Record variables are sufficient for simple CRUD (Create, Read, Update, Delete) operations, they often fall short when you need to perform complex data analysis, cross-table joins, or high-performance reporting. This is where Query objects come into play. A Query object is a specialized AL construct designed to retrieve data from one or more tables, apply filters, group data, and perform calculations—all executed directly at the database level.

Why does this matter? When you use standard Record variables to filter and loop through thousands of rows in AL code, the system must fetch each record individually, which creates heavy traffic between the application server and the database. Conversely, a Query object offloads the heavy lifting to the SQL server. The database engine executes the join, the aggregation, and the filtering in a single operation and returns only the finalized result set to Business Central. Understanding how to build, optimize, and consume Query objects is a fundamental skill for any developer looking to build performant, scalable applications in the Business Central environment.

Not read yet

The Architecture of a Query Object

A Query object is defined by a specific structure that dictates how the SQL query is constructed. Unlike a standard table or page, a Query object has a hierarchical layout where you define the data source and the columns you want to retrieve. The syntax relies on a declarative approach: you define what data you want, and the AL compiler translates that into efficient SQL statements.

At the core of every query is the Query object type. Within this object, you define:

  1. The Data Item: The primary table or tables from which you are pulling data.
  2. The Columns: Specific fields that will be returned in the result set.
  3. The Filters: Conditions applied to the data before it is aggregated or returned.
  4. The Aggregations: Mathematical operations such as Sum, Count, Min, or Max.

When you compile a Query object, Business Central creates a database view or a direct SQL query. This design ensures that the data retrieval is optimized for read-only scenarios. Because Query objects are read-only by design, they provide a secure and efficient way to expose data for reporting, API endpoints, or analytical dashboards without the risk of accidentally modifying the underlying business data.

Callout: Query Objects vs. Record Variables It is common for new developers to ask why they shouldn't just use Record.FindSet() or Record.Next(). The difference is fundamental. A Record variable is designed for transactional processing—fetching one row to update or delete it. A Query object is designed for set-based processing. If you need to sum the total sales for a customer, using a Record variable requires reading every sales line record into memory. A Query object uses the SQL SUM function to return a single numeric value, drastically reducing the memory footprint and execution time.

Not read yet

Defining Your First Query

To create a Query, you use the query keyword followed by the object ID and name. The structure follows a specific flow: query -> elements -> dataitem. Below is a basic example of a query that retrieves customer names and their total sales amount.

query 50100 "Customer Sales Query"
{
    QueryType = Normal;

    elements
    {
        dataitem(Customer; Customer)
        {
            column(CustomerNo; "No.") { }
            column(CustomerName; Name) { }

            dataitem(SalesLine; "Sales Line")
            {
                DataItemLink = "Sell-to Customer No." = Customer."No.";
                SqlJoinType = InnerJoin;

                column(TotalAmount; "Amount Including VAT")
                {
                    Method = Sum;
                }
            }
        }
    }
}

Breaking Down the Code

  • QueryType = Normal: This is the default. It indicates that the query is intended for standard data retrieval. Other types include API and Report, which serve specific integration or reporting needs.
  • DataItemLink: This property is crucial. It tells the system how to relate the two tables (in this case, the Customer table and the Sales Line table). It acts exactly like an ON clause in SQL.
  • SqlJoinType: We specified InnerJoin. This means the query will only return customers who have at least one sales line. If you wanted to see all customers regardless of whether they have sales, you would use LeftOuterJoin.
  • Method = Sum: This is where the magic happens. By setting the method to Sum, the AL compiler instructs SQL to perform the aggregation at the database level.

Not read yet

Advanced Data Handling: Joins and Filters

One of the most powerful features of Query objects is the ability to join multiple tables. Business Central supports several types of joins, and choosing the right one is essential for both performance and accuracy.

Understanding Join Types

  • InnerJoin: Returns rows only when there is a match in both tables.
  • LeftOuterJoin: Returns all rows from the left table, and the matched rows from the right table. If there is no match, the result columns from the right table will be null.
  • CrossJoin: Returns the Cartesian product of the two tables. This is rarely used in business applications as it can lead to massive datasets.

Note: Be cautious when using LeftOuterJoin. If you are performing aggregations on columns from the right table, a null value might cause unexpected behavior. Always ensure your code handles nulls or empty values appropriately when working with outer joins.

Applying Filters

Filters in Query objects can be applied in two ways: statically in the design or dynamically at runtime. Static filters are defined using the filter keyword within the data item.

dataitem(Customer; Customer)
{
    filter(CountryFilter; "Country/Region Code")
    {
        ColumnFilter = CountryFilter = const('US');
    }
}

Dynamic filters, on the other hand, are applied when you call the SetFilter method in your AL code before opening the query. This is the preferred method for user-driven reports where the criteria might change based on input from a request page.

Not read yet

Consuming Queries in AL

Defining the query is only half the battle. You must also know how to execute the query and iterate through the results in your AL code. The process follows a standard pattern: declare the query variable, apply any dynamic filters, call the Open method, and then use a Read loop.

procedure GetCustomerSales()
var
    CustSalesQuery: Query "Customer Sales Query";
begin
    CustSalesQuery.SetFilter(CustomerNo, 'C10000..C20000');
    if CustSalesQuery.Open() then begin
        while CustSalesQuery.Read() do begin
            Message('Customer %1 has total sales of %2', 
                CustSalesQuery.CustomerName, 
                CustSalesQuery.TotalAmount);
        end;
    end;
end;

The Read Loop

The Read() method is the mechanism that fetches the next row from the result set. It returns a boolean value: true if a row was successfully retrieved, and false when the end of the result set is reached. This is much cleaner than the FindSet / Next pattern used with record variables.

Not read yet

Comparison Table: Query Objects vs. Other Data Access Methods

Feature Record Variable Query Object Temp Table
Data Source Single Table Multiple (Joins) In-Memory
Performance Slower for Aggregation High (SQL-native) Fast for small sets
Operations CRUD Read-Only CRUD
Aggregation Manual (Looping) Native (SQL) Manual
Best Use Case Single record updates Reporting/Analysis Sorting/Caching

Best Practices for Performance and Maintenance

Query objects are high-performance tools, but they can be misused. When working in a large-scale Business Central environment, follow these best practices to ensure your code remains efficient and maintainable.

1. Minimize the Data Set

Only select the columns you absolutely need. If your query returns 50 columns but your report only uses 5, you are wasting memory and bandwidth. Every column you add to a query increases the size of the result set the database must process.

2. Leverage Indexed Columns

Whenever possible, ensure that the fields used in your DataItemLink and Filter properties are indexed in the underlying tables. If you join on a non-indexed field, the database engine will perform a full table scan for every row, which will destroy performance.

3. Use Query Objects for APIs

If you are building an integration that requires external systems to pull data, use the QueryType = API property. This automatically exposes the query as an OData endpoint, which is significantly faster than exposing a page or using standard web services.

4. Avoid Complex Logic in Columns

Do not try to perform complex conditional logic (like if-then-else blocks) inside a query column. If you need to transform data, do it after the query has returned the result, or create a calculated field on the table level if it is a simple arithmetic operation.

Warning: The "N+1" Query Problem A common mistake is to loop through a record set and call a query inside that loop. This is the classic "N+1" problem. If you have 1,000 customers and you call a query inside a foreach loop to get their sales, you are executing 1,001 database queries. Always look for ways to join the data into a single, set-based query instead of executing multiple small queries.

Not read yet

Common Pitfalls and Troubleshooting

Even experienced developers encounter issues when working with Query objects. Here are the most frequent problems and how to solve them.

Missing Data in Left Outer Joins

If you use a LeftOuterJoin and notice that records are missing, verify that your DataItemLink is correct. If the join condition is based on a field that contains empty values, those rows might be filtered out depending on the SQL collation settings.

Aggregation Errors

When you use an aggregation method like Sum or Average, all columns that are not aggregated must be included in the GroupBy logic. In AL, this is handled automatically, but if you attempt to add a non-aggregated column that doesn't make sense in the context of the grouping, the compiler will throw an error.

Deadlocks

Because queries are read-only, they are generally safe from locking issues. However, if you are running a very large, complex query while simultaneously performing heavy write operations on the same tables, you might experience contention. If this happens, consider running the query with the ReadUncommitted isolation level, which allows you to read data even if it is currently locked by another transaction.

Not read yet

Step-by-Step: Creating an API-Ready Query

Sometimes you need to expose data to a third-party BI tool. Here is the process for creating a Query that acts as an API.

  1. Define the Object: Create a new file with the .query.al extension.
  2. Set the Type: Set QueryType = API.
  3. Define API Properties: Use APIPublisher, APIGroup, APIVersion, and EntityName to define the URL structure.
  4. Define Data Items: Include the necessary tables and columns.
  5. Publish: Once the extension is installed, the data will be available at an endpoint like https://api.businesscentral.dynamics.com/v2.0/{tenant}/api/{publisher}/{group}/{version}/{entity}.
query 50101 "API Sales Query"
{
    QueryType = API;
    APIPublisher = 'MyCompany';
    APIGroup = 'Sales';
    APIVersion = 'v1.0';
    EntityName = 'salesData';
    EntitySetName = 'salesData';

    elements
    {
        dataitem(SalesHeader; "Sales Header")
        {
            column(DocumentNo; "No.") { }
            column(CustomerName; "Sell-to Customer Name") { }
            column(Amount; "Amount Including VAT") { }
        }
    }
}

This simple structure allows external systems to perform a GET request and receive a JSON-formatted list of sales data without needing to understand the underlying table structure of Business Central.

Not read yet

Advanced Techniques: Using TopNumberOfRows

Sometimes you don't need the entire dataset. For instance, if you are building a dashboard showing "Top 10 Customers by Sales," you don't need to fetch every customer in the database. You can use the TopNumberOfRows property to limit the result set at the SQL level.

query 50102 "Top 10 Customers"
{
    QueryType = Normal;
    TopNumberOfRows = 10;
    OrderBy = TotalSales = desc;

    elements
    {
        dataitem(Customer; Customer)
        {
            column(CustomerName; Name) { }
            column(TotalSales; "Sales (LCY)") { Method = Sum; }
        }
    }
}

By combining TopNumberOfRows with an OrderBy clause, you push the sorting and limiting logic directly to the database engine. This is significantly more efficient than fetching all records and sorting them in AL memory.

Callout: Performance Tuning with SQL Trace If you are unsure why a specific query is running slowly, use the SQL Profiler or the Business Central Performance Profiler. These tools allow you to see the exact SQL statement that is being generated by your Query object. If the generated SQL includes a Table Scan instead of an Index Seek, you know that your filtering or joining strategy needs to be optimized by adding better indexes or refining your DataItemLink.

Not read yet

Handling Nulls and Empty Values

One subtle area of Query objects is how they handle empty strings or zero values. When you join tables, you may encounter cases where there is no matching record. In SQL, this results in a NULL value. In AL, a NULL in a decimal field becomes 0, and a NULL in a text field becomes an empty string.

If your application logic relies on distinguishing between a "zero" value and a "null" (e.g., a total sales of 0 vs. a customer with no sales), you should add a helper column to your query. For example, you can add a boolean column that indicates whether a match was found:

column(HasSales; "Sales Line"."No.") 
{ 
    Method = Count; 
}

If the count is 0, you know there were no matching sales lines, allowing you to handle the logic appropriately in your AL code.

Organizing Your Queries

As your project grows, you will likely end up with dozens of query objects. It is important to maintain a consistent naming convention and file structure. A recommended pattern is:

  • File Name: Entity.Query.al (e.g., CustomerSales.Query.al)
  • Object Name: [Description] [Type] (e.g., CustomerSalesQuery)
  • Namespace: Use a consistent namespace to avoid conflicts with other extensions.

Keep related queries in the same folder within your project structure. If a query is only used by a specific report, consider grouping it with that report's source files to keep the project organized.

Not read yet

Common Questions (FAQ)

Can I update data through a Query object?

No. Query objects are strictly read-only. If you need to update data, you must use a Record variable.

How many tables can I join in a single query?

While there is no hard-coded limit, performance will degrade as you add more joins. A good rule of thumb is to keep queries to 3-5 joined tables. If you need to join more than that, consider using a view in the database or breaking the query into smaller, more manageable pieces.

Can I use a Query object as a data source for a Report?

Yes, and it is highly recommended. Using a Query object as the data item for a report is often much faster than using a traditional DataItem structure, especially when the report involves complex calculations.

What happens if I rename a field in the underlying table?

The AL compiler will detect the mismatch and throw an error during the build process. You will need to update the column reference in your Query object to point to the new field name.

Not read yet

Key Takeaways

  1. Set-Based vs. Record-Based: Understand that Query objects are for set-based data retrieval, which is significantly more efficient than the record-by-record processing of traditional AL variables.
  2. Offload to SQL: The primary benefit of a Query object is that it moves the processing (filtering, joining, and aggregating) to the database engine, reducing the load on the Business Central server.
  3. Choose Joins Wisely: Use InnerJoin for matches and LeftOuterJoin for comprehensive lists, but always account for how nulls are handled in your result set.
  4. Optimize Early: Always select only the necessary columns and use indexed fields for joins and filters to prevent performance degradation.
  5. Use for Integrations: Leverage QueryType = API for exposing data to external systems. It is the cleanest and fastest way to build web-accessible interfaces for your data.
  6. Read Loops: Master the Open() and Read() pattern. It is the standard, clean way to iterate through query results without the overhead of FindSet / Next.
  7. Performance Profiling: When in doubt, use the Performance Profiler to inspect the generated SQL. If the SQL is inefficient, your AL code will be too.

By integrating these practices into your daily development workflow, you will find that your Business Central applications become faster, more reliable, and much easier to maintain. Query objects are not just a feature; they are a fundamental building block for creating sophisticated, high-performance business applications.

Not read yet

Each section gets a ✓ as you scroll through it. Tap the button to jump to the next one.