HiveBrain v1.2.0
Get Started
← Back to all entries
patternsqlMinor

Resolving DUPLICATE for a column with UNIQUE

Submitted by: @import:stackexchange-dba··
0
Viewed 0 times
uniquecolumnwithduplicateforresolving

Problem

I have a few column with UNIQUE INDEX. In some queries, duplicates should be acceptable, in which a postfix should be added to the value. For example, if test title exits, we change it to test title-2.

Is there a way to make a unique value upon DUPLICATE?

INSERT INTO table1
  (title, abr, name) 
  VALUES
  ('title', 'abr', 'name')


In this typical example, all three columns are UNIQUE. When the INSERT fails, I do not know which col caused the error to change its corresponding value.

How can I make a query to change value to value-identifier upon duplicate error?

Solution

I would look at your model first. Placing a unique key constraint on a non-unique column gets you into this kind of problem. What happens when you get a legitimate value like test title-2 but you've already used that value to resolve a collision on test title.

If I had to resolve your problem, I would build a query for each unique key of the form:

SELECT  title
FROM    table1
WHERE   title STARTS WITH ?


The results will need to be parsed to see what the suffix should be. It might be possible to do this in a stored procedure. However, I would strongly argue that the data model needed to be fixed, not the code.

Code Snippets

SELECT  title
FROM    table1
WHERE   title STARTS WITH ?

Context

StackExchange Database Administrators Q#29227, answer score: 4

Revisions (0)

No revisions yet.