Building and Extending Tables

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 10 read · keep scrolling

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

Building and Extending Tables in AL

Introduction: The Foundation of Data in Business Central

When working with Microsoft Dynamics 365 Business Central, everything begins with data. Before you can build a user interface, create a business process, or generate a report, you must define how the system stores information. In the Application Language (AL), this is handled through Table objects. A table is essentially the blueprint for your database records; it defines the fields, the keys used for sorting and searching, and the fundamental rules that govern how data is entered and validated.

Understanding how to build and extend tables is the most critical skill for a Business Central developer. If your table structure is poorly designed, your entire application will suffer from performance bottlenecks, data integrity issues, and maintenance nightmares. Conversely, a well-designed table structure makes the rest of your development process significantly easier. Whether you are creating a custom feature from scratch or extending an existing table provided by Microsoft, you are performing the core work of data modeling within the Business Central ecosystem.

In this lesson, we will explore the anatomy of an AL table, learn how to create new tables, understand the powerful concept of Table Extensions, and discuss the best practices that separate amateur code from professional, production-ready solutions.


Not read yet

Anatomy of an AL Table

An AL table is a text-based definition that the Business Central compiler translates into a SQL Server table. When you define a table, you are essentially telling the platform which columns (fields) to create, what data types they should hold, and how the database should index that information for rapid retrieval.

Key Components of a Table

Every table object consists of several mandatory and optional sections. Understanding these is essential for building structured, readable code:

  • Table Properties: These define the behavior of the table as a whole. Examples include DataClassification, which is mandatory for compliance, and LookupPageId, which tells the system which page to show when a user clicks the lookup button on a field.
  • Fields: These are the individual data points. Each field has a name, an ID (an integer), a data type (such as Code, Text, Decimal, or Boolean), and various properties like Caption and NotBlank.
  • Keys: Keys define how the database should index the data. The primary key is the unique identifier for a record, while secondary keys allow the system to quickly sort and filter data based on other fields.
  • Field Groups: These are sets of fields that the system uses for specific purposes, such as the DropDown group, which determines which fields appear when a user is selecting a record from a lookup list.

Callout: Table vs. Table Extension A Table object is a complete definition of a new database entity. You use it when you need to store data that doesn't fit into any existing Business Central tables. A Table Extension, on the other hand, is a modifier. It allows you to add new fields or change properties on tables that Microsoft or another partner has already created. You cannot delete existing fields or change their data types in an extension; you can only append new functionality to the existing structure.


Not read yet

Creating a New Table: Step-by-Step

Let's walk through the process of creating a new table. Suppose we are building a custom module for tracking "Vehicle Maintenance." We need a table to store information about the vehicles in a company fleet.

Step 1: Define the Object

In your AL project, create a new file named Vehicle.Table.al. Start by using the ttable snippet provided by the AL Language extension in VS Code.

table 50100 Vehicle
{
    DataClassification = CustomerContent;
    Caption = 'Vehicle';
    LookupPageId = "Vehicle List";
    DrillDownPageId = "Vehicle List";

    fields
    {
        field(1; "No."; Code[20])
        {
            Caption = 'No.';
            DataClassification = CustomerContent;
        }
        field(2; Description; Text[100])
        {
            Caption = 'Description';
        }
        field(3; "Purchase Date"; Date)
        {
            Caption = 'Purchase Date';
        }
        field(4; Mileage; Decimal)
        {
            Caption = 'Mileage';
        }
    }

    keys
    {
        key(PK; "No.")
        {
            Clustered = true;
        }
    }
}

Step 2: Understanding the Field Definitions

In the code above, notice the field definition. Each field requires a unique ID. In a custom project, you will typically use IDs starting from 50100. The Code[20] type is standard for identifiers like "No." because it is efficient for indexing. The Text[100] type is used for descriptive fields. Always remember to set the DataClassification property, as Business Central requires this for GDPR and data privacy compliance.

Step 3: Setting the Keys

The keys section is where you define the primary key. Every table must have a primary key. By setting Clustered = true, you inform the SQL database that this is the physical order in which records are stored, which significantly improves read performance for that specific key.


Not read yet

Extending Existing Tables

Most of your work as a Business Central developer will involve extending standard tables. For example, if you want to add a "Vehicle No." field to the standard Sales Header table, you should not modify the standard table directly. Instead, you create a Table Extension.

The Syntax of a Table Extension

A table extension allows you to add fields to existing tables without changing the original source code. This is the foundation of the "no-code-modification" philosophy in modern Business Central development.

tableextension 50101 "Sales Header Ext" extends "Sales Header"
{
    fields
    {
        field(50100; "Vehicle No."; Code[20])
        {
            Caption = 'Vehicle No.';
            TableRelation = Vehicle."No.";
        }
    }
}

Why Use TableRelations?

In the example above, we used the TableRelation property. This is one of the most powerful features in AL. By setting TableRelation = Vehicle."No.", you create a hard link between the Sales Header and your custom Vehicle table. The Business Central platform automatically handles the referential integrity, lookup functionality, and validation for you. If a user tries to enter a Vehicle Number that does not exist in the Vehicle table, the system will automatically throw an error.

Note: When creating table extensions, always ensure that your field IDs are unique within that specific table extension. If you have multiple extensions for the same table, ensure that the field IDs do not overlap, as this can cause compilation errors and deployment failures.


Not read yet

Best Practices for Table Design

Designing tables is as much about discipline as it is about syntax. Follow these industry standards to ensure your tables remain performant and maintainable.

1. Naming Conventions

Use clear, descriptive names for your tables and fields. Avoid abbreviations that might confuse other developers. If your table is about "Vehicle Maintenance," name it Vehicle Maintenance. Ensure that your field names in AL match the intended display names in the UI, as the Caption property defaults to the field name if not specified.

2. Data Classification

Always categorize your data using the DataClassification property. This is not just a suggestion; it is a requirement for AppSource submission and general data hygiene. The common classifications include:

  • CustomerContent: Data created by the user (e.g., descriptions, dates).
  • EndUserIdentifiableInformation: Data that identifies a person (e.g., names, emails).
  • SystemMetadata: Data used by the system to function.

3. Field IDs

Plan your field IDs carefully. While you can technically use any integer, it is best practice to keep them grouped logically. If you are adding multiple fields to a table, keep them in a specific range so they are easy to identify in the object browser.

4. Avoiding "Fat" Tables

A common mistake is creating tables with too many fields. If a table has hundreds of fields, it becomes difficult to manage and can lead to performance issues. If you find yourself adding many fields that are only used in one specific context, consider whether a separate, related table might be a better design choice.


Not read yet

Common Pitfalls and How to Avoid Them

Even experienced developers encounter issues when building tables. Here are some of the most frequent mistakes and how to prevent them.

Over-indexing

It is tempting to create a secondary key for every field you think a user might filter on. However, every key you create must be maintained by the SQL Server every time a record is inserted, updated, or deleted. Too many indexes will significantly slow down data entry. Only create secondary keys for fields that are frequently used in filters or sorting in the user interface.

Incorrect Field Types

Choosing the wrong data type can lead to data truncation or storage inefficiency. For example, using Text instead of Code for an identifier field is a mistake because Code fields are automatically converted to uppercase and are more efficient for lookups. Always use Code for identifiers, primary keys, and relations.

Ignoring TableRelation Validation

Sometimes developers forget to set the ValidateTableRelation property. By default, it is set to true. If you set it to false, the system will not check if the value in the field exists in the related table. This can lead to "orphaned" data where a record points to a non-existent entity, causing crashes in reports or page displays.

Warning: Never use ValidateTableRelation = false unless you have a very specific technical reason to do so. It is almost always better to handle data validation logic within the table's trigger code rather than disabling the system's built-in referential integrity.


Not read yet

Deep Dive: Triggers in Tables

Tables are not just containers for data; they are also active participants in the data lifecycle. Every table has built-in triggers that allow you to execute code when specific events occur.

The Most Common Table Triggers:

  • OnInsert(): This code runs before a record is inserted into the database. Use this to initialize default values or calculate sequence numbers.
  • OnModify(): This runs before a record is modified. Use this for audit logging or to prevent changes to specific fields after a record has reached a certain status.
  • OnDelete(): This runs before a record is deleted. Use this to check if the record is allowed to be deleted (e.g., preventing the deletion of a customer who has open invoices).
  • OnRename(): This runs when the primary key of a record is changed.

Example: Using OnInsert

Suppose we want to ensure that every time a new Vehicle is created, we automatically set the "Purchase Date" to the current date if it is empty.

table 50100 Vehicle
{
    // ... fields ...

    trigger OnInsert()
    begin
        if "Purchase Date" = 0D then
            "Purchase Date" := Today;
    end;
}

This simple trigger adds a layer of business logic directly into the data layer, ensuring that the rule is enforced regardless of whether the record is created via a page, a web service, or an API.


Not read yet

Comparison: Choosing the Right Data Type

Selecting the correct data type is fundamental to efficient table design. Below is a quick reference guide for common scenarios.

Data Type Best Used For Note
Code IDs, Primary Keys, Lookup fields Automatically uppercase; efficient indexing.
Text Descriptions, Names, Comments Variable length; not for primary keys.
Decimal Quantities, Amounts, Prices Precise; use for all financial calculations.
Boolean Yes/No flags, Status indicators Very small footprint in the database.
Date Dates without time components Use for birthdates, transaction dates.
DateTime Timestamps Use for tracking exactly when an event occurred.
Integer Counts, sequence numbers Faster than decimal for non-fractional math.

Best Practices for Table Extensions: The "ID Range" Strategy

In a multi-developer environment or when working with ISV solutions, managing object IDs is critical. Business Central uses an ID range system. You must ensure that the IDs you use for your tables and fields do not conflict with IDs used by other extensions.

  1. Define a Range: Work with your team to define a specific range of IDs for your project (e.g., 50100 to 50150).
  2. Use Number Series: For tables that require a "No." field, do not hardcode the ID. Use the standard Business Central No. Series functionality. This allows users to configure their own numbering schemes for your custom entities.
  3. Encapsulation: Keep your logic inside the table objects as much as possible. If you need to perform a calculation based on table data, create a procedure within the table object. This makes your code reusable across different pages and reports.

Callout: The Power of Procedures in Tables One of the most overlooked features of AL tables is the ability to add your own procedures. If you have a calculation that determines the "Depreciated Value" of a vehicle, do not write that logic in a page. Put it in a procedure inside the Vehicle table. This way, if you ever need to show that value on a report, an API, or a different page, you can simply call Vehicle.GetDepreciatedValue() instead of rewriting the logic. This is the essence of clean, modular code.


Not read yet

Working with Field Groups

Field groups are often ignored by beginners, but they are essential for a professional user experience. By defining a DropDown field group, you control what the user sees when they are searching for a record in a lookup field.

fieldgroups
{
    fieldgroup(DropDown; "No.", Description)
    {
    }
}

When a user clicks the lookup button for a Vehicle No. field in a sales order, the system will show the No. and the Description. Without this fieldgroup definition, the system might only show the primary key, which makes it difficult for users to identify the correct record. Always define a DropDown group for every master data table you create.


Handling Data Migration and Upgrades

When you build a table, you must consider the future. What happens if you need to change a field length or add a new field later?

  • Adding Fields: This is safe. You can add as many fields as you like to a table or table extension without breaking existing data.
  • Changing Field Lengths: Be careful. You can generally increase the length of a Text field, but decreasing it can lead to data loss or errors if existing data exceeds the new length.
  • Renaming Fields: Never rename a field by changing its name in the code. This will cause the system to think you deleted the old field and added a new one, resulting in the loss of all data in that column. If you must rename a field, use the ObsoleteState property to deprecate the old field and create a new one, then write a migration script to move the data.

Not read yet

Troubleshooting Common Errors

"The field ID already exists"

This error occurs when you define a field with an ID that is already present in the base table or another extension. Check the base table definition or your other extensions to find a free ID.

"Data type mismatch"

This usually happens when you try to assign a value of one type to a field of another type (e.g., trying to put a Text value into a Decimal field). Always ensure your data types are compatible before assignment.

"TableRelation does not exist"

If you get this error, you have likely mistyped the name of the table or the field in your TableRelation property. Double-check the spelling and ensure that the table you are referencing is actually available in your project dependencies.


Comprehensive Key Takeaways

As we conclude this lesson on building and extending tables, let’s summarize the most vital concepts to carry forward into your development practice:

  1. Tables are the Foundation: Everything in Business Central relies on your table design. Spend time architecting your data structure before writing a single line of interface code.
  2. Extensions are Mandatory: Never modify base tables directly. Always use Table Extensions to add functionality, ensuring your solution remains compatible with future platform updates.
  3. Referential Integrity is Key: Use the TableRelation property to link your data. This is the most efficient way to maintain data quality and provide users with helpful lookups.
  4. Data Classification is Essential: Always classify your fields for GDPR compliance. It is a non-negotiable standard in modern development.
  5. Encapsulate Logic: Use procedures within your table objects to house business logic. This keeps your code modular, reusable, and easy to test.
  6. Field Groups Improve UX: Don't forget fieldgroups. A well-defined DropDown group makes the system much more intuitive for end users.
  7. Plan for the Future: Think about how your table structure will evolve. Avoid breaking changes by carefully managing field IDs and using deprecation strategies when necessary.

By mastering these concepts, you move beyond simply writing code that "works" and start building professional, scalable solutions that align with the architecture of Business Central. Data modeling is the bridge between business requirements and technical implementation; treat it with the care and rigor it deserves. As you continue your journey, keep experimenting with different table configurations and observing how they impact the overall behavior of the system. The more comfortable you become with the data layer, the more effective you will be as an AL developer.

Not read yet

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