Is It Better To Query For Existing Or To Allow Unique Constraint To Fail Postgres

  Kiến thức lập trình

What is better, performance and convention wise, for checking if a value exists before inserting into a database.

I want to be able to insert a “random” string in with every record as a pseudo id of sorts, my first thought was to query the database for the string to determine if it exists first, but at a scale of 200,000,000 records at the moment, this has become quite CPU intensive.
This random string is generated in Python and passed to Postgres

(Records are processed at 100s a second, so you end up with many reads on the table per second)

My second thought was to just allow the unique constraint on the column to fail and if it fails, regenrate a new random string. Failures are not expected to be frequent, but it seems kind of dirty to do it that way.

Does anyone with more experience know what would be the best, fastest, or most correct way to do this?

Theme wordpress giá rẻ Theme wordpress giá rẻ Thiết kế website

LEAVE A COMMENT