You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Subquery with order_by results in The ORDER BY clause is invalid in views, inline functions, derived tables, subqueries, and common table expressions, unless TOP, OFFSET or FOR XML is also specified.#106
Open
randlet opened this issue
Feb 23, 2021
· 2 comments
ProgrammingError: ('42000', '[42000] [Microsoft][ODBC Driver 13 for SQL Server][SQL Server]The ORDER BY clause is invalid in views, inline functions, derived tables, subqueries, and common table expressions, unless TOP, OFFSET or FOR XML is also specified. (1033) (SQLExecDirectW)')
when performing a simple API query with Django Rest Framework / Django Rest Framework Filters and I have narrowed it down to an issue when using a Subquery with an ordered queryset.
Here is a reproducible test case using the django-mssql-backend testapp with a freshly created/migrated SQL Server 2019 database:
SELECT"testapp_post"."id",
"testapp_post"."title",
"testapp_post"."author_id",
"testapp_post"."alt_editor_id"FROM"testapp_post"WHERE"testapp_post"."author_id"IN (
SELECT U0."id"FROM"testapp_author" U0 ORDER BY U0."name"ASC
);
And to "fix" it you can add an OFFSET 0 ROWS to the subquery:
SELECT"testapp_post"."id",
"testapp_post"."title",
"testapp_post"."author_id",
"testapp_post"."alt_editor_id"FROM"testapp_post"WHERE"testapp_post"."author_id"IN (
SELECT U0."id"FROM"testapp_author" U0 ORDER BY U0."name"ASC OFFSET 0 ROWS
);
or a TOP 100 PERCENT to the subquery:
SELECT"testapp_post"."id",
"testapp_post"."title",
"testapp_post"."author_id",
"testapp_post"."alt_editor_id"FROM"testapp_post"WHERE"testapp_post"."author_id"IN (
SELECT TOP 100 PERCENT U0."id"FROM"testapp_author" U0 ORDER BY U0."name"ASC
);
randlet
added a commit
to qatrackplus/django-mssql-backend
that referenced
this issue
Feb 23, 2021
This is a naive attempt at fixing ESSolutions/django-mssql-backend/ESSolutions#106
It just adds an `OFFSET 0 ROWS` to all queries which have an ordering
but no limit or offset.
I ran into the error:
when performing a simple API query with Django Rest Framework / Django Rest Framework Filters and I have narrowed it down to an issue when using a Subquery with an ordered queryset.
Here is a reproducible test case using the django-mssql-backend testapp with a freshly created/migrated SQL Server 2019 database:
Which results in:
The text was updated successfully, but these errors were encountered: