Customize Consent Preferences

We use cookies to help you navigate efficiently and perform certain functions. You will find detailed information about all cookies under each consent category below.

The cookies that are categorized as "Necessary" are stored on your browser as they are essential for enabling the basic functionalities of the site. ... 

Always Active

Necessary cookies are required to enable the basic features of this site, such as providing secure log-in or adjusting your consent preferences. These cookies do not store any personally identifiable data.

No cookies to display.

Functional cookies help perform certain functionalities like sharing the content of the website on social media platforms, collecting feedback, and other third-party features.

No cookies to display.

Analytical cookies are used to understand how visitors interact with the website. These cookies help provide information on metrics such as the number of visitors, bounce rate, traffic source, etc.

No cookies to display.

Performance cookies are used to understand and analyze the key performance indexes of the website which helps in delivering a better user experience for the visitors.

No cookies to display.

Advertisement cookies are used to provide visitors with customized advertisements based on the pages you visited previously and to analyze the effectiveness of the ad campaigns.

No cookies to display.

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