DEV Community

Jeeho Lee
Jeeho Lee

Posted on

Order Ascending/Descending Rule with Dates and NIL

While working on reordering a database of people by date of birth, I found it confusing why the oldest people were showing up as the first entry when doing ascending order and youngest people showing up as the first entry when doing descending order. If we're doing ascending, shouldn't it be least to greatest, thus the youngest to oldest?

If I had sorted by age, this would've likely been the case, but because I was sorting by date of birth, I was mistaken. Date/time values are stored as numbers, thus the more recent dates would be a larger number than the older dates. It would make sense that the older dates would show up first when put in ascending order since it's a small value.

Another order related info that I wanted to note was how to handle NULL values. As I naturally would assume, many databases consider NULL to have the lowest value, and thus the first value if ordering by ascending value. However, it seems like for PostgreSQL specifically, NULL values are sorted as if larger than non-null values (see https://stackoverflow.com/questions/5826210/rails-order-with-nulls-last). The nice thing is that it seems PostgreSQL has NULLS FIRST and NULLS LAST options to help with sorting!

Top comments (0)