﻿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
33531	Random ORDER BY not working with MSSQL	coronoro	nobody	"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


"	Bug	closed	Database layer (models, ORM)	3.0	Normal	invalid			Unreviewed	0	0	0	0	0	0
