Forum Discussion
Delete Duplicates (leave 1)
- Nov 20, 2021
Hi
I'm just about to go out but have a look at the 2 example apps in the attached zip file which show two different approaches to thisHope one/both are of help
True, either way works...if you're only using one field to identify duplicates. If you have to combine several fields to determine a unique record then as far as I know you'd need to create a multi-field PK
Not true.
Setting a unique index works on a single field or multiple fields.
There is no need to set those fields as a primary key for this purpose.
In general, it is usually better to avoid the use of composite primary keys.
- BrianWS1ONov 26, 2021Brass ContributorI don't follow; how do you set an index in MS Access across multiple fields? For example, if I want to avoid duplicates and I have records with First Name, Last Name, City, and State, but I don't want that same person at that location entered twice, how do I set up an index to prevent that?
Also, you can create a composite PK just temporarily to append the records and weed out the dupes, then change back to using a different PK.
Can you explain why a composite primary key should be avoided? Is it a processing thing? Does it matter with record sets below a certain size? Does it appreciably slow down processing when adding records? I'd like to see documentation to determine when this is or isn't a concern.- George_HepworthNov 26, 2021Silver Contributor
PMFJI:
You set a unique composite index like this in Access:
Of course, you could also include the multiple fields in a Composite Primary Key.
In my experience, the main reason NOT to use composite Primary Keys is the difficulty they present in multi-field queries. If you have to create joins on multiple fields, the SQL statement grows to an unwieldy and confusing state. I don't know if it impacts performance, though.
- BrianWS1ONov 27, 2021Brass ContributorThat is a cool feature, I never knew Access would let you create a composite index like that! I'm putting that in my mental notepad for future use, it should save a lot of hassles. Thanks!
- isladogsNov 26, 2021MVP
George has already shown you how to create a unique index for multiple fields.
I have used composite primary keys in the past but eventually stopped doing so (except in rare cases) because they tended to make managing queries & code more unwieldy. If you run an online search you will find articles both for & against their use. A fairly balanced (if rather complex) article can be found at https://medium.com/@pablodalloglio/7-reasons-not-to-use-composite-keys-1d5efd5ec2e5 though I've only skimmed the article
Lets take a simple reason for avoiding them. As well as not containing duplicates, primary keys cannot ever contain null values. So all those fields must ALWAYS contain data which at times may prevent a new record being saved. However, with a unique index, you can choose to ignore nulls.
Hope that helps