Linking Joining and Aggregating Data
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
Module: Develop Using AL Objects
Lesson: Linking, Joining, and Aggregating Data
Introduction: The Power of Data Relationships in AL
In the world of Business Central development, data rarely exists in isolation. Whether you are building a simple report, a complex integration, or a custom business process, you will inevitably need to pull information from multiple tables, combine them based on shared keys, and perform calculations to turn raw data into actionable insights. This is where the AL (Application Language) Query object becomes one of your most powerful tools. Unlike standard Record variables that retrieve data row-by-row, Queries are designed to interact directly with the database engine to perform set-based operations.
Understanding how to link, join, and aggregate data is the difference between a system that runs quickly and one that hangs when processing large datasets. When you retrieve data using a Query, the database performs the heavy lifting, returning only the final result set to your application. This lesson will guide you through the mechanics of designing efficient Queries, mastering join types, and utilizing aggregation functions to build performant and clean solutions. By the end of this lesson, you will be able to structure your data retrieval logic to maximize performance and maintainability.
Not read yet
Understanding the AL Query Object
The AL Query object is a server-side object that allows you to retrieve records from one or more tables and perform calculations on them. While you can use Record variables and Repeat-Until loops to process data, this approach often leads to the "N+1" problem, where your code performs one query to get a list of records and then an additional query for every single record in that list to fetch related data. Queries solve this by using SQL-based joins, which are significantly more efficient for large data volumes.
A Query object is composed of a query definition, followed by an elements section where you define the data items and columns. The structure is hierarchical, starting with a DataItem (the primary table) and potentially nesting additional DataItem objects inside it to create relationships.
Callout: Query vs. Record Variables It is important to distinguish between
Queryobjects andRecordvariables.Recordvariables are ideal for row-by-row CRUD (Create, Read, Update, Delete) operations where you need to modify individual records.Queryobjects are read-only and are designed specifically for reporting, data analysis, and bulk retrieval. Never use a Query if you need to update the underlying data, as Queries do not support write operations.
Not read yet
Designing Your First Query: The Basics
To create a Query, you define a query object in your AL project. You must specify a QueryType, which is typically Normal. The core of the Query is the elements block, which contains one or more dataitem elements. Each dataitem refers to a table in the database.
Step-by-Step: Creating a Basic Query
- Create a new file in your AL project with the
.alextension (e.g.,CustomerSales.query.al). - Define the object structure using the
querykeyword and provide a unique ID and name. - Within the
elementsblock, define your primarydataitem. - Add
columnelements to map fields from the table to the Query output. - Save and compile your project.
query 50100 "CustomerSalesQuery"
{
QueryType = Normal;
elements
{
dataitem(Customer; Customer)
{
column(CustomerNo; "No.") { }
column(CustomerName; Name) { }
column(City; City) { }
}
}
}
In this example, we have a simple query that selects specific fields from the Customer table. While this is straightforward, the real power comes when we start linking tables together.
Not read yet
Mastering Joins: Linking Data Items
In AL Queries, you link data items by nesting them. The secondary data item is placed inside the block of the primary data item. You then use the DataItemLink property to define how the two tables relate, typically using a common field like Customer No. or Document No..
Understanding Join Types
The SqlJoinType property determines how the database engine combines the rows from the two tables. There are four primary join types available in AL:
- InnerJoin: Returns rows only when there is a match in both tables. If a customer has no sales orders, they will not appear in the result set.
- LeftOuterJoin: Returns all rows from the primary table, and the matched rows from the secondary table. If there is no match, the columns from the secondary table will contain null values.
- RightOuterJoin: Returns all rows from the secondary table, and the matched rows from the primary table.
- FullOuterJoin: Returns all rows when there is a match in either the primary or secondary table.
Example: Joining Customers and Sales Headers
query 50101 "CustomerOrdersQuery"
{
QueryType = Normal;
elements
{
dataitem(Customer; Customer)
{
column(CustName; Name) { }
dataitem(SalesHeader; "Sales Header")
{
DataItemLink = "Sell-to Customer No." = Customer."No.";
SqlJoinType = InnerJoin;
column(OrderNo; "No.") { }
column(OrderDate; "Order Date") { }
}
}
}
}
In this example, we use an InnerJoin to only retrieve customers who have actually placed orders. If we wanted to see all customers regardless of whether they have orders, we would change the SqlJoinType to LeftOuterJoin.
Tip: Choosing the Right Join Always prefer
InnerJoinif you do not need data from the secondary table when a match is missing.LeftOuterJoinis useful for scenarios like "Show me all customers and their total sales, even if the total is zero." Be aware thatLeftOuterJoincan sometimes be slower thanInnerJoindepending on the database indexing, so use it judiciously.
Not read yet
Aggregating Data: Making Sense of Numbers
Data retrieval is only half the battle. Often, you need to calculate sums, averages, or counts. AL Queries provide built-in Method properties for columns that allow you to perform these operations directly on the database server.
Common Aggregation Methods
- Sum: Calculates the total of the column.
- Average: Calculates the arithmetic mean.
- Min: Finds the lowest value.
- Max: Finds the highest value.
- Count: Counts the number of rows.
When you use an aggregation method on a column, you must also define a GroupBy property on the columns you are aggregating against. If you do not group the non-aggregated columns, the database will not know how to organize the result set.
Example: Aggregating Sales per Customer
query 50102 "CustomerSalesTotal"
{
QueryType = Normal;
elements
{
dataitem(Customer; Customer)
{
column(CustNo; "No.") { GroupBy = true; }
dataitem(SalesLine; "Sales Line")
{
DataItemLink = "Sell-to Customer No." = Customer."No.";
SqlJoinType = InnerJoin;
column(TotalAmount; "Amount")
{
Method = Sum;
}
}
}
}
}
In this code, we group by the Customer No. and calculate the Sum of the Amount field from the Sales Line table. The database will group all sales lines belonging to a single customer and return a single row per customer with their total sales amount.
Not read yet
Best Practices for Query Development
Creating queries is easy, but creating performant and maintainable queries requires discipline. Follow these industry standards to ensure your code remains scalable.
1. Only Select What You Need
Avoid the temptation to include every field from a table. Every column you add to a query increases the amount of data transferred from the database to the application server. Only include columns that are strictly necessary for your logic or report.
2. Leverage Indexing
Queries are only as fast as the indexes on the tables being joined. Ensure that the fields you use in DataItemLink are indexed in the underlying tables. If you are joining on a custom field, verify that a secondary index exists on that field to prevent full table scans.
3. Use Filtered DataItems
You can apply filters directly to a data item using the DataItemTableFilter property. This reduces the dataset size before the join occurs, which is significantly faster than filtering the data after the query has executed.
dataitem(SalesHeader; "Sales Header")
{
DataItemTableFilter = "Document Type" = const(Order), Status = const(Released);
// ...
}
4. Avoid Complex Logic in Queries
Queries are not meant for complex business logic. If you need to perform conditional formatting, complex string manipulation, or multi-step calculations, do that in the AL code that consumes the query result, not inside the Query object itself. Keep the Query focused on data retrieval and aggregation.
Warning: The "N+1" Trap Even with Queries, you can fall into the N+1 trap if you iterate through a Query result and then call
Record.Get()inside the loop. If you find yourself doing this, rethink your Query structure. You should be able to include the necessary fields from related tables directly in the Query via joins rather than fetching them individually in the code.
Not read yet
Comparison Table: Data Retrieval Methods
| Feature | Record Variables | Query Objects |
|---|---|---|
| Primary Use | CRUD Operations | Reporting/Bulk Data |
| Join Capability | Manual (Code-based) | Native (SQL-based) |
| Performance | Slower for bulk data | Highly optimized |
| Modifiability | Can modify records | Read-only |
| Aggregation | Manual (in code) | Native (Sum, Avg, etc.) |
Step-by-Step: Consuming a Query in AL Code
Once you have defined your Query, you need to know how to use it in your business logic. You interact with a Query object using the Open() method, followed by a Read() loop.
- Declare the Query variable: Use the
querykeyword followed by the name you assigned. - Open the Query: Call the
Open()method. This triggers the execution of the SQL statement on the database. - Read the Data: Use a
whileloop to call theRead()method. Each call toRead()populates the variables in your query object with the next row of the result set. - Access Columns: Access the columns by their name as defined in the Query object.
- Close the Query: While not strictly required, it is good practice to let the variable go out of scope or explicitly clear it.
procedure ProcessCustomerSales()
var
CustSalesQuery: Query "CustomerSalesTotal";
begin
CustSalesQuery.Open();
while CustSalesQuery.Read() do begin
// Access data via the Query variable
Message('Customer %1 has total sales of %2',
CustSalesQuery.CustNo,
CustSalesQuery.TotalAmount);
end;
CustSalesQuery.Close();
end;
Not read yet
Common Pitfalls and Troubleshooting
Even experienced developers encounter issues when working with Queries. Here are some of the most common mistakes and how to avoid them.
The Missing GroupBy
A very common error occurs when you use an aggregation method (like Sum) but forget to set GroupBy = true on the other columns. The compiler will often throw an error, but if it doesn't, the database might return unexpected results or duplicate rows. Always double-check that every non-aggregated column is part of your grouping logic.
Incorrect Join Type
If your query is returning zero results when you expect data, check your SqlJoinType. An InnerJoin will drop rows entirely if a match is not found in the secondary table. If you are unsure why data is missing, temporarily change the join to LeftOuterJoin to see if the secondary table columns are coming back as null, which indicates a failure to match.
Data Type Mismatches
When performing joins, ensure that the data types of the linked fields match perfectly. While Business Central often handles implicit conversions, joining a Code field to a Text field can sometimes result in performance degradation or unexpected behavior. Always use the same data types for keys.
Excessive Use of Filters
While filtering is good, applying too many filters or filters on non-indexed fields can degrade performance. If you notice a specific query is slow, use the SQL Profiler or the Business Central performance toolkit to analyze the generated SQL. Look for "Table Scans" in the execution plan—these are usually a sign that your filters or joins are not utilizing indexes efficiently.
Callout: Performance Tuning When a query performs poorly, the first step is to look at the indexes. If you are filtering by
StatusandDate, ensure you have a composite index that covers both fields. If you are joining onCustomer No.andDocument No., ensure that the foreign key relationship is properly indexed. Most performance issues in AL are database-related, not language-related.
Not read yet
Advanced Techniques: Filters in Code
Sometimes, you cannot define all filters at design time. You might need to allow the user to select a date range or a specific customer group. You can apply filters to a Query dynamically in your AL code before calling the Open() method.
procedure GetSalesInRange(StartDate: Date; EndDate: Date)
var
CustSalesQuery: Query "CustomerSalesTotal";
begin
// Apply filters dynamically before opening the query
CustSalesQuery.SetFilter(OrderDate, '%1..%2', StartDate, EndDate);
CustSalesQuery.Open();
// ... proceed with reading
end;
This approach provides flexibility while still allowing the database to execute the query with the filters already applied, maintaining high performance. Note that the filter must be applied to a column defined in the Query.
Industry Best Practices: Documentation and Naming
As your project grows, your list of Query objects will expand. Maintainability is key to long-term success. Use these conventions:
- Naming Conventions: Use a descriptive name that indicates the purpose of the query (e.g.,
DetailedSalesAnalysis,InventoryValuationByLocation). Avoid generic names likeQuery1orTestQuery. - Comments: Use the
//or/* */syntax to document why a specific join type was chosen or what a complex calculation is intended to achieve. - Modular Design: If you find yourself creating the same Query in multiple places, consider creating a single, well-defined Query object that can be reused across different parts of your application.
- Consistent Formatting: Use standard AL indentation. Keep your
dataitemandcolumnblocks cleanly aligned to make the hierarchical relationship of the data obvious at a glance.
Not read yet
Summary and Key Takeaways
Linking, joining, and aggregating data are fundamental skills for any AL developer. By leveraging the Query object, you move from being a developer who writes code that loops through data, to one who writes code that orchestrates the database engine to do the work for you.
Key Takeaways:
- Use Queries for Read Operations: Reserve
Recordvariables for row-based manipulation and useQueryobjects for efficient data retrieval, reporting, and aggregation. - Understand Join Types: Choose
InnerJoinfor strict relationships andLeftOuterJoinwhen you need to include records even without a match. Misunderstanding these will lead to missing data. - Master Aggregation: Use
Methodproperties (Sum, Count, Average) to perform calculations on the server side, ensuring you useGroupByfor all non-aggregated columns. - Prioritize Performance: Only retrieve the columns you need, ensure your join fields are indexed, and apply filters at the database level using
DataItemTableFilterorSetFilter(). - Avoid the N+1 Problem: Never perform a
Record.Get()inside a loop that iterates over a Query result. If you need more data, include it in the Query structure via a join. - Dynamic Filtering: Always prefer applying filters in code via
SetFilter()rather than fetching all records and filtering them in memory. - Keep it Focused: A Query should be a dedicated tool for a specific data requirement. Keep your logic simple and avoid putting business process workflows inside the Query definition.
By following these principles, you will ensure that your Business Central solutions are not only functional but also performant and easy to maintain as your business needs evolve. The ability to structure data retrieval effectively is a hallmark of a senior developer and will serve you well across any project you undertake in the Business Central ecosystem.
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