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.
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.
SQLite has supported foreign key constraint since version 3.6. 19.
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, ...
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.
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