Empowering you to understand your world

PostgreSQL Tutorial: How To Sort And Filter The Contents Of A PostgreSQL Table

By Nicholas Brown

In our previous exercise, we read the contents of a table in a PostgreSQL database using the ‘SELECT’ command. Let us now sort and filter the contents of that table to improve readability and find the specific data we are looking for more easily.

Sorting Data In A PostgreSQL Table

You can sort the data in a PostgreSQL table using the ‘ORDER BY’ command alongside ‘SELECT’ as shown below. The following example will display all of your table’s contents, but sort it by capacity in descending order (as indicated by ‘DESC’):

SELECT * FROM batteries ORDER BY capacity DESC;

The highest capacity batteries are shown at top, and the lowest capacity models are at the bottom. You can change ‘DESC’ to ‘ASC’ to display them in ascending order instead.

Filtering The Contents Of A PostgreSQL Table

You can filter the contents of a PostgreSQL table when using the ‘select’ command so that you won’t have to sift through records you don’t need to see at the moment. It can save a great deal of time. Here’s an example that filters out batteries that have a capacity less than 11:

SELECT * FROM batteries WHERE capacity >= 11;

You can improve readability a little by including the ‘ORDER BY’ command as well so that the highest capacity one is at the top:

SELECT * FROM batteries WHERE capacity >= 11 ORDER BY capacity DESC;
Subscribe to our newsletter
Get notified when new content is published