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?
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With