Checking duplicate while inserting in SQLite
Asked Answered
K

3

6

I am trying to insert a data into SQLite database using Python.

INSERT INTO DATA_TABLE(UID,LABEL) VALUES (NULL, "UK")  
    WHERE "UK" NOT EXISTS IN (SELECT LABEL FROM DATA_TABLE);

This query is dynamically generated from Python and I am checking whether the date is already exist in the table before inserting and its not working in SQLite database. Getting this near "WHERE": syntax error error.

Am I doing something wrong ?

Thanks for your help.

Kingdom answered 19/7, 2010 at 14:9 Comment(0)
F
2

I'm pretty sure that INSERT doesn't have a WHERE clause (the documentation doesn't mention any). What you can do:

  • create a unique index on LABEL
  • use INSERT OR FAIL
  • if that triggers an error, the row already exists.
Feudalize answered 19/7, 2010 at 14:14 Comment(1)
Yes, I didn't aware of that. Thanks :)Kingdom
I
2

It is giving you a syntax error because it is not allowed syntax. From your example I presume the schema is probably:

create table data_table (uid integer primary key autoincrement.
     label string);

in which case primary key implies unique. But, since you allow auto-generation of uid then you don't care what it's value is, you just don't want duplicate labels in which case you actually care that label be unique so tell it so:

create table data_table (uid integer primary key autoincrement,
     label string unique on conflict fail);

which then works as expected:

sqlite> insert into data_table (label) values ("uk");
sqlite> insert into data_table (label) values ("uk");
Error: column label is not unique
sqlite> select * from data_table;
1|uk

Incidentally, if the names data_table, uid, and label aren't example names for the purposes of this question then you should use more meaningful names as these are horribly uninformative.

Incitement answered 19/7, 2010 at 14:35 Comment(1)
Thanks @Incitement , thats true. names are just example's , I am using label as a unique.Kingdom
S
1
INSERT INTO DATA_TABLE(UID,LABEL) VALUES (NULL, "UK")  
WHERE NOT EXISTS(SELECT 1 FROM DATA_TABLE WHERE LABEL="UK");

you can use this instead of INSERT OR FAIL.

Snake answered 19/7, 2010 at 19:42 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.