Opened 3 years ago

Closed 3 years ago

#33531 closed Bug (invalid)

Random ORDER BY not working with MSSQL

Reported by: coronoro Owned by: nobody
Component: Database layer (models, ORM) Version: 3.0
Severity: Normal Keywords:
Cc: Triage Stage: Unreviewed
Has patch: no Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no

Description

Given a simple Model:

class Person(models.Model):
    name = models.CharField(max_length=100)
    country_code = models.CharField(max_length=3, blank=True, null=True)

    class Meta:
        db_table = 'persons'

I want to pick an entry randomly by using

Person.objects.all().order_by('?')

the resulting query has the following order by clause

... FROM [persons] ORDER BY RAND() ASC

This however does not give a randomized order of the table. Instead it always returns the same entries in the same order(ordered by id).

The desired result can be achieved with

... ORDER BY NEWID()

I am aware that this also isn't an exactly optimal solution as stated here: https://dba.stackexchange.com/questions/955/what-is-the-best-way-to-get-a-random-ordering.

For completeness: I observed this behaviour using a MSSQL14 Server

Change History (1)

comment:1 by Mariusz Felisiak, 3 years ago

Resolution: invalid
Status: newclosed

Thanks for this report, however Django 3.0 is not supported anymore and the backend for MSSQL is not built-in. You should report this issue on a bug tracker for the 3rd database backend you're using.

Note: See TracTickets for help on using tickets.
Back to Top