Back to cookbooks list Articles Cookbook

How to Order by Date in PostgreSQL or Oracle

Problem:

You want to sort the rows by date in PostgreSQL or Oracle database.

Example 1:

The exam table has two columns, subject and exam_date.

subjectexam_date
Mathematics2022-12-19
English2023-01-08
Science2023-01-05
Health2023-01-05
ArtNULL

You want to sort the rows by exam_date.

Solution:

SELECT *
FROM exam
ORDER BY exam_date;

The result looks like this (the rows are sorted in ascending order by exam_date):

subjectexam_date
Mathematics2022-12-19
Science2023-01-05
Health2023-01-05
English2023-01-08
ArtNULL

Discussion:

Use the ORDER BY keyword and the name of the column by which you want to sort. This way, you'll sort the data in ascending order by this column. You could also use the ASC keyword to make it clear that the order is ascending (the earliest date is shown first, the latest date is shown last, etc.).

SELECT *
FROM exam
ORDER BY exam_date ASC;

If you'd like to see the latest date first and the earliest date last, you need to sort in descending order. Use the DESC keyword in this case.

SELECT *
FROM exam
ORDER BY exam_date DESC;

Note that in PostgreSQL and in Oracle, NULLs are displayed last when sorting in ascending order and first when sorting in descending order. Also, the rows with the same exam_date are displayed in random order (you may see Science second and Health third, or Health second and Science third).

Recommended courses:

Recommended articles:

See also: