MSBA-343 · Lesson 4 of 12 · 20 min
Set-based operations
▶ Video coming soon A video version of this lesson is on the way.
The receipt trace had shown two kinds of waste: a select repeated once per purchase line, and an insert repeated once per purchase line. Desmond said both came from the same habit. Developers who learned programming on loops think in records: fetch one, look at it, change it, write it back, fetch the next. Databases think in sets. A database can update ten thousand rows with one statement faster than X++ can update ten rows one at a time, because every round trip between the application server and the database costs time no matter how little work it carries. This clinic was about learning to think in sets, and about knowing when not to.
Row-by-row and set-based
A row-based operation handles one record per database call. A while select loop that updates each record it reads makes at least two calls per row, one to fetch and one to write, and more if the update method or event handlers do further work. A set-based operation sends one statement that affects many rows. X++ has three set-based statements for writing data: insert_recordset, update_recordset and delete_from. It also has two classes that buffer inserts and send them in batches: RecordInsertList and RecordSortedList.
The three statements
insert_recordset copies rows from one or more tables into another in a single statement, with a select that can join and filter. It is ideal for building temporary tables for reports, staging data, or queueing work. update_recordset changes fields on every row that matches its where clause, and the new values can come from expressions or from joined tables. delete_from removes every row that matches its where clause, with optional exists or notexists joins.
// Row-by-row: one fetch and one write per line
while select forupdate queue
where queue.Status == CRAlertStatus::Pending
&& queue.CreatedDateTime < cutoff
{
queue.Status = CRAlertStatus::Expired;
queue.update();
}
// Set-based: one statement
update_recordset queue
setting Status = CRAlertStatus::Expired
where queue.Status == CRAlertStatus::Pending
&& queue.CreatedDateTime < cutoff;The nightly cleanup job from MSBA-341 deleted alerts older than ninety days. Prudence had written it as a while select with a delete inside. Desmond rewrote it with delete_from and a where clause on the creation date, and the job went from eleven minutes on the rehearsal data to under a second. Prudence asked why the original had not seemed slow in her developer environment. The answer was that her environment had forty alerts. The rehearsal had a hundred and twenty thousand.
When set-based falls back to row-by-row
Set-based statements have a catch that every developer must know. The X++ runtime turns them into single SQL statements only when nothing needs to run for each row. If something does, the runtime quietly falls back to processing the rows one by one, so the code still behaves correctly but loses the speed. The documented conditions include a table whose insert, update or delete method has been overridden, tables with database logging enabled for the operation, alerts set up on the table, and event handlers subscribed to the table's data events. Some table types and configurations, such as certain temporary tables or tables that use valid time state, add their own conditions.
This is why the alert queue inserts in the receipt trace were slow even after Prudence's first attempt to fix them. She had replaced the loop with insert_recordset, but the queue table had an onInserted data event handler from MSBA-341 and an administrator had enabled the database log on it during testing. Both forced row-by-row processing. The fix needed two decisions, not one line of code.
| Condition | Why it forces row-by-row | What can be done |
|---|---|---|
| Overridden insert, update or delete method | The method must run for each record | Move the logic elsewhere, or call skipDataMethods(true) when the logic is not needed |
| Database log enabled for the operation | Each change must be logged | Ask whether the log is needed; skipDatabaseLog(true) only with the auditor's agreement |
| Alerts set up on the table | Each change may trigger an alert | Review alert rules on technical tables |
| Data event handlers subscribed | Each row raises the event | Move the logic, or call skipEvents(true) when handlers must not run |
| Some table types and settings | The runtime cannot express the work in one statement | Check the table type and test with a trace |
The skip methods
A table buffer has methods that tell the runtime to skip the per-row work: skipDataMethods, skipDatabaseLog and skipEvents, each called with true before the set-based statement. They exist for good reasons and they are dangerous for the same reasons. Skipping data methods means the logic in insert or update does not run. Skipping the database log means the change is not audited. Skipping events means subscribers, including ones in models you have never seen, do not hear about the change.
Desmond's rule was that a skip method needs a comment explaining why the skipped work does not matter for this statement, and a reviewer who agrees. For the alert queue, the onInserted handler from MSBA-341 did nothing more than set a timestamp that the insert_recordset could set directly, so the handler was removed and the timestamp moved into the statement. The database log on the queue had been switched on by mistake; Thandeka confirmed that the alert queue was a technical table with no audit value, and the administrator switched the log off. With both causes gone, the insert ran as one statement without any skip method at all. Desmond preferred that outcome: the best skip is the one you do not need.
// Queue an alert for every casting line on the receipt that lacks a certificate.
// One statement; runs set-based because CRInspAlertQueue has no overridden insert,
// no data event subscribers and no database log.
insert_recordset alertQueue (PurchId, LineNumber, ItemId, Status, QueuedDateTime)
select PurchId, LineNumber, ItemId, CRAlertStatus::Pending, now from purchLine
where purchLine.PurchId == _purchId
&& purchLine.CRInspectionRequired == NoYes::Yes
notexists join cert
where cert.PurchId == purchLine.PurchId
&& cert.LineNumber == purchLine.LineNumber;RecordInsertList
Sometimes a loop cannot be avoided, because each row needs X++ logic that SQL cannot express. Inserts in such loops can still be batched. RecordInsertList collects records in memory and sends them to the database in groups when add fills a buffer or when insertDatabase is called. RecordSortedList does the same but keeps records sorted by a key, which is useful when the order matters or duplicates must be found before insert. Both reduce round trips without changing the logic. Like insert_recordset, they fall back to single inserts when the table needs per-row processing.
Prudence used RecordInsertList in the warranty registration job, which read serial numbers from shipped sales lines, calculated each warranty's end date with the CRPumpWarrantyCalculator class from the first clinic series, and inserted a warranty per serial number. The calculation needed X++, so the loop stayed, but the inserts went out in batches.
Better queries
Not every improvement is a set-based statement. Many come from asking the database for less. Desmond went through his short list with Prudence, and she applied each item to code from the earlier clinics.
Field lists. A select without a field list fetches every column. A select that names only the fields it uses moves less data. The certificate lookup only needed RecId and Status. Be careful with field lists on buffers that are later updated or passed to methods expecting other fields; a field that was not selected is empty, not missing.
firstonly. When code needs one record, select firstonly tells the database to stop after the first match. Find methods on tables use it.
Joins instead of nested selects. A select inside a while select runs once per outer row. A join, or an exists join when only the existence of a related row matters, does the work in one statement. The receipt rule's find on PurchTable for every line was replaced by reading the vendor once, before the loop.
Indexes that match the where clause. Lesson 3 covered this; a query that filters on fields no index starts with will scan.
Query hints. X++ and the query classes allow hints such as forceLiterals, forcePlaceholders and index hints. They change how the statement is sent or which index the database is asked to prefer. Microsoft discourages most of them in normal code, because the database's own optimizer usually chooses better, and index hints are ignored unless they have been enabled in the environment. Desmond's rule was that a hint needs a trace that proves it helps and a comment that explains why.
Temporary tables
Reports and multi-step processes often need working storage. Finance and operations apps offer two kinds of temporary table. TempDB tables are created in the database's temporary database for the session, so they can be joined to regular tables and filled with insert_recordset. InMemory tables live in the application server's memory, which suits small sets of rows used by one process, but they cannot be joined to database tables in a single statement and they become slow when they grow large. For report data providers that collect thousands of rows by joining transaction tables, TempDB is almost always the right choice. The weekly casting report from MSBA-341 already used a TempDB table; Prudence checked that it was filled with insert_recordset rather than a loop.
When row-based is right
Set-based statements are not always the answer. When each row needs business logic that SQL cannot express, when standard validation must run, or when a set is genuinely small, row-based code is clearer and the cost is negligible. Standard business processes, such as posting, often must run their validations and events per record, and bypassing them with set-based statements and skip methods would break both data integrity and other models' extensions. The MB-500 outline asks developers to assess when to use each. Desmond's version of the assessment had three questions: how many rows, in the worst realistic case; what must run for each row; and who relies on the events or logging that a skip would suppress.
Transactions and batch work
Set-based statements change many rows inside one transaction. Large transactions hold locks for longer and can block other users. For a cleanup of a hundred thousand alerts, one delete_from is fine at night. For a nightly job that updates millions of inventory rows, it might be better to split the work into chunks with their own transactions, or into batch tasks that run in parallel. The batch framework lets a job create several tasks, each processing one bundle of work, so that several batch threads share the load. Desmond's alert job from MSBA-341 already limited each run to five hundred alerts; he kept that limit, because it bounded how long each run could hold locks.
Measuring the change
A set-based rewrite is a change like any other, and Desmond asked for the same evidence. Prudence traced the alert queue insert before and after each step. The first rewrite looked better in code and was no faster, and the trace showed why: the Call Tree still listed one insert per row beneath the insert_recordset, which is what a fallback looks like. Only after the handler and the database log were gone did the trace show a single statement. Without the trace she would have merged code that looked set-based and behaved row by row.
She also checked the result, not only the speed. A set-based statement that selects the wrong rows is fast and wrong. Her test compared the queue contents after the new statement with the contents the old loop produced for the same receipt, line by line, and lesson 6 turns that comparison into permanent unit tests.
Set-based code and other people's extensions
Prudence asked one more question: if Cobalt Ridge used skip methods on a standard table, who would notice? Desmond's answer was that nobody would notice until something broke. An independent software vendor's model installed later might subscribe to the same table's events to keep its own data in step. A skipEvents call in Cobalt Ridge code would silently starve that model of the events it relied on, and the failure would appear in the vendor's feature, far from the cause. For standard tables, Desmond's rule was stricter: no skip methods at all without a design review, and a comment naming the events, logs and methods that would not run.
Worked problem
Speeding up the nightly cleanup
The nightly job deletes alerts older than ninety days from CRInspAlertQueue with a while select loop. On rehearsal data it takes eleven minutes. How should Prudence change it?
Show solution
- Trace the job with rehearsal data to confirm that the loop of deletes is where the time goes.
- Check the table for overridden delete methods, data event subscribers, alerts and database logging.
- Remove the accidental database log setting with Thandeka's agreement, since the queue has no audit value.
- Replace the loop with delete_from and a where clause on the creation date.
- Trace again to confirm that the statement ran set-based and that the job now completes quickly.
Answer: With nothing forcing per-row processing, one delete_from replaces a hundred thousand round trips, and the trace proves that it ran as a single statement.
Common mistakes
MistakeAssuming update_recordset is always one SQL statement.
InsteadCheck for overridden methods, events, alerts and logging that force row-by-row processing.
MistakeCalling skipDataMethods or skipEvents to make a statement fast without asking what is skipped.
InsteadUse skip methods only with a reason in a comment and a reviewer's agreement.
MistakeRunning a select inside a loop to fetch the same parent record for every line.
InsteadRead it once, or join it.
MistakeUsing InMemory temporary tables for large report data joined to transaction tables.
InsteadUse TempDB tables and fill them with insert_recordset.
Summary and key terms
- Each database round trip costs time, so many single-row calls are slower than one statement for many rows.
- insert_recordset, update_recordset and delete_from act on sets; RecordInsertList batches inserts from loops.
- Overridden data methods, database logging, alerts and event subscribers make set-based statements fall back to row-by-row.
- Skip methods suppress per-row work and need a documented reason; field lists, joins, firstonly and good indexes reduce cost.
- TempDB tables suit report data that is joined and filled set-based; row-based code is right when per-row logic must run.
- Set-based operation
- A statement that changes many rows in one database call.
- insert_recordset
- An X++ statement that inserts rows selected from other tables in one statement.
- RecordInsertList
- A class that buffers inserts and sends them to the database in batches.
- skipDataMethods
- A buffer method that stops overridden insert, update or delete methods from running in a set-based statement.
- TempDB table
- A temporary table stored in the database's temporary area, which can be joined to regular tables.
Practice problems
Work each problem on paper first, then reveal the answer to check.
Name two conditions that make update_recordset fall back to row-by-row.
Show answer
For example, an overridden update method and database logging on the table.
What does a notexists join do in insert_recordset?
Show answer
It selects only rows that have no matching row in the joined table.
Why is InMemory a poor choice for large report data?
Show answer
It cannot be joined to database tables in one statement and slows down as it grows.
Lesson quiz · 5 questions
Score 60% or more to complete this lesson.
Create a free account to save your progress, take quizzes and earn a certificate.