Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Emulate nested set operators in databases that don't support them natively #3579

Closed
lukaseder opened this issue Aug 22, 2014 · 0 comments
Closed

Comments

@lukaseder
Copy link
Member

In standard SQL, set operators can be nested as such:

SELECT 1
UNION (
   SELECT 2
   INTERSECT (
      SELECT 2
      UNION ALL
      SELECT 3
   )
)

This is essentially specified by the SQL standard as such:

<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>

Where a <query primary> can be simply another <query expression> wrapped in parentheses, and in fact ORDER BY, OFFSET, and FETCH are allowed too, this way.

Some databases, however, do not support parentheses around subselects at all, in the context of set operations. These are:

  • Derby
  • Firebird
  • MariaDB
  • MS Access
  • MySQL
  • SQLite
  • Sybase ASE

Support can be emulated via derived tables, which are pretty well supported across vendors:

SELECT 1
UNION 
SELECT * FROM (
   SELECT 2
   INTERSECT 
   SELECT * FROM (
      SELECT 2
      UNION ALL
      SELECT 3
   )
)
@lukaseder lukaseder added this to the Version 3.5.0 milestone Aug 22, 2014
lukaseder added a commit that referenced this issue Oct 10, 2014
lukaseder added a commit that referenced this issue Oct 15, 2014
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment