Skip to content

Instantly share code, notes, and snippets.

@higs4281
Last active May 15, 2020 00:29
Show Gist options
  • Save higs4281/52f208390a31654775dca9b158125af2 to your computer and use it in GitHub Desktop.
Save higs4281/52f208390a31654775dca9b158125af2 to your computer and use it in GitHub Desktop.
the order of `order_by`

I used a paying_for_college query of notifications as a test of where to use an order_by clause.

We have 193K notifications, unorderd by default. 179K of them have '1' in their oid field.

from paying_for_college.models import Notification

nosort = Notification.objects.filter(oid__contains='1')
first = Notification.objects.order_by('timestamp').filter(oid__contains='1')
last = Notification.objects.filter(oid__contains='1').order_by('timestamp')
str(nosort.query)
SELECT "paying_for_college_notification"."id", "paying_for_college_notification"."url", 
"paying_for_college_notification"."institution_id", "paying_for_college_notification"."oid", 
"paying_for_college_notification"."timestamp", "paying_for_college_notification"."errors", 
"paying_for_college_notification"."emails", "paying_for_college_notification"."sent", 
"paying_for_college_notification"."log" 
FROM "paying_for_college_notification" 
WHERE "paying_for_college_notification"."oid"::text LIKE %1%
str(first.query)
SELECT "paying_for_college_notification"."id", "paying_for_college_notification"."url", 
"paying_for_college_notification"."institution_id", "paying_for_college_notification"."oid", 
"paying_for_college_notification"."timestamp", "paying_for_college_notification"."errors", 
"paying_for_college_notification"."emails", "paying_for_college_notification"."sent", 
"paying_for_college_notification"."log" 
FROM "paying_for_college_notification" 
WHERE "paying_for_college_notification"."oid"::text LIKE %1% 
ORDER BY "paying_for_college_notification"."timestamp" ASC
str(last.query)
SELECT "paying_for_college_notification"."id", "paying_for_college_notification"."url", 
"paying_for_college_notification"."institution_id", "paying_for_college_notification"."oid", 
"paying_for_college_notification"."timestamp", "paying_for_college_notification"."errors", 
"paying_for_college_notification"."emails", "paying_for_college_notification"."sent", 
"paying_for_college_notification"."log" 
FROM "paying_for_college_notification" 
WHERE "paying_for_college_notification"."oid"::text LIKE %1% 
ORDER BY "paying_for_college_notification"."timestamp" ASC
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment