0

Is it possible to run select query, check if row exist and then insert some values? I would like to do that in one query. I think about SELECT .. CASE .. THEN, for example:

SELECT user_id, CASE when user_id > 0 then (INSERT INTO another_table ...) ELSE return 0 END 
FROM users WHERE user_id = 10 

Now I'm able to do that with 2 queries, first do SELECT and second INSERT values (if first query return something).

Thanks!

Ridd
  • 10,701
  • 3
  • 19
  • 20

1 Answers1

1

in general the construct is:

INSERT INTO another_table 
SELECT value1,value2..etc
where exists (SELECT user_id FROM users WHERE user_id = 10)

or in this particular case:

INSERT INTO another_table 
SELECT value1,value2..etc
FROM users WHERE user_id = 10

If no such user, no rows will be selected and so inserted

Vao Tsun
  • 47,234
  • 13
  • 100
  • 132