Helping you build a better website
(and other interesting web stuff)

CSSHTMLJavaScriptjQueryMySQLPHPSilvaTechnologiesWooCommerceWordpress
Silva Web Designs - Blog

How to insert if something does not exist in MySQL database

When we create a database table we try to make sure that on certain tables we only allow the user to insert a unique record. To achieve this, we assign a primary key to the table but sometimes duplicate records can be inserted as there may not be any validations in place.

The code below allows you to insert records only if it doesn’t already exist in the table:


INSERT INTO user (Name,username,password)
SELECT * FROM (SELECT 'Name', 'Address', 'Postcode') 
AS tmp WHERE NOT EXISTS 	
(SELECT Name,username,password 
FROM user WHERE Name = 'Name' and username = 'Address' and password = 'Postcode');
Nathan da Silva - Profile

Posted by: Nathan da Silva

Nathan is the Founder of Silva Web Designs. He is passionate about web development, website design and basically anything digital related. His main expertise is with WordPress, Magento, Shopify as well of many other frameworks. Whether you need responsive design, SEO, speed optimisation or anything else in the world of digital then get in touch. If you would like to work with Nathan, simply drop him an email at [email protected]

It’s good to share

Join the discussion