Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sqlite create unique pair of columns

Tags:

sqlite

unique

I want to create a table with two columns: user_id, image_id. I don't want user_id or image_id to be unique, but I also want to protect my table from duplicate pairs of same user_id and image_id. Can I do that?

like image 768
Ilya Gazman Avatar asked Apr 04 '13 18:04

Ilya Gazman


People also ask

How do I create a unique two column combination in SQLite?

To define a UNIQUE constraint, you use the UNIQUE keyword followed by one or more columns. You can define a UNIQUE constraint at the column or the table level. Only at the table level, you can define a UNIQUE constraint across multiple columns.

How do you make a unique two column combination?

To define a UNIQUE on multiple columns, we put a comma-separated columns list inside parenthesis that follows the UNIQUE keyword.

Can a table have 2 unique columns?

Yes, you can define UNIQUE constraints to columns other than the primary key in order to ensure the data is unique between rows.

How do I get unique values from a column in SQLite?

If we define DISTINCT for one column in SQLite select statement then the DISTINCT clause will return unique values only for that column. In case if we use DISTINCT for multiple columns in SQLite SELECT statement then DISTINCT will use a combination of those columns to evaluate the duplicate values.


1 Answers

Add a separate constraint for both columns:

CREATE TABLE MyTable(
    user_id INTEGER,
    image_id INTEGER,
    [...],
    UNIQUE(user_id, image_id)
)
like image 147
CL. Avatar answered Sep 24 '22 13:09

CL.