[
https://issues.apache.org/jira/browse/DERBY-6008?page=com.atlassian.jira.plugin.system.issuetabpanels:comment-tabpanel&focusedCommentId=13526244#comment-13526244
]
Knut Anders Hatlen commented on DERBY-6008:
-------------------------------------------
Hi Bryan,
I think ORDER BY in sub-queries was added in SQL:2008, so you're right it's
quite new. And you're also right that ORDER BY doesn't make much sense on its
own in a sub-query of a set operation, as the top-level set operation doesn't
guarantee that the ordering of the sub-queries is preserved in the final
result. However, in combination with FETCH and OFFSET clauses, it starts making
sense. If you for example want to see a list of all countries that are among
the 10 largest countries in the world both in area and in population, you might
be able to express that as:
(SELECT NAME FROM COUNTRIES ORDER BY POPULATION DESC FETCH FIRST 10 ROWS ONLY)
INTERSECT
(SELECT NAME FROM COUNTRIES ORDER BY AREA DESC FETCH FIRST 10 ROWS ONLY)
Here, the ORDER BY clauses do matter, as FETCH FIRST needs ordering in order to
tell what FIRST actually means. Without the ORDER BY clauses, each sub-query
would return no more than ten rows, but it would be undefined which ten rows.
> Allow ORDER BY and FETCH/OFFSET in set operands
> -----------------------------------------------
>
> Key: DERBY-6008
> URL: https://issues.apache.org/jira/browse/DERBY-6008
> Project: Derby
> Issue Type: Improvement
> Components: SQL
> Reporter: Dag H. Wanvik
> Assignee: Dag H. Wanvik
> Attachments: derby-6008-a.diff, derby-6008-a.stat, derby-6008-b.diff,
> derby-6008-b.stat, derby-6008-c.diff, derby-6008-c.stat
>
>
> Currently, Derby doesn't allow ORDER BY nested in a set operand, e.g. in the
> following construct:
> (select i from t1 order by j offset 1 row) union
> (select i from t2 order by j desc offset 2 rows)
> This is allowed by the standard, as far as I can understand, cf. this quote
> from section 7.12 in SQL 2011:
> <query expression body> ::=
> <query term>
> | <query expression body> UNION [ ALL | DISTINCT ]
> [ <corresponding spec> ] <query term>
> | <query expression body> EXCEPT [ ALL | DISTINCT ]
> [ <corresponding spec> ] <query term>
> <query term> ::=
> <query primary>
> | <query term> INTERSECT [ ALL | DISTINCT ]
> [ <corresponding spec> ] <query primary>
> <query primary> ::=
> <simple table>
> | <left paren> <query expression body>
> [ <order by clause> ] [ <result offset clause> ] [ <fetch first clause>
> ] <right paren>
> I.e. the left paren chooses the second alternative in the production for
> <query primary>.
--
This message is automatically generated by JIRA.
If you think it was sent incorrectly, please contact your JIRA administrators
For more information on JIRA, see: http://www.atlassian.com/software/jira