How to run INSERT only if the record does not exist?

Asked

Viewed 683 times

4

I’d like to wear something like

insert into table (column) values ('')if not exist;

2 answers

7


Can use INSERT OR IGNORE.

To this end, the column(s) (s) concerned shall (m) be declared(s) as UNIQUE.

When there is a violation of a restriction (Constraint) it is treated as indicated in Conflict clause of Constraint declared for the column, which by default is abort.
If declared or not it can be overwritten in the INSERT command:

INSERT OR IGNORE INTO table (column) VALUES ('')

Thus the violation of the restriction is ignored.

Behold INSERT and ON CONFLICT clause.

2

You can use a Unic to avoid repetition where appropriate. I found the example below in https://www.techonthenet.com/sqlite/unique.php

CREATE TABLE employees
( employee_id INTEGER PRIMARY KEY AUTOINCREMENT,
  last_name VARCHAR NOT NULL,
  first_name VARCHAR,
  hire_date DATE,
  CONSTRAINT name_unique UNIQUE (last_name, first_name)
);

In addition you can also use a select along with the Insert to carry out the validation. Using the above table, you could do something like:

 insert into employees(last_name, first_name, hire_date)

 select 
    'Stuart','John','1990-01-01' 
 from 
    employees 
 where 
    not exists(select 1 from employees where first_name = 'john')

When the query has no results, it will not perform the Insert and you can perform any filtering in the Where.

  • yes I did it but wanted to do it on the Insert itself

  • I added another way to perform Insert in my previous answer

Browser other questions tagged

You are not signed in. Login or sign up in order to post.