Adrian Roy Baguio
Adrian Roy Baguio

Reputation: 114

The most appropriate way to check if the value already existed

Let me explain the scenario first.

I have a customer and phone relation database. A customer can have multiple phone numbers as long as the phone numbers are unique.

For example,

Normally, I have to execute couple queries to achieve this

First check if the number trying to add has already existed in the database. query = "SELECT COUNT(NAME) where name = 'Bryan' and number '111'";

If the result is 0, then proceed with INSERT execution.

I don't think this is the right way though.

I have tried using the following query but it didn't work. Its saying invalid syntax.

IF NOT EXISTS (
SELECT telephone
FROM phone_numbers
WHERE telephone = '123456' 
AND customer_id = 20)
BEGIN
INSERT INTO phone_numbers (telephone, customer_id) VALUES
("123456", 20)
END;

I'm writting this in C# could anyone please enlighten me the most appropriate way to do this?

Upvotes: 1

Views: 78

Answers (1)

spender
spender

Reputation: 120400

Not an answer to your specific question, but advice as to how better define your schema such that the problem you face isn't allowed to happen.

So if you specify the following unique constraint:

ALTER TABLE `phone_numbers` 
  ADD UNIQUE `unique_index`(`customer_id`, `telephone`);

Your database won't allow you to mess this up in the first place.

Upvotes: 1

Related Questions