getting error when clear cache in drupal
Consider using db_merge if you want to write when the record doesn't exist and update if the record exists. In fact at the business logic level you should check if a record exists or not before making an insert or update. That way you will have more control. 

And regarding the problem you are facing only when you clear cache, it can be that somewhere in your code when you have an entry in cache you are not making an insert. But when there is no entry in the cache, you are making an insert. So every time you clear the cache an insert is being attempted with the same key which might be causing the problem.