Insert query check if record exists - If not, Insert it [duplicate] Insert query check if record exists - If not, Insert it [duplicate] php php

Insert query check if record exists - If not, Insert it [duplicate]


You can use below query. Here it will insert the ip_address when it is not present in your table.

INSERT INTO ip_list (ip_addr)SELECT * FROM (SELECT '192.168.100.1') AS tmpWHERE NOT EXISTS (    SELECT ip_addr FROM ip_list WHERE ip_addr='192.168.100.1');


You should add a UNIQUE key on ip_addr and then use INSERT IGNORE.

Maybe this helps if you haven't heard of UNIQUE yet: http://www.tutorialspoint.com/sql/sql-unique.htm


if I were you, I enforce a UNIQUE constraint on the column,

ALTER TABLE ip_list ADD CONSTRAINT IP_Unique UNIQUE(ip_addr)