Skip to content

Sort NULL and mixed values in ORDER BY as SQLite, and honour NULLS FIRST and NULLS LAST, with a dialect keeping the old order #3172

Backlog

Description

@mathiasrw

What happens today

After #3165 and #2693 the ORDER BY comparator still uses the rules of compileOrder (src/select/orderby.js). It compares (a[key]||''), so NULL, undefined, 0 and '' all count as '' and sort between negative and positive numbers. .valueOf() is added only for columns declared DATE, DATETIME, DATETIME2, STRING or NUMBER, so a column of numbers and text has no defined order.

alasql('CREATE TABLE p (n INT); INSERT INTO p VALUES (2), (NULL), (-1), (0)');
alasql('SELECT COLUMN n FROM p ORDER BY n'); // [-1, null, 0, 2]    SQLite: [null, -1, 0, 2]

This also fixes #3141.

What to change

  1. The ORDER BY comparator calls alasql.cmp from Make the standard comparison level the default, with dates by value and SQLite's order across types #3171 for each sort key. NULL and undefined are one NULL. Numbers come before text, and dates compare by time value, whatever the declared type.
  2. The parser reads NULLS FIRST and NULLS LAST with and without ASC or DESC.
  3. Each sort item carries nulls: 'first' | 'last'. When the query does not say, the default comes from the rule nullOrder of Rules that differ between dialects become named rules chosen when a statement is compiled #3170. With sqlite (the new default) NULLs come first ascending and last descending.
  4. With nullOrder: 'v4' the comparator keeps today's (a||'') rules. Add it to alasql/dialect/v4.
  5. Keep the sort stable.
  6. COLLATE NOCASE applies only to text.

What stays the same

  • Clean numbers or clean text without NULLs sort as before.
  • With alasql/dialect/v4 every ORDER BY gives the 4.x order.
  • In the default, the place of NULL, undefined, 0 and '' changes, and so does the order of mixed columns, also in GROUP_CONCAT(... ORDER BY ...) and set operations.

Done when

  • A new test file named after this issue covers the example above in both directions, the mixed column 2, NULL, 0, missing, -1, 'b', '10' (SQLite gives [null, null, -1, 0, 2, '10', 'b']), NULLS FIRST and NULLS LAST with and without a direction, dates in an undeclared column, and the same queries with alasql/dialect/v4.
  • The ORDER BY matrix in the dialect test against SQLite covers NULL, mixed types and NULLS FIRST and NULLS LAST, and their expected differences are removed.
  • The full test suite and the CI checks (dialect test, parity check, run-state check, binding check) pass, and the pull request lists every parity difference.

Fixes

Fixes #2812, #3141.

Depends on

#3165, #2693, #3170, #2588, #3171

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions