Design query objects for stable results

Completed

A stable query starts with a clearly defined projection: the tables and fields that satisfy a consumer's requirement. You also need to understand when execution begins and what a query result can do.

Define the query projection

A query contains data items that identify source tables, columns that expose fields, and optional filters that define selection criteria. Give the query and its columns names that describe their meaning because AL consumers refer to those names.

QueryType distinguishes a normal query from an API query. A normal query supports AL consumption and report datasets. An API query exposes a query through an API and requires API properties such as publisher, group, version, entity name, and entity set name. Choose the type according to the consumer rather than treating the two types as interchangeable.

Query results are read-only. A query doesn't provide an updateable record buffer. Use a record variable when you need to modify source records.

Control execution and result expectations

Open executes the query, but it doesn't read the first row. Call Read to advance to a result row. Continue calling Read until it returns false, then call Close to end the execution and initialize the query instance. Configure filters before Open.

Ordering helps make a result predictable for a consumer, but a query isn't a permanently live view. After source data changes, rerun the query to get a fresh projection. Don't assume a previously opened result updates dynamically.

OrderBy sorts the result by one or more exposed columns. TopNumberOfRows limits how many rows the query returns. When you combine them, the query sorts before it applies the row limit, so choose an order that matches the meaning of the top result. Without an intentional order, a top-row limit doesn't define which qualifying rows the consumer receives.

For more information, see Query object and Query data type.