Skip to content

(SELECT ... LIMIT 1) UNION ALL SELECT ... applies the LIMIT to the whole result #2711

Open

Description

@mathiasrw

A parenthesised first SELECT with its own ORDER BY … LIMIT in a set operation has that LIMIT applied to the whole result, unless the other SELECT also has an ORDER BY or LIMIT. Rows are lost and there is no error.

Measured on develop (94ccf84), A = 3, 1, 2 and B = 9, 8, next to SQLite 3.43 (which needs SELECT * FROM (…) around the parenthesised part):

Query AlaSQL SQLite
(SELECT a FROM A ORDER BY a LIMIT 1) UNION ALL SELECT a FROM B 1 1, 9, 8
(SELECT a FROM A ORDER BY a LIMIT 1) UNION ALL (SELECT a FROM B ORDER BY a LIMIT 1) 1, 8 1, 8
SELECT a FROM A UNION ALL (SELECT a FROM B ORDER BY a LIMIT 1) 3, 1, 2, 8 3, 1, 2, 8

Cause

The grammar rule LPAR Select RPAR UnionClause OrderClause LimitClause (#2395) returns the inner SELECT itself and adds the outer ORDER BY / LIMIT to it, so the statement no longer knows which clause belonged to the first SELECT. queryfn3 (src/38query.js) then guesses: it applies the first SELECT's ORDER BY / LIMIT before the set operation only when another branch also has one (unionBranchHasOrder).

Direction

Keep the parenthesised SELECT's own ORDER BY / LIMIT apart from the statement's in the parser (for example on the branch, as the other branches already have them), and apply each where it belongs, without the guess. A lost row is a wrong result, so this can go into 4.x.

Related: #1965, #2395, #2605, #2608.

Activity

  1. added this to the v4.x Focus milestone on Oct 20, 2026
  2. mathiasrw commented on Oct 20, 2026

    @mathiasrw
    MemberAuthor

    Part of the set operation design in #2718.

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

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions