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-column
s in a single constraint.
Column-constraint:
Table-constraint:
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?
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.
A unique constraint will create an index. An index will drastically improve your query. With no index you will read all the table.
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.
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.
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
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