As Dan Farrell mentioned in a comment, your question lacks precision: it would have been much clearer if you had given us the schema you were working with (what are the columns?).
Additionally, as Daniel mentioned in his answer, if you want to have a unique column or a unique combination of columns, you should use a UNIQUE
index to start with.
Now with that said, relying on MySQL reporting errors for business decisions is not quite right, and not needed. Indeed, MySQL provides two commands that let you decide what to do when an insertion violates a unique index, and it should be used instead of having MySQL throw an error. You can refere to MySQL documentation on INSERT for more
INSERT IGNORE INTO ...
: with this syntax, MySQL will insert the row only if no unique key is violated, i.e. in your case if the URL is not already in the table. You'll get something like
INSERT IGNORE INTO `yourtable` (field1, field2, ..., url)
VALUES ('f1', 'f2', ..., 'http://example.com');
Upon executing the query, MySQL will tell you how many rows were affected, thus if the url was already present, it will tell you no row was affected.
INSERT INTO ... ON DUPLICATE KEY UPDATE ...
: with this syntax, you will be able to update an entry instead of inserting a new one if the url already exists; useful for example if you had a counter field storing how many times the url has been submitted by your users
INSERT INTO `yourtable` (last_submitted_by, counter, url)
VALUES ('joe', 1, 'http://example.com')
ON DUPLICATE KEY UPDATE
counter = counter + 1,
last_submitted_by = VALUES(last_submitted_by) ;
Note that in the UPDATE
part you can reference values you specified in the INSERT
part with the VALUES(..)
construct (in my example this would be used to maintain a reference to the last user who submitted this url.
Update (after a comment on an other answer)
Of course there is a limit to the size of fields you can use in an index, and for text fields you must specify the length. This answer on another SO question gives details on the limit, but even with the lower limit (1000 bytes for MySQL), that would be plenty enough for urls uniqueness (that would be 500 characters if stored in unicode, which you don't really have a reason to do for urls, although now you might encounter some with special characters now that non ascii characters are available in domain names (outside domain names, non ascii characters should be url encoded anyway).