Poly Bug
Poly Bug

Reputation: 1542

sqlite column constraints both unique and foreign

Does sqlite allow a column to be both unique and a foreign key at the same time?
How does the definition look like?

CREATE TABLE table1 (
    id INTEGER PRIMARY KEY,
    fkey INTEGER NOT NULL UNIQUE REFERENCES table2(id)
)

CREATE TABLE table2 (
    id INTEGER PRIMARY KEY
)

Upvotes: 0

Views: 77

Answers (1)

Gatunox
Gatunox

Reputation: 532

Sure

CREATE TABLE table1 ( id INTEGER PRIMARY KEY, fkey INTEGER NOT NULL UNIQUE, FOREIGN KEY(fkey) REFERENCES table2(id) )

result.

Query executed successfully: CREATE TABLE table1 ( id INTEGER PRIMARY KEY, fkey INTEGER NOT NULL UNIQUE, FOREIGN KEY(fkey) REFERENCES table2(id) ) (took 0ms)

REMEMBER. As of version 3.6.19, SQLite supports foreign key constraints. But enforcement of foreign key constraints is turned off by default (for backwards compatibility). To enable foreign key constraint enforcement, run PRAGMA foreign_keys=ON, from http://sqlite.org/faq.html

Upvotes: 1

Related Questions