0

I have two tables that I'm combining using UNION ALL. I then want to order the resulting table by Date. The original tables are in a DD/MM/YY format as opposed to YYYY-MM-DD expected by SQLite. Here's a representative example of what I have.

CREATE TABLE T1 (Name TEXT, Date TEXT);

INSERT INTO T1 VALUES
('Washington', '04-06-2017'),
('Pittsburgh', '30-06-2017');

CREATE TABLE T2 (Name TEXT, Date TEXT);

INSERT INTO T2 VALUES
('Melbourne', '04-06-2017'),
('Sydney', '30-06-2017');

CREATE TABLE T (Name TEXT, Date TEXT);

INSERT INTO T (Name, Date)
SELECT * FROM (
SELECT Name, Date FROM T1
UNION ALL
SELECT Name, Date FROM T2);

When I query these results, if I use:

SELECT * FROM T
ORDER BY Name asc;

The sort works. If I use:

SELECT * FROM T
ORDER BY Date

The ORDER BY works but the order isn't the one I want as SQLite sorts assuming a YYYY-MM-DD format. So I tried to use strftime. However, when I use:

SELECT * FROM T
ORDER BY strftime('%d-%m-%Y', Date) asc;

The resulting table is sorted by day (as if the format was as before) and the sort is only within the individual parts of the table (i.e., the part above the UNION command and the part below the UNION command). Can anyone explain why this is happening or suggest a resolution to my problem?

Thanks in advance!

2
  • This is not one of the supported date formats, so strftime() returns NULL.
    – CL.
    Jan 11, 2018 at 17:05
  • I see, thanks! I'll convert the date format earlier in the sequence
    – JWGrayson
    Jan 11, 2018 at 18:33

1 Answer 1

0

You could create a new column from the Date column that is in a sortable format i.e YYYYMMDD using the substr function e.g. :-

SELECT *, 
    substr(Date,7,4)||substr(Date,4,2)||substr(Date,1,2) AS sortabledate
    FROM T 
    ORDER BY sortabledate ASC
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.