Sorting the table of values in 1C is performed using the method Sort() indicating the order of the columns and the sorting direction, which allows you to structure the data without accessing the database. Unlike queries, where the order of records is determined at the time of selection, working with Table of values requires an explicit call to the ordering algorithm within the object. This action is critical for the correct display of reports, generation of printed forms, or preparation of data for further algorithmic analysis, where the sequence of elements is of fundamental importance.

The main difficulty that developers face is that the sorting method only works on data that is already populated and cannot use database indexes to speed up the process. If you try to sort an empty table or a table that does not have the specified columns, the system will throw a runtime error. Therefore, before calling a method, you must make sure that the structure of the object fully complies with the requirements of the algorithm, and the data types in the cells allow comparison.

The effectiveness of this operation directly depends on the volume of rows processed and the number of criteria applied. When working with large amounts of data (hundreds of thousands of rows), incorrect use of sorting can lead to noticeable delays in the user interface. In such cases, it is recommended to use optimized approaches, including pre-filtering or the use of temporary tables, to minimize the load on the platform's computational thread 1C:Enterprise 8.

Basic Sort Method Syntax

A fundamental tool for organizing data is the method Sort() (or Sort() in the English version of the syntax). It changes the order of rows within the value table itself without creating a new object. The method argument is a string containing a list of column names and the sorting direction for each of them. If direction is not specified explicitly, ascending is used by default.

Syntactically, the call looks like accessing an object and passing a string parameter. For example, the design Table.Sort("Price Descending, Article") will sort the lines first by price from highest to lowest, and lines with the same price - by article in direct order.

⚠️ Attention: An attempt to sort a table by a column that does not exist in its structure will interrupt the code execution and generate an exception. Always check for columns before sorting, especially if the structure is generated dynamically.

For numeric and string data, the algorithm works predictably, but when working with complex types (for example, when one column can contain both numbers and strings), the result may not be obvious. In such situations, the platform applies internal casting rules, which sometimes leads to undesirable ordering of elements. It is recommended to strictly type columns at the stage of their creation.

  • 📊 The method allows you to set up to 10 levels of nested sorting in one line of parameters.
  • 🔄 Changes are applied instantly to the original object; a copy of the data is not created automatically.
  • ⚙️ Keywords “Descending” (Desc) and “Ascending” (Asc) are supported to control the direction.

Sorting by multiple fields at once

In real accounting problems, it is often necessary to organize data according to complex criteria, where one indicator is the primary key, and another is the secondary key. For example, when generating a warehouse report, you must first group goods into warehouses, and within each warehouse, arrange them in descending order of balances. Method Sort copes perfectly with such tasks, allowing you to list fields separated by commas.

The order in which fields are specified on the parameter line is critical. The algorithm first sorts the entire array by the first specified field. Then, within groups of rows with the same first field value, it sorts by the second field, and so on. Violation of the logic of the fields will lead to the fact that the global grouping will be broken, and the data will have to be regrouped again.

Example of complex sorting

Code: TZ.Sort("Counterparty, Agreement, Receipt Date Desc");

// First, all lines are sorted by Account.

// Within each counterparty - according to the Agreement.

// Inside each contract - by date from new to old.

Particular attention should be paid to heterogeneous data. If you're sorting by date, make sure there are no empty values in the column like Undefined, since they can “fly away” to the beginning or end of the sample depending on the platform version and configuration. To guarantee results, it is better to fill such fields with placeholder dates (for example, the beginning of an era) before starting sorting.

Field 1 (Priority) Field 2 (Clarification) Field 3 (Detail) Grouping result
City street House Full address order
Category Price (Descending) Title Products by category, expensive at the top
Date Time Document Number Chronological order of documents
Currency Amount (Descending) - Financial report by currency

Using indexes to speed up searches

Although direct sorting changes the physical order of rows, it is more efficient to use indexes for frequent searches on specific fields. An index in 1C is a special structure that is created on top of a table of values ​​and allows you to quickly find rows without searching through all records. However, it is worth understanding the difference: an index does not sort the table visually, it only speeds up access to data by key.

If your job is to repeatedly search for specific values in sorted order, creating an index may be overkill unless the data size is in the millions of rows. But if you need to change the display order frequently, having an index on the required fields can help implement fast sampling algorithms, although the method Find() It works without it, it’s just slower at larger volumes.

To create an index, use the method Indexes.Add(). Once an index is added, the platform automatically keeps it up to date as data changes. This imposes a small overhead on writing, but significantly speeds up reading. In the context of sorting, this is useful if you plan to select a subset of data that is already logically sorted.

  • 🚀 Indexes speed up the search for specific values, but do not change the traversal order during the loop.
  • 🗂️ You can create compound indexes on multiple columns to optimize complex queries.
  • ⚖️ The balance between write speed and search speed is critical for large tables.
📊 How much data do you sort most often?
Up to 1,000 lines
1,000 - 10,000 lines
10,000 - 100,000 lines
More than 100,000 lines

Optimizing performance at high volumes

When it comes to sorting tens or hundreds of thousands of rows, the standard approach can cause interface freezes. Method Sort is blocking, that is, the user will not be able to work with the program until the operation is completed. In such cases, optimization strategies must be applied to minimize the impact on the user experience.

One effective technique is to use background jobs for heavy computation if sorting is not required immediately on the current thread. It's also worth considering sorting the data at the database query level before loading it into the values ​​table. If the data already comes from the DBMS sorted, additional sorting in 1C may be an unnecessary waste of processor resources.

⚠️ Attention: Do not use a loop through table rows for manual sorting (for example, using the “bubble” method). This will lead to a quadratic increase in execution time and a complete freeze of the program when the data volume exceeds 500 rows.

Another important aspect is data typing. If the columns are declared as String, but contain numbers, the sorting will be done lexicographically (1, 10, 2 instead of 1, 2, 10). Casting types before loading values ​​into a table or using strong typing when creating columns ensures correctness and speed of comparison.

💡

Tip: If you need to frequently sort the same table by different fields, consider creating multiple copies of the value table or using temporary tables with different indexes for each scenario.

Typical errors and ways to resolve them

The most common mistake is trying to sort by columns that were removed or renamed during configuration modification. Code written six months ago may suddenly stop working if the metadata structure has changed. Always update method string parameters Sort when refactoring code.

Another common problem is ignoring locale settings when sorting strings. In different locales, characters may have different weights when compared. For example, the letter "Yo" may be ignored or treated as a separate character. For mission-critical reports where the order of letters has legal significance, it is recommended to use string comparison functions with explicit rules or to standardize the data (such as transliteration) before sorting.

Developers also often forget that sorting is unstable for some data types in certain versions of the platform, although this is rare in modern 1C releases. It is more important to ensure that the numeric fields you are sorting do not contain references to objects that cannot be directly compared. Trying to compare two different document links without explicitly specifying the comparison field (for example, by number) will cause an error.

☑️ Check before starting sorting

Done: 0 / 4

FAQ: Frequently asked questions

Is it possible to sort a table of values by expression rather than by column name?

No, method Sort accepts only existing column names. If you need to sort by a calculated expression (for example, the sum of two columns), you need to first add a new temporary column to the table, calculate the values ​​into it, and then sort by the name of that new column.

How to return the original row order after sorting?

The sorting method is irreversible. To return to the original order, you must either have a saved copy of the table before sorting, or have a column in the table structure with the original ordinal number (index) on which you can perform a reverse sort. Without a pre-prepared key, it is impossible to restore order.

Does sorting a table of values affect the performance of output to a spreadsheet document?

Yes, indirectly. If the table is sorted, output to a spreadsheet document (or screen) may be faster if grouping is used, since the engine won't have to regroup the data itself. However, the sorting process itself takes CPU time, so the balance depends on the specific use case.

What happens if you sort the table associated with the dynamic list form?

Sorting a table of values in code does not automatically affect the display on the form if the table is used as the data source for a dynamic list. To change the order in the user interface, you need to apply sorting to the dynamic list itself or redraw the form element after changing the data in the underlying table.

💡

Key takeaway: Value table sorting is a powerful but resource-intensive tool. Use it consciously, always check for the presence of columns and try to sort the data as close as possible to the source (in the request) to reduce the load on the client application.