Sort Postgres Tables

Brett Cassette
InstructorBrett Cassette
Share this video with your friends

Social Share Links

Send Tweet
Published 7 years ago
Updated 5 years ago

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.

[00:00] 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.

[00:16] 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.

[00:43] 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.

[00:58] 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.

~ 7 years ago

Hi, I found here has a typo:

SELECT friends
ORDER BY friend_count desc, name desc;

SELECT friends
ORDER BY friend_count, name desc;

the SELECT friends should be FROM friends.

Markdown supported.
Become a member to join the discussionEnroll Today