View Full Version : checking mysql record exists problem

12-06-2010, 09:27 AM
hi again

hi ,,,, i have a table cost with

cost no( Unique) , name , and officer in the field names in the table

i want to insert some records to cost table ....

i want to check there cost no exists or not before record adding to the table


in the cost table i have cost no -50

now i going to insert Cost no-50 ,51 and 52

it should only insert 51 , 52 because cost no 50 is already there( 50 should not be replace with new record 50 )

plz give me SQL QUERY for this

help meeeeeeeeeeeee

12-06-2010, 11:06 AM
Set them seperately as normal, and the database will refuse to set the one with cost=50 because it's unique.

12-06-2010, 05:57 PM
Lamped is right, you can allow MySQL to attempt the INSERT and it will just fail if that value already exists. However, this is entirely dependant on whether you set up a unique index for that column. If you are just saying you want that column to be unique, but you didn't create an index to enforce uniqueness, then you'll have to SELECT first, and then insert if the select returns nothing.

p.s. Assuming you do have a unique index, you can find out if the INSERT worked or not by calling mysql_affected_rows() after the insert query and testing the return value: 0 means no row was inserted, 1+ means a row was inserted.