0

I saw the below query in algoexpert where they say they can update the job id based on the previous query. I have seen an update query with a select clause inside it or the merge clause that inserts or updates depending on a match

Is there some SQL syntax that lets you do the below. Please can you point me to links to read up on this?

BEGIN TRANSACTION;
  SELECT * FROM jobs_table WHERE status = 'QUEUED' ORDER BY created_at ASC LIMIT 1;
  // if there's none, we ROLLBACK;
  UPDATE jobs_table SET status = 'RUNNING' WHERE id = id from previous query;
  COMMIT;
3
  • Have you tried where id in (...) Commented Mar 25, 2022 at 12:09
  • Specify which dbms you are using Commented Mar 25, 2022 at 12:09
  • You could use UPDATE jobs_table SET ... WHERE EXISTS(...) instead. Commented Mar 25, 2022 at 12:09

1 Answer 1

1
UPDATE jobs_table 
SET status = 'RUNNING' 
WHERE id IN (SELECT id 
             FROM jobs_table 
             WHERE status = 'QUEUED' 
             ORDER BY created_at ASC 
             LIMIT 1);

When no id is found in the sub-query, nothing is being updated.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.