Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to do IF NOT EXISTS in SQLite

Tags:

sql

sqlite

I am trying to port this line from MS SQL Server to SQLite

IF NOT EXISTS(SELECT 1 FROM EVENTTYPE WHERE EventTypeName = 'ANI Received')      INSERT INTO EVENTTYPE (EventTypeName) VALUES ('ANI Received'); 

It seems that SQLite does not support IF NOT EXISTS or at least I can't make it work. Am I missing something simple? Is there a workaround?

like image 742
AngryHacker Avatar asked Feb 10 '09 04:02

AngryHacker


People also ask

How do you check if data exists in a table SQLite?

SELECT EXISTS(SELECT 1 FROM myTbl WHERE u_tag="tag" LIMIT 1); Selecting 1 is the accepted practice if you don't need something from the record, though what you select shouldn't really matter either way. Put an index on your tag field. If you do not, a query for a non-existent tag will do a full table scan.

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.

What to use instead of not exists?

Using Joins Instead of IN or EXISTS An alternative for IN and EXISTS is an INNER JOIN, while a LEFT OUTER JOIN with a WHERE clause checking for NULL values can be used as an alternative for NOT IN and NOT EXISTS.


2 Answers

How about this?

INSERT OR IGNORE INTO EVENTTYPE (EventTypeName) VALUES 'ANI Received' 

(Untested as I don't have SQLite... however this link is quite descriptive.)

Additionally, this should also work:

INSERT INTO EVENTTYPE (EventTypeName) SELECT 'ANI Received' WHERE NOT EXISTS (SELECT 1 FROM EVENTTYPE WHERE EventTypeName = 'ANI Received'); 
like image 196
beach Avatar answered Sep 23 '22 02:09

beach


If you want to ignore the insertion of existing value, there must be a Key field in your Table. Just create a table With Primary Key Field Like:

CREATE TABLE IF NOT EXISTS TblUsers (UserId INTEGER PRIMARY KEY, UserName varchar(100), ContactName varchar(100),Password varchar(100)); 

And Then Insert Or Replace / Insert Or Ignore Query on the Table Like:

INSERT OR REPLACE INTO TblUsers (UserId, UserName, ContactName ,Password) VALUES('1','UserName','ContactName','Password'); 

It Will Not Let it Re-Enter The Existing Primary key Value... This Is how you can Check Whether a Value exists in the table or not.

like image 44
TheDean Avatar answered Sep 24 '22 02:09

TheDean