How to Sort a Table By Month in PostgreSQL

PostgreSQL supports an ORDER BY clause to sort a table ascendingly or descendingly. It sorts the table based on a specific column or multiple columns. However, the "ORDER BY" clause wouldn't be sufficient to sort the table's data by month; instead, it must be executed with the EXTRACT() function to achieve the desired functionality.

This write-up will illustrate a detailed procedure to sort a table by month in Postgres.

How to Sort a Table By Month in Postgres?

To sort a table by month use the ORDER BY clause alongside the EXTRACT() function. 'Month' must be passed as an argument to the EXTRACT() function. Here is a simple syntax to order the table’s data by month:

SELECT col_list
FROM tab_name
ORDER BY EXTRACT('Month' FROM date_val);

You can also use the “DESC” option to sort the table’s data from higher month to lower month.

Example: Sort Table By Month

Follow the given instructions to sort the table by month in ascending or descending order:

Step 1: Sample Table

Execute the provided command to populate the “emp_data” table:

SELECT *
FROM emp_data;
img

The above table maintains the default insertion order.

Step 2: Sort By Month Ascending Order

Use the following SELECT statement to sort the table’s data with respect to the month specified:

SELECT *
FROM emp_data
ORDER BY EXTRACT('Month' FROM joining_date);
img

From the above snippet, you can observe that the table’s data has been successfully sorted(ascendingly) according to the month specified in the joining_date column.

Step 3: Sort By Month Descending Order

Use the DESC option to sort the table in descending form:

SELECT *
FROM emp_data
ORDER BY EXTRACT('Month' FROM joining_date) DESC;
img

From the above result set, you can clearly notice that the table’s data has been successfully sorted(descendingly) according to the month specified in the joining_date column.

Conclusion

Use the ORDER BY clause alongside the EXTRACT() function to sort a table by month. 'Month' must be passed as an argument to the EXTRACT() function. The “ASC” or “DESC” options can be utilized to sort the table’s data ascendingly or descendingly. This post has demonstrated a detailed procedure to sort a table by month in Postgres.