Question:
How can I make an insert with a where condition?
I have the following query:
INSERT INTO `registro`(`id`, `username`)
values
('','USER_1'),
('','USER_2'),
('','USER_3')
It will add a new user in the record table. But I need him to check if this user already exists in the DB, if it already exists he shouldn't insert it. This check should only be done for the username
column.
I read in some places that the INSERT does not accept the WHERE, in which case how should it be done?
Answer:
In SQL, you can do it like this
INSERT INTO pessoa (id, nome, sexo, datanascimento, cpf)
SELECT 227,'FULANDO DE TAL','F','1999-09-09', '999.999.999-9'
WHERE NOT EXISTS (SELECT 1 FROM pessoa WHERE id = 227);