﻿id	summary	reporter	owner	description	type	status	component	version	severity	resolution	keywords	cc	stage	has_patch	needs_docs	needs_tests	needs_better_patch	easy	ui_ux
37556	Combined querysets with default ordering raise ORA-00907 on Oracle	Dmitri	Dmitri	"On Oracle, combining unsliced querysets for a model with `Meta.ordering`
generates a bare `ORDER BY` inside parenthesized components of a compound
query. Oracle rejects this SQL with:

{{{
oracledb.exceptions.DatabaseError: ORA-00907: missing right parenthesis
}}}

This isn't specific to ordering by related fields. For example, the
following test using the existing `Note` model in
`tests/queries/test_qs_combinators.py` fails on Oracle:

{{{
#!python
def test_union_default_ordering(self):
    note_b = Note.objects.create(note=""n2"", misc=""m2"")
    note_a = Note.objects.create(note=""n1"", misc=""m1"")
    qs = Note.objects.all()
    self.assertSequenceEqual(qs.union(qs), [note_a, note_b])
}}}

The behavior is the same on `stable/6.0.x` and `main`, so this isn't a
regression in Django 6.1.

For unsliced combined queries, the ordering of individual components
doesn't affect the selected rows; the outer query applies the resulting
ordering. Keeping it also creates backend deviations: some databases
accept and ignore it, while Oracle rejects it.

Simon previously suggested clearing ordering when it isn't meaningful:

> when ordering in combined queries is not meaningful
> (`not (self.is_sliced or self.distinct_fields or self.select_for_update)`)
> I think we should always elide it

The proposed direction is therefore to clear meaningless ordering while
preserving it for sliced queries, `DISTINCT ON`, and `SELECT FOR UPDATE`.
When meaningful ordering is preserved but unsupported by the target
backend, compilation could raise a clear error based on the backend
feature flags.

References:

* #36938 and #37097: previous fixes for ordering in combined queries.
* [https://github.com/django/django/pull/21277#issuecomment-4435897084 Simon's proposed approach].
* [https://github.com/django/django/pull/22337 PR #22337]: discussion and a proof of concept with tests, tested on Oracle 26ai and SQLite.
* [https://github.com/django/django/pull/22337#issuecomment-7285484134 Jacob's follow-up supporting investigation of this approach through the regular development process].
* [https://github.com/django/django/pull/22372 PR #22372]: temporarily skips the related test on Oracle.
"	Bug	assigned	Database layer (models, ORM)	6.0	Normal		oracle, union, order_by		Unreviewed	0	0	0	0	0	0
