Skip to main content

Order Preservation

With the preserve_insertion_order configuration option set to true, SereneDB preserves the order of rows for many operations, similarly to data frame libraries such as Pandas. The option is false by default, which lets parallel operations return rows in any order unless the query has an ORDER BY.

Example​

Take the following table for example:

SQL
CREATE TABLE tbl AS    SELECT *    FROM (VALUES (1, 'a'), (2, 'b'), (3, 'c')) t(x, y);
SELECT *FROM tbl;
 x | y
---+---
 1 | a
 2 | b
 3 | c

Let's take the following query that returns the rows where x is an odd number:

SQL
SELECT *FROM tblWHERE x % 2 == 1;
 x | y
---+---
 1 | a
 3 | c

Here the row (1, 'a') comes before (3, 'c'), the order the table stores them in. A table does not guarantee that order, whatever the option says; see Insertion Order.

Clauses​

With preserve_insertion_order set to true, the following clauses keep the order of the rows they read:

  • COPY (see Insertion Order)
  • FROM with a single table
  • LIMIT
  • OFFSET
  • SELECT
  • UNION ALL
  • WHERE
  • Window functions with an empty OVER clause
  • Common table expressions and table subqueries as long as they only contain the aforementioned components

The following operations do not guarantee that the row order is preserved:

  • FROM with multiple tables and/or subqueries
  • JOIN
  • UNION
  • USING SAMPLE
  • Whole-table aggregation (the input order, that is, the order in which rows are fed into order-sensitive aggregate functions is not guaranteed unless explicitly specified in the aggregate function)
  • GROUP BY (neither in- nor output order are guaranteed)
  • ORDER BY (specifically, ORDER BY may not use a stable algorithm)
  • Scalar subqueries

Insertion Order​

With preserve_insertion_order set to true, the following components preserve insertion order:

Tables do not honor preserve_insertion_order, also when it is true: a table returns its rows in the order it stores them, which is not the order they were inserted in once a write such as INSERT ... SELECT or COPY runs on several threads. Use ORDER BY when the order of a table's rows matters.

Preservation of insertion order is controlled by the preserve_insertion_order configuration option. This setting is false by default. To change this setting, use:

SQL
SET preserve_insertion_order = false;