Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sqlite - How to get INSERT OR IGNORE to work

Tags:

sqlite

I'm trying to insert data into a table. I would like to insert the row if the column doesn't have the data already - regardless of the other columns.

CREATE TABLE t (     id          INTEGER PRIMARY KEY,     name        VARCHAR,     other       INT ); INSERT OR IGNORE INTO t (name) VALUES ('a'); INSERT OR IGNORE INTO t (name) VALUES ('a'); INSERT OR IGNORE INTO t (name) VALUES ('a'); 

With the above snippet I end up with 3 rows, not 1 as I would have thought. If it matters the actual sql is happening inside of a INSTEAD OF INSERT trigger, this is just a simple test case.

like image 798
Justin808 Avatar asked Aug 24 '12 07:08

Justin808


People also ask

How manually insert data in SQLite database?

If you want to inset the data manually(fully graphical) do the following: Go to the DDMS perspective. File explorer (tab-menu) Locate your db (/data/data/com.

What is insert or ignore in SQLite?

The INSERT OR IGNORE INTO statement ignores the error message. The SELECT statement shows that the last two statements did not modify the fourth row. Since SQLite version 3.7. 11 it is possible to insert multiple rows using one INSERT statement.

What does SQLite insert return?

Typical Use. In the INSERT statement above, SQLite computes the values for all three columns. The RETURNING clause causes SQLite to report the chosen values back to the application. This saves the application from having to issue a separate query to figure out exactly what values were inserted.


1 Answers

Replace

CREATE TABLE t (     id          INTEGER PRIMARY KEY,     name        VARCHAR,     other       INT ); 

with

CREATE TABLE t (     id          INTEGER PRIMARY KEY,     name        VARCHAR UNIQUE,     other       INT ); 

Then you will get

sqlite> CREATE TABLE t (    ...>     id          INTEGER PRIMARY KEY,    ...>     name        VARCHAR UNIQUE,    ...>     other       INT    ...> ); sqlite> INSERT OR IGNORE INTO t (name) VALUES ('a'); sqlite> INSERT OR IGNORE INTO t (name) VALUES ('a'); sqlite> INSERT OR IGNORE INTO t (name) VALUES ('a'); sqlite> select * from t ; 1|a| 
like image 111
wildnove Avatar answered Oct 01 '22 12:10

wildnove