Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

check if data exist while inserting data

How to insert a record to a table if there is no data exist of same type

insert into  user_table (userid, active,contid) values ('AAA',1,1);
insert into  user_table (userid, active,contid) values ('ABA',1,2);
          
        INSERT INTO new_table(userid,isactive)
SELECT userid,1
  FROM user_table where contid=1
 WHERE NOT EXISTS (SELECT userid
                     FROM new_table
                    WHERE contid=1
                  )

i need to copy data from one table1 to table2 if table2 doesnt have the same data. if data exist just skip and dont make any insert. I am getting "SQL command not properly ended" error with the above query

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

The exisrs clause should have another condition.

You need to check if a active userid already exists too

INSERT INTO new_table(userid,isactive)
SELECT userid,1
  FROM user_table WHERE contid=1
 AND NOT EXISTS (SELECT 1
                     FROM new_table
                    WHERE user_table.userid = new_table.userid AND contid=1
                  )
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading