if not exists mysql code example
Example 1: mysql create table if not exists example
CREATE TABLE IF NOT EXISTS checklists (
todo_id INT AUTO_INCREMENT,
task_id INT,
todo VARCHAR(255) NOT NULL,
is_completed BOOLEAN NOT NULL DEFAULT FALSE,
PRIMARY KEY (todo_id , task_id),
FOREIGN KEY (task_id)
REFERENCES tasks (task_id)
ON UPDATE RESTRICT ON DELETE CASCADE
);Code language: SQL (Structured Query Language) (sql)
Example 2: not exists mysql
SELECT DISTINCT store_type FROM stores
WHERE NOT EXISTS (SELECT * FROM cities_stores
WHERE cities_stores.store_type = stores.store_type);
Example 3: insert if not exists mysql
INSERT INTO table_listnames (name, address, tele)
SELECT * FROM (SELECT 'Unknown' AS name, 'Unknown' AS address, '022' AS tele) AS tmp
WHERE NOT EXISTS (
SELECT name FROM table_listnames WHERE name = 'Rupert'
) LIMIT 1;
Example 4: mysql insert into if not exists
INSERT INTO table_name (firstname, lastname)
SELECT 'NEW FIRSTNAME', 'NEW LASTNAME'
FROM DUAL
WHERE NOT EXISTS(
SELECT 1
FROM table_name
WHERE firstname = 'NEW FIRSTNAME' AND lastname = 'NEW LASTNAME'
)
LIMIT 1;
Example 5: mysql insert if not exists
INSERT IGNORE INTO companies
(id, full_name, address, phone_number)
VALUES
(1, 'Apple', '1 Infinite Loop, Cupertino, California', 18002752273);