Skip to content

UNION removes duplicates in N × M time and keeps duplicates of the second SELECT #2744

Open

Description

@mathiasrw

UNION compares every row with every row kept so far, so its time grows with the square of the rows. It also keeps duplicates that are inside the second SELECT.

const tab = (from, n) => Array.from({length: n}, (_, i) => ({id: from + i, val: 'v' + ((from + i) % 1000)}));
const a = tab(0, 8000), b = tab(6400, 8000);
alasql('SELECT * FROM ? UNION SELECT * FROM ?', [a, b]);                             // 3095 ms
alasql('SELECT DISTINCT * FROM (SELECT * FROM ? UNION ALL SELECT * FROM ?)', [a, b]); // 8 ms, same rows

alasql('SELECT * FROM ? UNION SELECT * FROM ?', [[{id: 2}], [{id: 1}, {id: 1}]]);   // [{id:1},{id:1},{id:2}]

Measured on develop (Bun 1.4.3): 2,000 rows per side take 216 ms, 4,000 take 761 ms, 8,000 take 3,095 ms. The benchmark dimension set-ops (#2742) has three tables of 30,000 rows: UNION ALL takes 14 ms, UNION 42 seconds (89 seconds with 10 columns).

Cause: arrayUnionDeep in src/15utility.js starts from a copy of one side and, for each row of the other side, calls deepEqual against every row kept so far, without stopping at the first match. SELECT DISTINCT already removes duplicates with a key per row. EXCEPT and INTERSECT (arrayExceptDeep, arrayIntersectDeep) have the same N × M loop.

Activity

  1. mateuscmtropical commented on Nov 11, 2026

    @mateuscmtropical
    Contributor

    Hi, I'd like to work on this one.

  2. mateuscmtropical commented on Nov 11, 2026

    @mateuscmtropical
    Contributor

    Hi, I've opened a PR for this: #3051

  3. modified the milestones: v4.x Focus, v5.0.0 on Nov 15, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions