Creating Queries in Business Central
Earn 25 points (50 with Pro) in two steps
- ① Read through the lesson — each section gets a ✓ as you scroll through it.
- ② When every section has a ✓, tap Complete lesson.
0 of 10 read · keep scrolling
✦ See fewer ads and earn double points — 50 a lesson instead of 25 — with Pro
Creating Queries in Business Central: A Comprehensive Guide
Introduction: The Power of Data Retrieval in AL
When developing applications for Dynamics 365 Business Central, one of the most critical skills you can master is efficient data retrieval. Business Central stores vast amounts of information across hundreds of tables, and as a developer, you are frequently tasked with extracting, aggregating, and presenting this data to end-users or external systems. While standard Record variables are sufficient for simple lookups, they often fall short when you need to perform complex joins, calculate totals on the fly, or expose data to web services. This is where the Query object in AL (Application Language) becomes indispensable.
A Query object is a specialized AL construct designed specifically for reading data. Unlike a table or a page, a query is not intended for data modification; it is an optimized tool for data extraction. By using queries, you can join multiple tables together, filter data at the database level, and perform aggregation functions—such as sums, counts, and averages—directly within the SQL server execution plan. This approach significantly reduces the amount of data transferred between the database and the Business Central service tier, leading to faster response times and a better experience for the user.
In this lesson, we will explore the architecture of AL queries, the syntax required to define them, and the best practices for implementing them in your own solutions. Whether you are building an integration to an external reporting tool or simply trying to optimize a slow-loading list page, understanding how to craft efficient queries is a hallmark of a professional Business Central developer.
Not read yet
Understanding the Query Object Architecture
To work effectively with queries, you must first understand how they differ from standard record-based data access. When you use a Record variable in AL, you are essentially asking the system to fetch records one by one or in small batches, which can lead to "N+1" query problems if you are looping through data and fetching related records in each iteration. A Query object, by contrast, defines a structured view of the data that the SQL engine compiles into a single, highly optimized statement.
Key Components of a Query
Every AL Query object consists of several structural elements that define how the data is retrieved and transformed. These components work together to provide a clean, tabular output:
- Query Elements: These are the building blocks of your query. They define which tables are included, how they are joined, and which specific fields are selected.
- DataItems: A DataItem acts as the primary source of data for the query. You can add multiple DataItems to join tables together.
- Columns: Columns represent the individual fields that will be available in the result set. You can rename these fields, perform calculations on them, or use them as filters.
- Filters: Filters allow you to restrict the data before it is returned. You can apply static filters in the code or dynamic filters at runtime.
- Aggregations: Queries support aggregate methods like
Sum,Min,Max,Avg, andCount. These are processed on the database server, which is significantly faster than calculating them in AL code.
Callout: Query vs. Record.SetRange While both
Recordobjects andQueryobjects can retrieve data, they serve different purposes. UseRecordobjects when you need to perform CRUD operations (Create, Read, Update, Delete) on individual records. UseQueryobjects when you need to read read-only data, join multiple tables, perform complex aggregations, or expose data to OData web services. Queries are inherently faster for large data sets because they minimize the overhead of the Business Central record-level security and triggers.
Not read yet
Defining a Query: Syntax and Structure
Creating a query in AL is straightforward. You define a new file with the .query.al extension and use the query keyword. Within the query, you define your DataItems and Columns. Let’s look at a basic example where we join the Customer table with the Sales Header table to find all open sales orders for specific customers.
Basic Query Example
query 50100 "Customer Sales Orders"
{
QueryType = Normal;
elements
{
dataitem(Customer; Customer)
{
column(CustomerNo; "No.") { }
column(CustomerName; Name) { }
dataitem(SalesHeader; "Sales Header")
{
DataItemLink = "Sell-to Customer No." = Customer."No.";
SqlJoinType = InnerJoin;
column(OrderNo; "No.") { }
column(PostingDate; "Posting Date") { }
}
}
}
}
In this example, we have defined a query that joins Customer and Sales Header. The DataItemLink property is essential here; it tells the system how to relate the two tables. The SqlJoinType property dictates whether this is an InnerJoin (only matching records) or a LeftOuterJoin (all records from the parent, matching records from the child).
Understanding Join Types
Choosing the right join type is critical for performance and data accuracy. The SqlJoinType property supports the following:
- InnerJoin: Only returns rows where 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 right-side columns will be null.
- CrossJoin: Returns the Cartesian product of the two tables. Use this with extreme caution as it can lead to massive result sets.
Not read yet
Advanced Query Features: Aggregations and Filters
One of the most powerful aspects of Business Central queries is the ability to aggregate data without writing complex loops. Imagine you need a report showing the total sales amount per customer. Instead of iterating through every Sales Invoice Line in AL, you can define a query that does the math for you.
Implementing Aggregations
To perform an aggregation, you must set the MethodType property on a column to Totals and then specify the Method (e.g., Sum). You must also group the results by the fields that are not being aggregated.
query 50101 "Customer Sales Totals"
{
QueryType = Normal;
elements
{
dataitem(Customer; Customer)
{
column(CustomerNo; "No.") { }
dataitem(SalesInvoiceLine; "Sales Invoice Line")
{
DataItemLink = "Sell-to Customer No." = Customer."No.";
column(TotalAmount; Amount)
{
MethodType = Totals;
Method = Sum;
}
}
}
}
}
When this query executes, the database engine groups the results by CustomerNo and calculates the sum of Amount for every related Sales Invoice Line. This is an incredibly efficient way to generate summary dashboards or export data for analytical processing.
Note: Grouping Behavior When you use
MethodType = Totals, the query automatically groups the results by all columns that do not have an aggregation method applied. You do not need to manually specify a "Group By" clause, as the AL compiler handles this based on the structure of your elements.
Not read yet
Step-by-Step: Consuming a Query in AL Code
Once you have defined your query, you need to know how to trigger it and process the results in your AL code. You do this by declaring a variable of type Query and calling the Open() and Read() methods.
Executing a Query
Follow these steps to fetch data using a query:
- Declare the Query Variable: Define the variable using the name of the query object you created.
- Apply Filters (Optional): Use
SetFilter()orSetRange()on the query object just as you would with a table record. - Open the Query: Call the
Open()method to execute the query against the database. - Loop Through Results: Use a
whileloop with theRead()method to fetch each row of data. - Access Columns: Access the columns by referencing them as properties of the query variable.
procedure DisplayCustomerSales()
var
CustomerSalesQuery: Query "Customer Sales Totals";
begin
// Optional: Filter the query
CustomerSalesQuery.SetFilter(CustomerNo, '10000..20000');
// Execute the query
if CustomerSalesQuery.Open() then begin
while CustomerSalesQuery.Read() do begin
Message('Customer %1 has a total sales amount of %2',
CustomerSalesQuery.CustomerNo,
CustomerSalesQuery.TotalAmount);
end;
end;
end;
This pattern is the standard way to interact with queries. Notice how clean and readable the code is compared to manual record iteration.
Not read yet
Best Practices for Query Development
As with any development task, there are "dos and don'ts" that will help you maintain high performance and code quality. Queries are powerful, but they can also be abused if not handled correctly.
1. Keep Result Sets Lean
Only include the columns that you actually need. Every extra column you add to a query increases the amount of data the SQL server must process and return. If you are building a query for a specific integration, do not include fields "just in case."
2. Use Proper Filtering
Always apply filters as early as possible. If you are creating a report for a specific date range, use SetFilter on the Posting Date field before calling Open(). Filtering at the query level is exponentially faster than filtering the results after they have been fetched into memory.
3. Avoid Over-Joining
While you can join many tables, keep the join depth reasonable. Deeply nested joins with many tables can create complex SQL statements that the optimizer might struggle to execute efficiently. If you find yourself joining more than 4-5 tables, consider if there is a better way to structure your data or if you should be using two separate queries.
4. Use Read-Only Operations
Remember that queries are for reading. Never attempt to modify data based on query results directly within the query object logic. If you need to update records, use the result of the query to identify the SystemId or primary key of the records, then perform the update using a standard Record variable.
Warning: Performance Pitfall A common mistake is to execute a query inside a loop that is itself inside another loop. This is a recipe for performance degradation. Always try to design your queries to return the necessary data in a single pass. If you are looping through records in AL and running a query for each iteration, you are effectively creating a "N+1" problem at the service layer.
Not read yet
Comparison Table: Query vs. Other Data Access Methods
To help you decide when to use a query, refer to the following comparison table.
| Feature | Record (Table) | Query | Report DataItems |
|---|---|---|---|
| Primary Purpose | CRUD Operations | Data Retrieval/Aggregation | Generating Reports |
| Joins | Manual (Code) | Native (SQL Joins) | Native (DataItem Links) |
| Aggregation | Manual (Code) | Automatic (SQL) | Automatic (Grouping) |
| Web Services | Limited | Native Support | Not Supported |
| Performance | High for single records | High for bulk/joined data | High for reporting |
Handling Common Pitfalls
Even experienced developers can run into issues when working with queries. Below are some of the most frequent challenges and how to resolve them.
The "Empty Result" Problem
If your query returns no data, check your DataItemLink and SqlJoinType. Often, an InnerJoin might be failing because there are no matching records in the secondary table, causing the entire row to be excluded. Switching to a LeftOuterJoin can help identify if your join conditions are too restrictive.
Column Name Collisions
When joining tables, you might have fields with the same name in different tables (e.g., Description exists in almost every table). AL allows you to alias these columns. Always provide a unique name for your columns in the query definition to avoid confusion in your AL code.
column(CustomerName; Name) { }
column(SalesOrderDescription; Description) { }
Filtering on Non-Indexed Fields
If you are filtering your query on a field that is not indexed in the underlying table, the query performance will suffer significantly. Always check the table structure in the Business Central base application to ensure your filters are targeting indexed fields.
Not read yet
Exposing Queries as Web Services
One of the primary benefits of using a Query object is that it can be exposed as a web service with virtually no additional effort. This is the preferred way to provide data to external systems like Power BI, Excel, or custom middleware.
Exposing a Query
- Open the Web Services page in the Business Central client.
- Click New.
- Select Query in the Object Type column.
- Enter the Object ID (e.g., 50100).
- Provide a name for the Service Name.
- Check the Published box.
Once published, you can access the data via OData at the URL provided. Because queries are optimized for reading, they perform significantly better than exposing pages as web services, especially when you need to pull large volumes of data.
Troubleshooting and Debugging
When a query isn't returning the data you expect, the first step is to enable the SQL Trace in the Business Central administration or use the Debugger to inspect the filter values before the query is opened.
- Check the Filters: Use the debugger to verify that the
SetFilterorSetRangecalls are actually applying the values you expect. - Verify Data Consistency: Sometimes, the data in the database simply doesn't match the criteria. Run a simple SQL query (if you have access to the underlying SQL database, such as in an On-Premise environment) to see if the join logic produces the expected result.
- Test with Small Data Sets: Start by querying a small subset of data. If the query works for one customer but not for the whole set, you likely have a data issue or a logic error in your join conditions.
Not read yet
Summary of Key Takeaways
As we conclude this lesson, keep these core principles in mind to ensure your Business Central development remains efficient and scalable:
- Queries are for Reading: Always prioritize Queries for data extraction, aggregation, and reporting tasks. They are purpose-built for these operations and outperform standard
Recordvariable loops. - Leverage SQL Efficiency: By using Queries, you push the heavy lifting (joins and calculations) to the SQL Server, which is far more efficient than processing that logic in the AL service tier.
- Choose Joins Wisely: Understand the difference between
InnerJoinandLeftOuterJoin. Using the wrong join type is the most common cause of missing data in query results. - Aggregate at the Source: Use
MethodType = Totalsto perform summations and averages. This eliminates the need for complex, manual looping logic in your AL code. - Filter Early: Always apply filters using
SetRangeorSetFilterbefore calling theOpen()method. This ensures the database server only processes the records you actually need. - Expose for Integration: Queries are the ideal mechanism for exposing data to external systems via OData. They provide a clean, tabular interface that is easy for external developers to consume.
- Maintain Simplicity: While you can create complex queries, try to keep them focused on a single business purpose. Overly complex queries with too many joins can become difficult to maintain and troubleshoot.
By mastering the Query object, you move beyond simple record manipulation and into the realm of professional data engineering within Business Central. Practice these concepts by building a few custom queries for your next project, and you will quickly see the improvements in both your code quality and the performance of your applications.
Not read yet
Frequently Asked Questions (FAQ)
Q: Can I update data using a Query?
A: No. Queries are read-only. If you need to update data, use the query to find the relevant records and then use a Record variable to perform the update.
Q: Why is my query returning fewer records than expected?
A: This is almost always due to an InnerJoin that is filtering out records that don't have a match in the secondary table. Try changing the SqlJoinType to LeftOuterJoin.
Q: Is there a limit to how many records a query can return? A: While there is no hard limit on the number of records, keep in mind that returning massive result sets can impact the performance of the service tier. If you need to export thousands of records, consider using a batching strategy or a background report.
Q: Should I use Queries for every list page?
A: No. List pages in Business Central are built to use Record variables. Queries are best suited for reporting, integrations, and complex data analysis, not for the standard user interface grid.
Q: Can I use functions within a Query?
A: You can use standard aggregate functions like Sum, Min, Max, Avg, and Count. You cannot call custom AL functions or procedures within the query definition itself.
Not read yet
Each section gets a ✓ as you scroll through it. Tap the button to jump to the next one.
Spend your points to unlock exam-style practice questions
Spend points to unlock MB-820 exam-style practice questions.
Practice for MB-820