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!

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

Top comments (0)

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay