Skip to content

INTERSECT, EXCEPT and UNION compare rows wrongly when both SELECTs have their own ORDER BY #2610

Closed

Description

@Anikesh0001

When both SELECTs of a set operation have their own ORDER BY, INTERSECT, EXCEPT and UNION compare rows incorrectly. INTERSECT finds no common rows, EXCEPT removes nothing, and UNION keeps duplicates. No error is raised. UNION ALL is not affected.

Reproduced on develop (v4.20.1) with alasql.options.cache = false, so this is separate from #2605:

alasql('CREATE TABLE e1 (a INT); INSERT INTO e1 VALUES (1),(2),(3),(4)');
alasql('CREATE TABLE e2 (a INT); INSERT INTO e2 VALUES (1),(5)');
Query alasql Expected
(SELECT a FROM e1 ORDER BY a LIMIT 2) INTERSECT (SELECT a FROM e2 ORDER BY a LIMIT 1) [] [{a:1}]
(SELECT a FROM e1 ORDER BY a) INTERSECT (SELECT a FROM e2 ORDER BY a) [] [{a:1}]
(SELECT a FROM e1 ORDER BY a LIMIT 3) EXCEPT (SELECT a FROM e2 ORDER BY a LIMIT 1) [{a:1},{a:2},{a:3}] [{a:2},{a:3}]
(SELECT a FROM e1 ORDER BY a LIMIT 2) UNION (SELECT a FROM e2 ORDER BY a LIMIT 1) [{a:1},{a:1},{a:2}] [{a:1},{a:2}]

The same queries give the correct result when the SELECTs have only a LIMIT, or no ORDER BY / LIMIT at all.

Cause

queryfn3 in src/38query.js (the pattern added in #2417): when the right operand has its own ORDER BY / LIMIT, the first SELECT is sorted before the set operation. To sort, the code writes the order keys $$$0, $$$1, ... into each row of the first SELECT. The keys are removed only at the end of queryfn3 (query.removeKeys), after the set operation.

arrayUnionDeep, arrayExceptDeep and arrayIntersectDeep (src/15utility.js) compare rows with deepEqual. That returns false when the number of keys differs, so {a:1, $$$0:1} never matches the row {a:1} from the other SELECT.

Direction

Delete the order keys from the first SELECT's rows right after that sort, before the set operation. The final ORDER BY is not applied in this pattern, so nothing reads them afterwards.

Tests: the queries above.

Related: #2414, #2417, #2605.

Activity

  1. added a commit that references this issue on Oct 20, 2026
    632bb35
  2. mathiasrw commented on Oct 21, 2026

    @mathiasrw
    Member

    Fix released as part of v4.21.0

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions