Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use a CTE in a left outer join?

I am trying to join a common table expression to an existing table (table1) as follows.

select column1, column2 from table1

left outer join

  ;with cte as (
    select column1, column2 from table2)

  select column1, column2 from cte

on table1.column1 = cte.column1

The errors are:

  1. Incorrect syntax near ';'.
  2. Incorrect syntax near the keyword 'on'.

What am I doing wrong? Should I be using a CTE for this task?

like image 499
Sergey Koulikov Avatar asked Oct 10 '11 01:10

Sergey Koulikov


People also ask

Can we use with CTE in left join?

All replies. CTEs can't be created within a SELECt query. As correctly suggested take the CTE definition outside the JOIN and use the CTE name in the JOIN. CTE definition that starts with WITH should not be preceded by any other statement, so as per the general practice, always use a semi colon before WITH.

Can you use a CTE in a join?

When you define a CTE you're doing so before any of the rest of the query. So you can't write: LEFT JOIN ( ;WITH CTE ... ) And as long as one CTE is defined before others, it can be referred to within the CTEs that follow.

Can we use CTE in Merge statement?

Multiple CTE query definitions can be defined in a CTE. A CTE must be followed by a single SELECT statement. INSERT , UPDATE , DELETE , and MERGE statements aren't supported.

Is CTE better than subquery?

The performance of CTEs and subqueries should, in theory, be the same since both provide the same information to the query optimizer. One difference is that a CTE used more than once could be easily identified and calculated once. The results could then be stored and read multiple times.


1 Answers

The CTE must come at the beginning of the query.

with cte as (
    select column1, column2 from table2
)
select column1, column2 from table1
   LEFT JOIN cte
on table1.column1 = cte.column1;
like image 64
Daryl Teo Avatar answered Oct 05 '22 01:10

Daryl Teo