Skip to content

Duplicate CTE generated when multiple window functions are involved #105

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

Open
salomvary opened this issue Jan 30, 2025 · 0 comments
Open

Comments

@salomvary
Copy link

Given this CTE query:

  cte = With(Thing.objects
             .annotate(row_number=Window(RowNumber())))

  queryset = (
      cte.queryset().with_cte(cte)
      .annotate(row_number2=Window(RowNumber(), order_by=[F("row_number")]))
      .filter(row_number2=1)
  )

The generated SQL looks like this:

WITH RECURSIVE cte AS (
    SELECT my_app_thing.id, 
           ROW_NUMBER() OVER () AS row_number 
    FROM my_app_thing
)
SELECT *
FROM (
    WITH RECURSIVE cte AS (
        SELECT my_app_thing.id, 
               ROW_NUMBER() OVER () AS row_number 
        FROM my_app_thing
    )
    SELECT cte.id AS col1, 
           cte.row_number AS row_number, 
           ROW_NUMBER() OVER (ORDER BY cte.row_number) AS row_number2
      FROM cte
  ) qualify
WHERE row_number2 = 1

While it should be something like this:

WITH RECURSIVE cte AS (
    SELECT my_app_thing.id, 
           ROW_NUMBER() OVER () AS row_number 
    FROM my_app_thing
)
SELECT *
FROM (
    SELECT cte.id AS col1, 
                 cte.row_number AS row_number, 
                 ROW_NUMBER() OVER (ORDER BY cte.row_number) AS row_number2
    FROM cte
) qualify
WHERE row_number2 = 1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant