Skip to content

Instantly share code, notes, and snippets.

@Gurpartap
Last active March 24, 2017 02:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Gurpartap/e8d19272b7c996ce10239bb60a787f41 to your computer and use it in GitHub Desktop.
Save Gurpartap/e8d19272b7c996ce10239bb60a787f41 to your computer and use it in GitHub Desktop.
select x where latest y of x is z
create table tasks (
id serial primary key,
name text not null
);
create table results (
id serial primary key,
created_at timestamptz default now() not null,
state text default null,
task_id int references tasks(id)
);
insert into tasks (name) values ('task_1');
insert into tasks (name) values ('task_2');
insert into tasks (name) values ('task_3');
insert into tasks (name) values ('task_4');
insert into tasks (name) values ('task_5');
insert into results (state, task_id) values ('completed', 1);
insert into results (state, task_id) values ('failed', 2);
begin;
select task.*
from tasks task
left join lateral (
select _r.state
from task_results _r
where _r.task_id = task.id
order by _r.created_at desc
limit 1
) result on true
where task.name = $1::text
and (result is null or result.state not in ('completed', 'failed'))
limit 1
for update of task
skip locked
;
commit;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment