Back to cookbooks list Articles Cookbook

How to Order by Date in SQLite

Problem:

You want to sort the rows by date in SQLite database.

Example 1:

The exam table has two columns, subject and exam_date.

subjectexam_date
Mathematics2023-12-19
English2024-01-08
Science2024-01-05
Health2024-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:

SubjectExamDate
ArtNULL
Mathematics2023-12-19
Science2024-01-05
Health2024-01-05
English2024-01-08

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 SQLite, NULLs are displayed first when sorting in ascending order and last 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: