Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQLite Syntax for Creating Table with Foreign Key

I'm creating a table with foreign key references. I'm wondering about the required syntax. Mostly I've seen the following (from http://www.sqlite.org/foreignkeys.html#fk_basics):

CREATE TABLE artist(     artistid    INTEGER PRIMARY KEY,     artistname  TEXT   );   CREATE TABLE track(     trackid     INTEGER,      trackname   TEXT,     trackartist INTEGER,     FOREIGN KEY(trackartist) REFERENCES artist(artistid)   ); 

However, from the same site (http://www.sqlite.org/foreignkeys.html#fk_actions) I see this:

CREATE TABLE artist(     artistid    INTEGER PRIMARY KEY,     artistname  TEXT   );   CREATE TABLE track(     trackid     INTEGER,     trackname   TEXT,      trackartist INTEGER REFERENCES artist(artistid) ON UPDATE CASCADE   ); 

The latter syntax is a little more concise, but I want to know if the result is somehow different (aside from the ON UPDATE CASCADE, which of course has an effect; I only included it because I copied the code exactly from the referenced site, and because I don't know that the above syntax doesn't apply only when making such a specification). I am working in Android, in case that matters.

like image 484
hBrent Avatar asked Aug 22 '13 17:08

hBrent


People also ask

How do you create a table with only foreign keys?

To create a new table containing a foreign key column that references another table, use the keyword FOREIGN KEY REFERENCES at the end of the definition of that column. Follow that with the name of the referenced table and the name of the referenced column in parentheses.

Does SQLite support foreign keys?

SQLite has supported foreign key constraint since version 3.6. 19.

What is the syntax for adding foreign key to a relation?

The syntax for creating a foreign key using a CREATE TABLE statement in SQL Server (Transact-SQL) is: CREATE TABLE child_table ( column1 datatype [ NULL | NOT NULL ], column2 datatype [ NULL | NOT NULL ], ... CONSTRAINT fk_name FOREIGN KEY (child_col1, child_col2, ...


1 Answers

This answer might not be related to yours but i thought it should be helpful for others who are working with android database.
IN SQLite Foreign key constraints are disabled by default (for backwards compatibility). You have to enable it explicitly using

PRAGMA foreign_keys = 1 

after you establishing your connection with the database. Here's the link to the official docs that explains it in more depth. http://sqlite.org/foreignkeys.html Please navigate to enabling foreign key support in the above link.

like image 118
Mightian Avatar answered Sep 17 '22 17:09

Mightian