3

I have a SQL query that uses a Common Table Expression (CTE) with window functions, and I need to implement it using Kotlin's Exposed DSL. Since Exposed doesn't have built-in CTE support, I'm looking for a way to create custom CTEs.

Query:

WITH ranked_orders AS (
    SELECT
        customer_id,
        order_date,
        total_amount,
        DENSE_RANK() OVER (PARTITION BY customer_id ORDER BY order_date DESC) as rank_num
    FROM orders
)
SELECT
    customer_id,
    order_date,
    total_amount
FROM ranked_orders
WHERE rank_num <= 3;

Based on this JetBrains video (29:00) https://www.youtube.com/watch?v=xgfeqj8UyVA&lc=Ugz_N4GGefP6accqKbl4AaABAg, it seems Exposed provides the tools to implement CTEs ourselves, but I haven't found concrete examples of how to do it. They created custom CTE, haven't provided code. Any working code examples would be greatly appreciated!

4
  • 2
    You don't need a CTE for this. This is equivalent to a subquery as the posted answer shows. Commented Aug 11 at 9:43
  • @PanagiotisKanavos Does this DSL support derived tables straightforwardly or does that just push the question to that? Commented Aug 11 at 10:39
  • 1
    @MartinSmith by googling around I found subqueries are supported through alias. I don't use Kotlin so I can't test whether .where works on an aliased query. Commented Aug 11 at 10:46
  • This query was just for context. I want to know how to implement CTE in Exposed? Video I linked at 29:00, they have used a custom CTE (using With). Commented Aug 13 at 15:04

1 Answer 1

3
+50

You can rewrite your SQL to this:

SELECT
    customer_id,
    order_date,
    total_amount
FROM (
    SELECT
        customer_id,
        order_date,
        total_amount,
        DENSE_RANK() OVER (PARTITION BY customer_id ORDER BY order_date DESC) as rank_num
    FROM orders
) ranked_orders 
WHERE rank_num <= 3;

It seems that kotlin-exposed does not know how to handle CTE, the same way as a regular database does do, so rewriting the SQL is option one.

The second option is to take a deep dive in the docs: adjustWhere, or with

Sign up to request clarification or add additional context in comments.

2 Comments

This query was just for context. I want to know how to implement CTE in Exposed? Video I linked at 29:00, they have used a custom CTE (using With).
Updated to clarify why rewriting the query seems to be needed.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.