473,785 Members | 2,188 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Answer to avoiding Duplicates with an INSERT

23 New Member
I had to do a lot of searching to get this one to work and in doing so I saw a lot of different sites where people were looking for this answer so I thought I would put it up.

If you are trying to put data in to a table where you don't want any duplicate data a primary key, unique constraint and all that prevention is the best way to go. However when you try to insert data and it conflicts with an entry you get an error then you have to deal with error handling. So as a step to keep from getting these errors you can use a second table that will allow you to enter in values with a SELECT statement even if the values are not in the table you are selecting from. This will in turn allow you to use the NOT EXISTS clause. Another place where this is useful is if your table already has duplicate data and you want to stop this problem from compounding while you are working on removing the duplicates.

So first you will need to create a table, I called mine DUAL as it is the name of a default table in Oracle DBs that has a very similar use (so I've read). In this table you have one row and one column. I have the column USED though it can be anything you like. It has a datatype of varchar(1) and a value of x. It is important that it has a value. Didn't experiment to see if it could be other datatypes like numeric or int. So I can't say for sure if it would work but don't know why it would not.

In this example, and the reason I needed to do this in the first place, I am using a proc to enter in Newsletter info from a form on my site and when a customer opts in during the ordering process. I have listed the proc below in CREATE syntax(it has been simplified but should work just the same).

Expand|Select|Wrap|Line Numbers
  1. CREATE PROC addEmailNew    
  2. @newEmail varchar(75),
  3. @newName varchar(75),
  4. @newDate datetime
  5.  
  6. AS
  7. INSERT INTO tblNewsletter (emailAddress,nlName,signupDate) 
  8. SELECT @newEmail,@newName,@newDate
  9. FROM dual
  10. WHERE NOT EXISTS (SELECT emailAddress FROM tblNewsletter WHERE emailAddress = @newEmail)
  11.  

So if you were to run:

Expand|Select|Wrap|Line Numbers
  1. EXEC addEmailNew 'TestieTesterson@notarealsite.com','Testie Testerson', '1/1/2008'
  2.  
Then the proc would check to see if there was an email for TestieTesterson @notarealsite.c om already in the table and only insert the data if there is not. No error messages or triggers just 1 row(s) affected or 0 row(s) affected.

You can use this in many other ways, and the SELECT statement used in the WHERE Clause can be as complicated as you like. It will only insert if the statement returns nothing. Another use could be that it would only insert the email if they have a record in another table. So, using this example, only people who have an account with your site will be allowed to enter their email. So the SELECT in the WHERE Clause could search for their name or account number in a customer table.

I hope this will help others out and would like to hear if it has. Also suggestions for other uses as well as better ways to do the same task would be great!!

Thanks, RSY.
Jan 8 '08 #1
4 6385
iburyak
1,017 Recognized Expert Top Contributor
I never use a second table to prevent duplicates.
You can use distinct at insert time or not exist close.
Unique index is a good solution.


Good Luck.
Jan 8 '08 #2
ryushinyama
23 New Member
I never use a second table to prevent duplicates.
You can use distinct at insert time or not exist close.
Unique index is a good solution.


Good Luck.

If you have the time, could you explain the syntax you would use for the INSERT statement with the DISTINCT? Also the NOT EXIST CLOSE syntax alternative would be great too!!

Though what I have written above is working for me, the methods you mention here may be a better way or work in cases where this method wouldn't.

Thanks, RSY
Jan 9 '08 #3
ck9663
2,878 Recognized Expert Specialist
i'd still recommend that you create a unique index using those keys that could define a duplicate. during insert, check the error if your error corresponds with inserting duplicate records. in this way, even if the insert was done manually, the table will protect itself from any duplicate insertion...

-- ck
Jan 9 '08 #4
iburyak
1,017 Recognized Expert Top Contributor
CK9663 is absolutely right, you do need a unique index no mater what you do.
To insert with not EXIST use following:

Expand|Select|Wrap|Line Numbers
  1. IF NOT EXISTS (SELECT emailAddress FROM tblNewsletter WHERE emailAddress = @newEmail)
  2.   BEGIN
  3.      INSERT INTO tblNewsletter (emailAddress,nlName,signupDate) 
  4.      Values(@newEmail,@newName,@newDate)
  5.   END 
Go to Oracle forum for more help.

Good Luck.
Jan 9 '08 #5

Sign in to post your reply or Sign up for a free account.

Similar topics

2
2669
by: Joe | last post by:
Hey, I'm going to give some background on my situation in case anyone can point out a way around my problem altogether... for the problem itself, please skip to the bottom of the post. thanks. I've been having some problems with database performance... Several threads are constantly attempting INSERTs of new records into a large table - that is hundreds of thousands of records -large by my account :-) The table has a VARCHAR field...
3
12915
by: kj | last post by:
When I run the attached query, I get duplicates when there is one to many relationship between tableA and tableB. The query, tested schema and the result is attached. Sorry for the long post. Here is tested Schema and Data inserts. ---------------------- create table TestTblA (ShipDate datetime, CPEID varchar(30), phonenum char(14))
3
3072
by: kjaggi | last post by:
I am trying to either write a trigger or a check constraint to prevent duplicates in my table. There are two columns I need to look at for the duplicates and only one combo value for both columns is allowed in the table. For e.g. Column Serial can have only one '123456' value with testresult value as 'PASS'. This serial can be in the table many times with any other combo so for e.g. The table could contain 100 entries for serial column...
4
3627
by: Drew | last post by:
I have a permission tracking app that I am working on, and I have made the insert page for it. I am having issues on how to prevent duplicates from getting entered. Currently the interface for the app has a mixture of select boxes, list boxes and checkboxes. The form submits the page to processAIMR.asp and then does the inserting. I am using a loop to insert a new record for each checkbox checked or listbox entry selected. My...
0
422
by: c_kubie | last post by:
I have an update string getting a list of names that are list1 but not in list2. (Sorry for the lame example) list1 ---- Bill Bill mike tom jim
4
3641
by: Frank-René Schäfer | last post by:
-- A class needs to have N members according to N types mentioned in a typelist (possibly with one type occuring more than once). -- The classes should be generated **avoiding** multiple inheritance (avoiding prosperation of virtual func tables). -- At the same time, a class taking N types shall contain a virtual member function that calls a function according to the number of arguments That means, something like:
1
1659
by: rickn | last post by:
Being new to VB and programming, I'm not sure how to modify the following or if required have a Select statement to NOT allow any duplicates. I'm trying not to have any duplicates in the LOTNUM_72 field. The data is coming from odbc and being inserted via ole into access. IF the LOTNUM_72 field is set as Prinary Key, then no records are inserted if any duplicates are seen. I'n not sure at all how to make the coding so if a duplicate does...
1
15513
by: cefrancke | last post by:
I'm trying to insert records in a table that has a "no duplicates" index on two columns. The following snippet shows where I started off... INSERT INTO Table_A (ID_A, ID_B) VALUES (334, 2057) However, if these two values exist already as a "key" combination then, the MS Access
1
2166
by: tskmjk55 | last post by:
Recently, I have a requirement to develop a vb.net application wherein the input excel sheet data which has an average of 5000 records should be checked for Internal duplicates (duplicates within the same sheet) and external duplicates (duplicates which exist outside this sheet). I have gone through lot of logics..some of which are ... - Common and currently testing out.. - First insert the excel sheet data into DB..then query by...
0
9646
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9484
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10350
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10157
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
8983
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7505
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6742
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5386
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
2
3658
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.