Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking Duplicates before inserting into SQL database

Tags:

sql

So I've been doing some research and I need to write up an INSERT statement to insert unique client names into a table on my server. However the default standard of the database already has thousands of clients in it, and when inserting new clients we need to check if they already exist before attempting to add it to the system.

My question is what would be the best/fastest way to do this? Would it be better to run a simple select query on the clients table (ordered by ASC), and do a binary search or something on the results, or perhaps just do a SQL query similar to the one below?

IF NOT EXISTS (SELECT 1 FROM clients AS c WHERE c.clientname = ?)
BEGIN
  INSERT INTO clients (clientname, address, ...)
  VALUES (?, ?, ...)
END

Is this a slow statement? I may have to run the insert several hundred times per each submission.

like image 592
SNpn Avatar asked Jun 22 '26 22:06

SNpn


1 Answers

The standard advice is to create a UNIQUE constraint if you want a given column to be unique.

ALTER TABLE clients ADD UNIQUE KEY (clientname);

Then try to do the INSERT, and it'll succeed if there is no matching row, and it'll fail if there is a duplicate. No SELECT is necessary.

like image 83
Bill Karwin Avatar answered Jun 25 '26 22:06

Bill Karwin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!