Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking duplicate while inserting in SQLite

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.

like image 560
ukanth Avatar asked Jul 19 '10 14:07

ukanth


People also ask

How to avoid INSERT duplicate Data in SQL?

Use the INSERT IGNORE command rather than the INSERT command. If a record doesn't duplicate an existing record, then MySQL inserts it as usual. If the record is a duplicate, then the IGNORE keyword tells MySQL to discard it silently without generating an error.

How to identify Duplicates in SQL?

One way to find duplicate records from the table is the GROUP BY statement. The GROUP BY statement in SQL is used to arrange identical data into groups with the help of some functions. i.e if a particular column has the same values in different rows then it will arrange these rows in a group.

When using sqlite If you want to make sure that you do not put duplicates in your new Favourites table How would you have created your Favourites table?

Option 1: Have a unique constraint in your table. You can put the constraint you want directly in your table: CREATE TABLE Permission ( permissionID INTEGER PRIMARY KEY UNIQUE, user INTEGER, location INTEGER unique (user, location) ); This is the most natural option to express your requirement.

How to check for duplicate entries in MySQL?

First, use the GROUP BY clause to group all rows by the target column, which is the column that you want to check duplicate. Then, use the COUNT() function in the HAVING clause to check if any group have more than 1 element. These groups are duplicate.


1 Answers

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.
like image 161
Piskvor left the building Avatar answered Sep 23 '22 14:09

Piskvor left the building