Skip to content

Adding limit to a UNION SQL outputs incorrect sql in "tsql" dialect #4786

Closed
@aman-wisdom

Description

@aman-wisdom

Description
The issue exists in the latest version of sqlglot 26.6.0. When applying limit operation on a Union node and converting to T-SQL, we get an expression which is invalid in T-SQL.

Fully reproducible code snippet

>>> parse_one("select count(*) from a union select count(*) from b", dialect="tsql").limit(5).sql(dialect="tsql")
'SELECT TOP 5 * FROM (SELECT COUNT(*) FROM a UNION SELECT COUNT(*) FROM b) AS _l_0'

While this looks correct, it throws syntax error as shown in the image below. Note that the union query works as a standalone but not when placed within parantheses. (See error message at the bottom of the image.)

Image

Official Documentation
Couldn't find the official documentation explaining this situation, but it should be reproducible anywhere I think.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions