2

I have a table I'm trying to add a unique index to. Problem is, the way the script is set up that inserts data, there will be on occasion, some empty strings instead of NULL.

So, aside from changing the script (which I foresee being necessary unless someone saves me!).... is there any setting in mysql that can automatically use NULL value if an empty string is passed through to the unique key?

6
  • This solution does it in an update, you can probably apply the concept: stackoverflow.com/questions/3238319/… Commented Oct 24, 2012 at 3:31
  • Can anything be set up table-wise, or is this a case of do it right the first time and you won't have this problemology Commented Oct 24, 2012 at 3:37
  • Why don't you do it the other way around, disallow null and set the default to empty string? Commented Oct 24, 2012 at 5:45
  • 1
    Are you using PDO? If so, you can use PDO::NULL_EMPTY_STRING attribute as a means to fix your script. Commented Oct 24, 2012 at 5:46
  • @Jack Thanks I will check this out. It sounds like what I'm looking for! Commented Oct 24, 2012 at 17:12

2 Answers 2

5

If you can't fix the import script then you should be able to use a trigger to patch things up before INSERTs or UPDATEs get to the table. Something like this should do the trick:

delimiter $$
create trigger nullify_blanks_ins before insert on your_table
for each row begin
    if new.string = '' then
        set new.string = null;
    end if;
end;
$$
create trigger nullify_blanks_upd before update on your_table
for each row begin
    if new.string = '' then
        set new.string = null;
    end if;
end;
$$  
delimiter ;

new here refers to what the row will look like after the INSERT or UPDATE completes so you can look for the garbage values and fix them. Then, since these are BEFORE triggers, your patched rows will go into the database. You would, of course, have to change the table (your_table) and column (string) names to suit your situation.

Sign up to request clarification or add additional context in comments.

Comments

0

try something like

SET sn=NULLIF(sn,NULL);

or

UPDATE Table
  SET demo = CASE demo = ' ' THEN NULL ELSE demo END,
  ...

2 Comments

Wouldn't you have to drop the unique index, insert the data, do your update, then re-add the unique index for this to work?
@muistooshort well no you wouldn't even be able to have multiple empty strings if the unique index was in place....

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.