Skip to content

Incorrect SQL code generated #26

Open
@SimonSntPeter

Description

@SimonSntPeter

Came to this from the HN discusson 'against SQL'.
In https://github.com/erezsh/Preql

The translation of this...

print Continent {
... // Include existing fields
density: population / area // Create new a field

} order{^density}

...to this...

WITH subq_1(id, name, area, population, density) AS (
SELECT id, name, area, population, (CAST(population AS float) / area) AS density
FROM Continent
ORDER BY density DESC)
SELECT * FROM subq_1

...is almost certainly wrong. Certainly it is in mssql and likely every other DB. The order by is not honoured except in the last (outermost) select statement.

If tried in MSSQL you correctly get this error:

Msg 1033, Level 15, State 1, Line 6
The ORDER BY clause is invalid in views, inline functions, derived tables, subqueries, and common table expressions, unless TOP, OFFSET or FOR XML is also specified.

Any 'order by' in a subquery, including a CTE, does not guarantee any ordering at all.

It needs to be

WITH subq_1(id, name, area, population, density) AS (
SELECT id, name, area, population, (CAST(population AS float) / area) AS density
FROM Continent)
SELECT * FROM subq_1
ORDER BY density DESC

(which mssql accepts without complaint)

HTH

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