1

I'm currently trying to SELECT columns from a table, do some arithmetic with the selected values and then INSERT the updated values back into the same table. So far, I'm thinking of SELECT all columns, copy to another table, UPDATE that table and copy it back but this seems kinda redundant.

INSERT INTO tableB (x, y) SELECT x, y FROM tableA;

UPDATE tableB SET y = y + 1;

INSERT INTO tableA (x, y) SELECT x, y FROM tableB;

where x and y are declared UNIQUE(x, y)

EDIT: Is there a way to avoid creating another table for this transaction?

2
  • If you want to insert into two different tables then you need two statements AFAIK. And if the two inserts are logically dependent, then you might want to use a transaction. Commented Dec 9, 2017 at 11:09
  • I think my question might be slightly ambiguous but I'm trying to copy and update the values in one table only, in this case tableA. I created tableB to hold the temporary values. Commented Dec 9, 2017 at 11:17

2 Answers 2

3

If you want to copy the changed data, you can do that with a single insert:

insert into tablea (x,y)
select x, y + 1
from tablea;
Sign up to request clarification or add additional context in comments.

2 Comments

I'm trying to copy the values, not directly update it. The old values should remain, only that the new values to be inserted depends on the old ones. Sorry if its slightly confusing.
You can do that with a single statement
1

If I read your logic correctly, then you only need two inserts here, possibly inside a transaction:

BEGIN;
    INSERT INTO tableB (x, y) SELECT x, y+1 FROM tableA;
    INSERT INTO tableA (x, y) SELECT x, y FROM tableB
COMMIT;

The update after the insert is unnecessary as you can simply insert the incremented values of y.

2 Comments

Would something like timestamp addition with interval work in the first statement?
@Larrrrrrrrrry If it works in any select, it should work here. I think you need two inserts, but the update looks unnecessary to me.

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.