Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQLite Query to Insert a record If not exists

Tags:

sqlite

I want to insert a record into a sqlite table if its actually not inserted.

Let's say it has three fields pk, name, address

I want to INSERT new record with name if that name not added preveously.

Can we do with this in a single Query. Seems like its slightly different from SQL Queries sometimes.

like image 670
Tharindu Madushanka Avatar asked May 06 '10 09:05

Tharindu Madushanka


People also ask

What does SELECT return if not found SQLite?

The SELECT WHERE NOT EXISTS clause can only return a single row; there is not a FROM clause - there is no way multiple rows can be returned. Hope this clears it up.

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.


2 Answers

Yes, you can do that with a single query.

INSERT ON CONFLICT IGNORE should help you: http://www.sqlite.org/lang_conflict.html

Put a unique key on the name, this will create a conflict when you try inserting a record if the name already exists.

The default is ABORT, so without the IGNORE, the statement will return an error. If you don't want that, use IGNORE.

like image 85
Konerak Avatar answered Oct 07 '22 08:10

Konerak


If you can't make use of a UNIQUE INDEX in combination with INSERT INTO or INSERT OR IGNORE INTO, you could write a query like this;

INSERT INTO table (column) SELECT value WHERE NOT EXISTS (SELECT 1                    FROM table                    WHERE column = value) 
like image 44
SQLighter Avatar answered Oct 07 '22 08:10

SQLighter