0

I have 6 columns in my table:

Id  | Name | Mail id | Gender | Contact Number | father name

while inserting a data into table i wanted to check condition like if Name,mailid,contact number already exists then insert should not happen else record should be inserted.

Can any one suggest how to check the condition while inserting a record.

Joke_Sense10
  • 4,893
  • 2
  • 15
  • 20
user1869857
  • 27
  • 1
  • 9
  • Maybe this help you: http://stackoverflow.com/questions/913841/mysql-conditional-insert – kitek Nov 17 '13 at 17:24
  • If the tuple `Name, MailID, ContactNumber` should be unique, you should define a unique index on it to enforce that constraint. Then you can use `INSERT IGNORE` which is simpler. Otherwise go with Muhammed Ali's answer. – Hut8 Nov 17 '13 at 17:28
  • refer the link below it works pretty well http://stackoverflow.com/a/3164741/3209804 – Varshaan Nov 24 '15 at 08:22

3 Answers3

1
IF NOT EXISTS (SELECT * FROM Table_Name WHERE Condition you are checking)
BEGIN
  INSERT INTO .............   ---<----- Your Insert Statement.....

END
M.Ali
  • 62,698
  • 12
  • 85
  • 116
0

You can define an index on multiple columns, e.g.:

CREATE UNIQUE INDEX arbitrary_index_name ON table_name (Name, mailid, contactnumber);
Milina Udara
  • 587
  • 1
  • 9
  • 24
0

I also faced similar situation, you can do this by adding unique constraint to your table and using 'insert ignore' statement to add data.

Create table statement:

CREATE TABLE Student (
Id INT PRIMARY KEY AUTO_INCREMENT,
NAME VARCHAR(50),
Mailid VARCHAR(50),
Gender CHAR,
contactnumber BIGINT,
fathername VARCHAR(50),
UNIQUE(NAME,Mailid,contactnumber));

Insert Ignore statement:

INSERT IGNORE INTO student(NAME, Mailid,Gender,contactnumber,fathername) VALUES('Shekhar', 's@s.com', 'M', 987654321, 'Joshi');
Shekhar Joshi
  • 828
  • 1
  • 12
  • 23