Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQLite - Any difference between table-constraint UNIQUE & column-constraint UNIQUE?

Question about SQLite.

In the CREATE TABLE SQL, we can add UNIQUE constraints in either way: column-constraint or table-constraint. My question is simple. Do they work differently?

The only difference I could find was, in table-constraint, there could be multiple indexed-columns in a single constraint.

Column-constraint: enter image description here

Table-constraint: enter image description here

Here is an example:

CREATE TABLE Example (
    _id INTEGER PRIMARY KEY,
    name TEXT UNIQUE ON CONFLICT REPLACE,
    score INTEGER
)

and

CREATE TABLE Example (
    _id INTEGER PRIMARY KEY,
    name TEXT,
    score INTEGER,
    UNIQUE (name) ON CONFLICT REPLACE
)

Are they different?

like image 958
Naetmul Avatar asked May 27 '13 09:05

Naetmul


People also ask

Is unique key same as unique constraint?

A unique constraint is the rule that the values of a key are valid only if they are unique. A key that is constrained to have unique values is called a unique key . A unique constraint is enforced by using a unique index.

Does unique constraint improve performance?

A unique constraint will create an index. An index will drastically improve your query. With no index you will read all the table.

Can a table have two unique constraints?

A PRIMARY KEY constraint automatically has a UNIQUE constraint. However, you can have many UNIQUE constraints per table, but only one PRIMARY KEY constraint per table.

What is unique constraint in SQLite?

Introduction to SQLite UNIQUE constraint A UNIQUE constraint ensures all values in a column or a group of columns are distinct from one another or unique. 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.


1 Answers

In this case there is no difference.

However, you could create an unique constraint on table, that would span over two different columns. Like this:

CREATE TABLE Example (
    _id INTEGER PRIMARY KEY,
    name TEXT,
    index INTEGER,
    score INTEGER,
    UNIQUE (name, index) ON CONFLICT REPLACE
)

Consult this post for further details: SQLite table constraint - unique on multiple columns

like image 112
Dariusz Avatar answered Oct 02 '22 22:10

Dariusz