Join egghead, unlock knowledge.

Want more egghead?

This lesson is for members. Join us? Get access to all 3,000+ tutorials + a community with expert developers around the world.

Unlock This Lesson
Become a member
to unlock all features

Level Up!

Access all courses & lessons on egghead today and lock-in your price for life.


    Sort Postgres Tables


    How do I see a list of my Facebook friends sorted by the number of friends they have, and then sorted alphabetically to break ties? Sorting data helps us to answer important business questions. In this lesson, we’ll learn how to do it in Postgres.



    Become a Member to view code

    You must be a Pro Member to view code

    Access all courses and lessons, track your progress, gain confidence and expertise.

    Become a Member
    and unlock code for this lesson
    orLog In




    Today we're sorting data. We're going to sort some friends by the number of friends they have in our Facebook type app. By default, this is always ascending, so we're going to start with the lowest number of friends and move up to the highest number of friends.

    If we want to change to descending, we will append the the descending descriptor here, but I like it ascending to start. We see here, though, that Sophia and Andrew have a tie for the number of friends they have. If they do, we can specify another way to sort them, because without it, we don't have that information. It's just going to default to using this ID column.

    We might prefer to sort by the name. Now Andrew comes before Sophia, so Andrew will sort higher. We can also add descending to both of these to specify that we want it to go in the exact opposite order.

    Now we'll start with the highest number of friends, move through to the lowest number of friends, and also, in name ties, we'll go in reverse alphabetical order. That doesn't seem to make sense, so we'll leave this. Now Andrew beats Sophia, but the person with the most friends is still going to be listed first in our list. That's orderized.