How to Order by Date in PostgreSQL or Oracle
Database:
Operators:
Table of Contents
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.
| subject | exam_date |
|---|---|
| Mathematics | 2022-12-19 |
| English | 2023-01-08 |
| Science | 2023-01-05 |
| Health | 2023-01-05 |
| Art | NULL |
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):
| subject | exam_date |
|---|---|
| Mathematics | 2022-12-19 |
| Science | 2023-01-05 |
| Health | 2023-01-05 |
| English | 2023-01-08 |
| Art | NULL |
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).