<s>[INST] Here is a small programming problem I need help with. Now I know what you're thinking, "Not another homework problem!" But I assure you this is not a homework problem, rather a small task I'm trying to accomplish for a side project. I have an sqlite database with the following structure:

CREATE TABLE projects (
    id integer PRIMARY KEY,
    description text
)

CREATE TABLE tasks (
    id integer PRIMARY KEY,
    project integer,
    description text,
    FOREIGN KEY(project) REFERENCES projects(id)
)

CREATE TABLE time (
    id integer PRIMARY KEY,
    project integer,
    description text,
    starttimestamp datetime,
    endtimestamp datetime,
    FOREIGN KEY(project) REFERENCES projects(id)
)

I want a query that will compare the starttimestamp of a task in the time table to the starttimestamp of each task that follows it and then determine which one is the next task. 

Here's a basic idea of the query I've come up with:

SELECT t1.starttimestamp, t1.id, t2.starttimestamp, t2.id, 
       ABS(strftime('%J', t1.endtimestamp) - strftime('%J', t2.starttimestamp)) AS timediff 
FROM time AS t1 
JOIN time AS t2 ON t1.project = t2.project 
WHERE t1.id < t2.id AND t1.project = 1
ORDER BY timediff DESC

This query works to an extent, it returns a list of all consecutive tasks in the table and a time difference in days. The problem is, the query is comparing each task to every other task, which is not efficient. 

Can anyone help me optimize this query?[/INST]