Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CTE after UNION ALL

This query does not work:

WITH a AS 
(SELECT 1 AS c1)
SELECT
    *
FROM
    a 


UNION ALL

WITH b AS 
(SELECT 1 AS c1)
SELECT
    *
FROM
    b

Could you help, please?

Real query uses tables, but it is not essential in the example.

Many thanks

like image 727
Maxim Eliseev Avatar asked Mar 13 '26 12:03

Maxim Eliseev


2 Answers

;WITH a AS 
(SELECT 1 AS c1), 
b AS 
(SELECT 1 AS c1)
SELECT
    *
FROM
    a 
UNION ALL
SELECT
    *
FROM
    b
like image 171
d89761 Avatar answered Mar 16 '26 01:03

d89761


Simple answer: you're breaking the query ;-)

Let me explain:

  • The UNION key word takes 2 "queries" and makes them into one.
  • The WITH key word can't be used inside a query and it is only valid for one query
  • WITH can be used to define multiple CTEs

The result of all of these is that you want to define both of the CTEs (a & b) before the UNION query. Putting the WITH inside the UNION query breaks the UNION (since WITH is always outside of (before) a query.

like image 23
Gidil Avatar answered Mar 16 '26 00:03

Gidil