How to check if the record exists in the database and update if it exists

Asked

Viewed 98 times

0

How to check if the record exists in the database and update if it exists I tried this way

Select if((SELECT COUNT(*) FROM Pessoas WHERE id = 0) > 0, 
          ( UPDATE Pessoas SET Name ="João" where id = 0 ),
          ( INSERT INTO Pessoas VALUES (0,"João")  )
);
  • 1

    Just clarify one thing: no if you do a search with id = 2 and in the update and insert vc assigns the id 0. It got me a little confused...

  • Corrected now thank you

  • Okay, I’ll formulate an answer.

  • 1

    Because all the answers are negative?

  • I don’t understand either.

  • Why is my question now also negative?

Show 1 more comment

3 answers

2


Usually for these cases I resort to stored Procedure to perform these control operations, e.g.:

CREATE DEFINER=`root`@`localhost` PROCEDURE 'gravar_pessoas'(zid int, znome varchar(100))
begin
   if not exists(select * from pessoas where id = zid) then
     insert into pessoas() values(zid, znome);
   end if;

   if exists(select *  from pessoas where id = zid) then
      update pessoas set nome = znome where id = zid;
    end if;
end

1

It sounds strange to me before the appointment you already have the id and still check if it exists in the database. But let’s go to the answer!


Whereas you already have the id of the record to be searched and that id almost always is a primary key or unique, you can run the following query:

INSERT INTO `pessoas` (`id`, `Name`) VALUES (0, 'João') ON DUPLICATE KEY UPDATE `Name` = 'João';

That’s exactly what you’re doing at query of your question:

If there is some record with the id = 0, update your Name = 'João'.

If not, insert the id = 0 with Name = 'João'.

  • 2

    To the colleague who left giving -1 in EVERYTHING here: could you please leave a comment clarifying what is not agreed?!

-2

select if((select count(*) from Pessoas where id = 2) > 0, 
(UPDATE Pessoas SET Name ="João" where id = 0), 
INSERT INTO Pessoas VALUES (0,"João")) as value from Pessoas
  • 1

    The people who gave -1 could clarify why ?

  • also do not know why only really wanted to know the best resolution for my problem

Browser other questions tagged

You are not signed in. Login or sign up in order to post.