cancel
Showing results for 
Search instead for 
Did you mean: 
Data Engineering
Join discussions on data engineering best practices, architectures, and optimization strategies within the Databricks Community. Exchange insights and solutions with fellow data engineers.
cancel
Showing results for 
Search instead for 
Did you mean: 

SQL CTE in Databricks or something similar?

gbradley145
New Contributor III

%sql

WITH genCTE AS (

SELECT MAX(PredID) + 1 AS PredID, 145 AS SystemID

FROM TableA

UNION ALL

SELECT PredID + 1

FROM genCTE

)

SELECT * FROM genCTE

When I attempt this, I get an error that genCTE does not exists.

There may be a better way to what I am trying to do. Currently in the version of databricks we are running, we cant use an identity column. We are migrating a table and job from SQL Server to databricks. I can do a full load and pull over the identity column. But, I need to continue to populate this identity column going forward.

I also have a tried a SQL UDF where I can easily grab the MAX(ID) and have tried a row_number function over the top of it, but I cant get it work.

Hopefully I have done an adequate job of describing this issue. I simply need continue the IDs and need to do it programmaticly in databricks. I am hoping I can do this via SQL as well as I am not at all familiar with Python, although I would be open to a Python solution, I would just need a little more hand holding with it.

Thank you!

4 REPLIES 4

byrdman
New Contributor III

not seeing anything wrong , but know that your close to making this work.. I do use CTE's in Databricks SQL. make sure your query works as expected outside the CTE. another work around is make the cte portion into a dataframe then create a view from the dataframe, and use it for joins in your sql statement.

PriyaAnanthram
Contributor III

Recursive CTEs I havent yet used I got the below eg working with pyspark code How to implement Recursive Queries in Spark | by Akash Chaurasia | Globant | Medium

Hubert-Dudek
Esteemed Contributor III

You are referencing CTE inside of CTE. That's why it is not working. It would be best if you refactored your query.image.png

Anonymous
Not applicable

Hi @Greg Bradley​ 

Hope all is well! Just wanted to check in if you were able to resolve your issue and would you be happy to share the solution or mark an answer as best? Else please let us know if you need more help. 

We'd love to hear from you.

Thanks!

Connect with Databricks Users in Your Area

Join a Regional User Group to connect with local Databricks users. Events will be happening in your city, and you won’t want to miss the chance to attend and share knowledge.

If there isn’t a group near you, start one and help create a community that brings people together.

Request a New Group