{"title":"AL database methods and performance on SQL Server","url":"https://jonas-paprotka.de/docs/dev-itpro/administration/optimize-sql-al-database-methods-and-performance-on-server/","by":"JOP-AL","license":"Copyright (c) Microsoft Corporation. CC BY 4.0, https://creativecommons.org/licenses/by/4.0/; code samples MIT. From https://learn.microsoft.com/en-us/dynamics365/business-central/dev-itpro/administration/optimize-sql-al-database-methods-and-performance-on-server, MicrosoftDocs/dynamics365smb-devitpro-pb at 828b6ee (2026-11-19). Changed: includes filled in, links to this site, and for agents shortened without dropping a fact.","credit":"Microsoft Corporation, CC BY 4.0","origin":"https://learn.microsoft.com/en-us/dynamics365/business-central/dev-itpro/administration/optimize-sql-al-database-methods-and-performance-on-server","source":{"name":"Business Central developer and IT pro docs","repo":"https://github.com/MicrosoftDocs/dynamics365smb-devitpro-pb","commit":"828b6ee72fcd75755627cd6011f3d20899217ab2","date":"2026-11-19"},"checked":"2026-11-19","description":"Read about the relationship between basic database methods in AL and SQL statements in Business Central.","date":"2025-04-01","meta":{"topic":"article"},"outline":[{"level":2,"title":"Get, Find, FindSet, and Next","slug":"get-find-findset-and-next","at":97,"chars":2799},{"level":3,"title":"Dynamic result sets","slug":"dynamic-result-sets","at":2186,"chars":710},{"level":2,"title":"CalcFields, CalcSums, and Count","slug":"calcfields-calcsums-and-count","at":2896,"chars":853},{"level":2,"title":"SetAutoCalcFields","slug":"setautocalcfields","at":3749,"chars":2267},{"level":2,"title":"Insert, Modify, Delete, and LockTable","slug":"insert-modify-delete-and-locktable","at":6016,"chars":1782},{"level":2,"title":"ModifyAll and DeleteAll","slug":"modifyall-and-deleteall","at":7798,"chars":593},{"level":2,"title":"Related information","slug":"related-information","at":8391,"chars":1138}],"text":"This article describes the relationship between basic database methods in AL and SQL statements.\n## Get, Find, FindSet, and Next\nThe AL language offers several methods to retrieve record data. In Dynamics 365 Business Central, records are retrieved using multiple active result sets (MARS). Generally, retrieving records with MARS is faster than with server-side cursors. Additionally, each function is optimized for a specific purpose. To achieve optimal performance, you must use the method that is best suited for a given purpose.\n Record.Get is optimized for getting a single record based on primary key values.\n Record.Find is optimized for getting a single record based on the primary keys in the record and any filter or range that is set.\n Record.Find('-') and Record.Find('+') are optimized for reading primarily from a single table when the application might not read all records. Find('-') is implemented by issuing a self-tuning TOP X call, where X can change over time, based on statistics of the number of rows read.\n  The following are examples of scenarios in which you should use the Find('-') function to achieve optimal performance:\n   Before you post a general journal batch, you must check all journal lines for validity and verify that all lines balance. After the first line when an error is found, you don't have to retrieve the rest of the rows.\n   if you want to fulfill multiple outstanding orders from a recent purchase but you don't know how many orders are covered by the purchase.\n Record.FindSet(ForUpdate, UpdateKey) is optimized for reading the complete set of records in the specified filter and range. The UpdateKey parameter doesn't influence the efficiency of this method in Dynamics 365 Business Central, such as it did in Microsoft Dynamics NAV 2009.\n  FindSet isn't implemented by issuing a TOP X call.\n Record.FindFirst and Record.FindLast are optimized for finding the single first or last record in the specified filter and range.\n Record.Next can be called at any time. However, if Record.Next isn't called as part of retrieving a continuous result set, then Business Central calls a separate SQL statement in order to Find the Next record.\n### Dynamic result sets\nAny result set that is returned from a call to the Find methods discussed in the previous section is dynamic. That means that the result set is guaranteed to contain any changes that you make further ahead in the result set. However, this feature comes at a cost. If any modifications are made to a table being traversed, then Business Central might have to issue an extra SQL statement to guarantee that the result set is dynamic.\nThe following code shows how records are most efficiently retrieved. FindSet is the most efficient method to use because this example reads all records.\n```al\nif FindSet() then\n    repeat\n        // Insert statements to repeat.\n    until Next() = 0;\n```\n## CalcFields, CalcSums, and Count\nEach call to the CalcFields, CalcField, CalcSum, or CalcSums methods requires a separate SQL statement unless the client calculates the same sum or another sum using the same SumIndexFields or filters in a recent operation. In that case, the result is cached.\nEach CalcFields or CalcSums request should be confined to use only one SIFT index. The SIFT index can only be used if:\n All requested sum-fields are contained in the same SIFT index.\n The filtered fields are part of the key fields specified in the SIFT index containing all the sum fields.\nIf neither of these requirements is fulfilled, then the sum is calculated directly from the base table.\nIn Dynamics 365 Business Central, SIFT indexes count records in a filter if a SIFT index contains all filtered fields in the key fields defined for the SIFT index.\n## SetAutoCalcFields\nIt's a common task to retrieve data and request calculation of associated FlowFields. The following example traverses customer records, calculates the balance, and marks the customer as blocked if the customer exceeds the maximum credit limit. Note: the Customer record and associated fields are imaginary in the following examples.\n> NOTE\n> Starting in Business Central 2025 release wave 1, the SetAutoCalcFields is also available on the RecordRef data type.\n```al\nif Customer.FindSet() then\n    repeat\n        Customer.CalcFields(Balance);\n        if Customer.Balance > MaxCreditLimit then begin\n            Customer.Blocked := true;\n            Customer.Modify();\n        end else\n            if Customer.Balance > LargeCredit then begin\n                Customer.Caution := true;\n                Customer.Modify();\n            end;\n    until Customer.Next() = 0;\n```\nIn Dynamics 365 Business Central, you can do this operation faster. First, we set a filter on the customer. In Dynamics 365 Business Central, setting a filter on a record is translated into a single SQL statement.\n```al\nCustomer.SetFilter(Balance, '>%1' , LargeCredit);\nif Customer.FindSet() then\n    repeat\n        Customer.CalcFields(Balance);\n        if Customer.Balance > MaxCreditLimit then begin\n            Customer.Blocked := true;\n            Customer.Modify();\n        end else\n            if Customer.Balance > LargeCredit then begin\n                Customer.Caution := true;\n                Customer.Modify();\n            end;\n    until Customer.Next() = 0;\n```\nIn the previous example, an extra call to CalcFields still must be issued for the code to be able to check the value of Customer.Balance. In Dynamics 365 Business Central, you can optimize this further by using the new SetAutoCalcFields method.\n```al\nCustomer.SetFilter(Balance, '>%1', LargeCredit);\nCustomer.SetAutoCalcFields(Balance)\nif Customer.FindSet() then\n    repeat\n        if Customer.Balance > MaxCreditLimit then begin\n            Customer.Blocked := true;\n            Customer.Modify();\n        end else\n            if Customer.Balance > LargeCredit then begin\n                Customer.Caution := true;\n                Customer.Modify();\n            end;\n    until Customer.Next() = 0;\n```\n## Insert, Modify, Delete, and LockTable\nEach call to Insert, Modify, or Delete methods requires a separate SQL statement. If the table that you Modify contains SumIndexes, then the operations are slower. As a test, select a table that contains SumIndexes and execute 100 Insert, Modify, or Delete operations to measure how long it takes to maintain the table and all its SumIndexes.\nCloning a record before a Modify or Delete operation issues an extra SQL statement, since the SQL SELECT query is restarted every time the table is cloned. A record is cloned when calling the ../developer/methods-auto/record/record-copy-method, when using a RecordRef or when the record isn't passed with the var parameter within a function.\nThe following code samples lead to a bad performance, since they'll issue an extra SQL statement per record in the table.\n```al\nif MyTable.FindSet() then\n    repeat\n        MyTableCopy.Copy(MyTable);\n        // ...\n        MyTableCopy.Modify(); // or .Delete();\n    until MyTable.Next() = 0;\n```\n```al\nif MyTable.FindSet() then\n    repeat\n        RecRef.GetTable(MyTable);\n        // ...\n        RecRef.Modify(); // or .Delete();\n    until MyTable.Next() = 0;\n```\nInstead, you should use the following code, which only requires an extra SQL statement:\n```al\nRecRef.Open(Database::\"My Table\");\nif RecRef.FindSet(true) then\n    repeat\n        // ...\n        RecRef.Modify(); // or .Delete();\n    until RecRef.Next() = 0;\n```\n```al\nif MyTable.FindSet(true) then\n    repeat\n        MyTable.Modify(); // or .Delete();\n    until MyTable.Next() = 0;\n```\nThe LockTable method doesn't require any separate SQL statements. It causes any subsequent reading from any tables to be done with an update lock. See ../developer/methods-auto/record/record-locktable-method.\n## ModifyAll and DeleteAll\nUsing ModifyAll and DeleteAll can improve performance by limiting the amount of SQL calls needed. However, be aware that ModifyAll and DeleteAll revert to individual calls if any of the following conditions exist:\n There's trigger code on the table.\n There are event subscribers to the following events: OnBeforeModify, OnAfterModify, OnGlobalModify, OnBeforeDelete, OnAfterDelete, OnGlobalDelete, and OnDatabaseModify.\n Security filtering is active.\n The table contains Media or MediaSet data type fields.\n There are fields that are added through companion tables.\n## Related information\noptimize-sql-table-keys-and-performance\noptimize-sql-bulk-inserts\n../developer/methods-auto/record/record-get-method\n../developer/methods-auto/record/record-find-method\n../developer/methods-auto/record/record-next-method\n../developer/methods-auto/record/record-findset-boolean-method\n../developer/methods-auto/record/record-findfirst-method\n../developer/methods-auto/record/record-findlast-method\n../developer/methods-auto/record/record-calcfields-method\n../developer/methods-auto/fieldref/fieldref-calcfield-method\n../developer/methods-auto/record/record-calcsums-method\n../developer/methods-auto/fieldref/fieldref-calcsum-method\n../developer/methods-auto/record/record-setautocalcfields-method\n../developer/methods-auto/record/record-insert--method\n../developer/methods-auto/record/record-modify-method\n../developer/methods-auto/record/record-modifyall-method\n../developer/methods-auto/record/record-delete-method\n../developer/methods-auto/record/record-deleteall-method\n../developer/methods-auto/record/record-locktable-method\n../developer/devenv-events-in-al\nUsing Security Filters<../security/security-filters>"}