Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQLite: Preventing Duplicate Rows

CREATE TABLE Permission ( 
    permissionID INTEGER PRIMARY KEY UNIQUE,
    user         INTEGER
    location     INTEGER 
);

I don't want to have user or location to be UNIQUE because I can have multiple rows with user containing the same data, or multiple rows with location containing the same data. I just want to avoid having both user and location having some value, with that row repeating any number of times.

Ex: this is okay

permissionID user location
--------------------------
      1        1     2
      2        2     2
      3        2     1

but this is not okay:

permissionID user location
--------------------------
      1        1     2
      2        1     2

because a row already exists in which user = 1 and location = 2.

How can I avoid duplicates?

like image 823
user1425798 Avatar asked Mar 28 '15 02:03

user1425798


People also ask

How do I prevent duplicate rows from selection?

The go to solution for removing duplicate rows from your result sets is to include the distinct keyword in your select statement. It tells the query engine to remove duplicates to produce a result set in which every row is unique.

When using sqlite If you want to make sure that you do not put duplicates?

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 do I stop inserting duplicate records in MySQL?

Note − 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.


1 Answers

Declare a unique constraint on (user, location).

CREATE TABLE Permission (
    permissionID integer primary key,
    user integer not null,
    location integer not null,
    unique (user, location)
);
sqlite> insert into Permission (user, location) values (1, 2);
sqlite> insert into Permission (user, location) values (1, 2);
Error: UNIQUE constraint failed: Permission.user, Permission.location
like image 193
Mike Sherrill 'Cat Recall' Avatar answered Sep 24 '22 10:09

Mike Sherrill 'Cat Recall'