Oracle SQL Questions for combined INSERT/UPDATE?

I have a table with 4 columns:

ID (Primary Key)
Name
Data1
Data2

I need a single SQL statement to perform an update if the primary key in the sql already exists or an insert if the primary key does not already exist? Any ideas? I'm hoping there is some way to do this in one statement.

I could easily do an SQL statement in my code to see if the primary key exist then do an if else to do either an insert/update, but that sounds like a waste of code and inneficient if an single oracle SQL query would cover both for me.
LVL 5
KGNicklAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

wdosanjosCommented:
0
HainKurtSr. System AnalystCommented:
not one statement but:

option 1:

begin
  insert ...
exception
when DUP_VAL_ON_INDEX then
  update ...
when others then null;
end;

option 2:

select count(1) into cnt from ...
if (cnt=0)
  insert
else
  update

option 3:

MERGE which is posted before...
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
ms_sanjayCommented:
or you can do like this
update tablename set name=<<ne name>> where id=id;

if sql%norfound then
   insert into table name values(id,name,data1,data2)

Hope this helps.

Thanks
Sippy
0
awking00Commented:
What is the source for your updates or inserts? Is it a file or another table?
0
Mark GeerlingsDatabase AdministratorCommented:
Without knowing anything about the percentage of inserts compared to updates, your most efficient option is likely to use the "merge" syntax that Oracle SQL supports now.  

Also, remember that using PL\SQL is almost always slower than using SQL by itself, so the PL\SQL examples using "if" statements and "exception" sections will likely be slower than a straight SQL solution.
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Oracle Database

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.