foreignkeys.html 43 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986
  1. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
  2. <html><head>
  3. <title>SQLite Foreign Key Support</title>
  4. <style type="text/css">
  5. body {
  6. margin: auto;
  7. font-family: Verdana, sans-serif;
  8. padding: 8px 1%;
  9. }
  10. a { color: #45735f }
  11. a:visited { color: #734559 }
  12. .logo { position:absolute; margin:3px; }
  13. .tagline {
  14. float:right;
  15. text-align:right;
  16. font-style:italic;
  17. width:240px;
  18. margin:12px;
  19. margin-top:58px;
  20. }
  21. .toolbar {
  22. font-variant: small-caps;
  23. text-align: center;
  24. line-height: 1.6em;
  25. margin: 0;
  26. padding:1px 8px;
  27. }
  28. .toolbar a { color: white; text-decoration: none; padding: 6px 12px; }
  29. .toolbar a:visited { color: white; }
  30. .toolbar a:hover { color: #80a796; background: white; }
  31. .content { margin: 5%; }
  32. .content dt { font-weight:bold; }
  33. .content dd { margin-bottom: 25px; margin-left:20%; }
  34. .content ul { padding:0px; padding-left: 15px; margin:0px; }
  35. /* rounded corners */
  36. .se { background: url(images/se.png) 100% 100% no-repeat #80a796}
  37. .sw { background: url(images/sw.png) 0% 100% no-repeat }
  38. .ne { background: url(images/ne.png) 100% 0% no-repeat }
  39. .nw { background: url(images/nw.png) 0% 0% no-repeat }
  40. </style>
  41. <meta http-equiv="content-type" content="text/html; charset=UTF-8">
  42. </head>
  43. <body>
  44. <div><!-- container div to satisfy validator -->
  45. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
  46. <html>
  47. <head>
  48. <link type="text/css" rel="stylesheet" href="images/fileformat/rtdocs.css">
  49. </head>
  50. <body>
  51. <div id=document_title>SQLite Foreign Key Support</div>
  52. <div id=toc_header>Table Of Contents</div>
  53. <div id=toc>
  54. <div style="margin-left:6ex">
  55. <a href="#fk_basics">1 Introduction to Foreign Key Constraints</a>
  56. </a></div>
  57. <div style="margin-left:6ex">
  58. <a href="#fk_enable">2 Enabling Foreign Key Support</a>
  59. </a></div>
  60. <div style="margin-left:6ex">
  61. <a href="#fk_indexes">3 Required and Suggested Database Indexes</a>
  62. </a></div>
  63. <div style="margin-left:6ex">
  64. <a href="#fk_advanced">4 Advanced Foreign Key Constraint Features</a>
  65. </a></div>
  66. <div style="margin-left:12ex">
  67. <a href="#fk_composite">4.1 Composite Foreign Key Constraints</a>
  68. </a></div>
  69. <div style="margin-left:12ex">
  70. <a href="#fk_deferred">4.2 Deferred Foreign Key Constraints</a>
  71. </a></div>
  72. <div style="margin-left:12ex">
  73. <a href="#fk_actions">4.3 ON DELETE and ON UPDATE Actions</a>
  74. </a></div>
  75. <div style="margin-left:6ex">
  76. <a href="#fk_schemacommands">5 CREATE, ALTER and DROP TABLE commands</a>
  77. </a></div>
  78. <div style="margin-left:6ex">
  79. <a href="#fk_unsupported">6 Limits and Unsupported Features</a>
  80. </a></div>
  81. </div id>
  82. <h2 style="margin-left:1.0em"> Overview</h2>
  83. <p>This document describes the support for SQL foreign key constraints
  84. introduced in SQLite version 3.6.19.
  85. <p>The first section introduces the
  86. concept of an SQL foreign key by example and defines the terminology
  87. used for the remainder of the document. Section 2 describes the steps
  88. an application must take in order to enable foreign key constraints in
  89. SQLite (it is disabled by default). The next section, section 3,
  90. describes the indexes that the user must create in order to use
  91. foreign key constraints, and those that should be created in order for
  92. foreign key constraints to function efficiently. Section 4 describes
  93. the advanced foreign key related features supported by SQLite and
  94. section 5 describes the way the <a href="lang_altertable.html">ALTER</a> and <a href="lang_droptable.html">DROP TABLE</a> commands are
  95. enhanced to support foreign key constraints. Finally, section 6
  96. enumerates the missing features and limits of the current implementation.
  97. <p>This document does not contain a full description of the syntax used
  98. to create foreign key constraints in SQLite. This may be found as
  99. part of the documentation for the <a href="lang_createtable.html">CREATE TABLE</a> statement.
  100. <h1 id="fk_basics">1 Introduction to Foreign Key Constraints</h1>
  101. <p>
  102. SQL foreign key constraints are used to enforce "exists" relationships
  103. between tables. For example, consider a database schema created using
  104. the following SQL commands:
  105. <div class=codeblock><table width=100%><tr><td><pre>CREATE TABLE artist(
  106. artistid INTEGER PRIMARY KEY,
  107. artistname TEXT
  108. );
  109. CREATE TABLE track(
  110. trackid INTEGER,
  111. trackname TEXT,
  112. trackartist INTEGER <b>-- Must map to an artist.artistid!</b>
  113. );
  114. </table></div>
  115. <p>
  116. The applications using this database are entitled to assume that for
  117. each row in the <i>track</i> table there exists a corresponding row in the
  118. <i>artist</i> table. After all, the comment in the declaration says so.
  119. Unfortunately, if a user edits the database using an external tool or
  120. if there is a bug in an application, rows might be inserted into the
  121. <i>track</i> table that do not correspond to any row in the <i>artist</i>
  122. table. Or rows might be deleted from the <i>artist</i> table, leaving
  123. orphaned rows in the <i>track</i> table that do not correspond to any of
  124. the remaining rows in <i>artist</i>. This might cause the application
  125. or applications to malfunction later on, or at least make coding the
  126. application more difficult.
  127. <p>
  128. One solution is to add an SQL foreign key constraint to the database
  129. schema to enforce the relationship between the <i>artist</i> and
  130. <i>track</i> table. To do so, a foreign key definition may be added
  131. by modifying the declaration of the <i>track</i> table to the following:
  132. <div class=codeblock><table width=100%><tr><td><pre>CREATE TABLE track(
  133. trackid INTEGER,
  134. trackname TEXT,
  135. trackartist INTEGER,
  136. <b>FOREIGN KEY(trackartist) REFERENCES artist(artistid)</b>
  137. );
  138. </table></div>
  139. <p>
  140. This way, the constraint is enforced by SQLite. Attempting to insert
  141. a row into the <i>track</i> table that does not correspond to any
  142. row in the <i>artist</i> table will fail, as will attempting to
  143. delete a row from the <i>artist</i> table when there exist dependent
  144. rows in the <i>track</i> table There is one exception: if the foreign
  145. key column in the <i>track</i> table is NULL, then no corresponding
  146. entry in the <i>artist</i> table is required. Expressed in SQL, this
  147. means that for every row in the <i>track</i> table, the following
  148. expression evaluates to true:
  149. <div class=codeblock><table width=100%><tr><td><pre>trackartist IS NULL OR EXISTS(SELECT 1 FROM artist WHERE artistid=trackartist)
  150. </table></div>
  151. <p>Tip: If the application requires a stricter relationship between
  152. <i>artist</i> and <i>track</i>, where NULL values are not permitted
  153. in the <i>trackartist</i> column, simply add the appropriate
  154. "NOT NULL" constraint to the schema.
  155. <p>There are several other ways to add an equivalent foreign key declaration
  156. to a <a href="lang_createtable.html">CREATE TABLE</a> statement. Refer to the
  157. <a href="lang_createtable.html">CREATE TABLE documentation</a> for details.
  158. <p>The following SQLite command-line session illustrates the effect of the
  159. foreign key constraint added to the <i>track</i> table:
  160. <div class=codeblock><table width=100%><tr><td><pre>sqlite&gt; SELECT * FROM artist;
  161. artistid artistname
  162. -------- -----------------
  163. 1 Dean Martin
  164. 2 Frank Sinatra
  165. sqlite> SELECT * FROM track;
  166. trackid trackname trackartist
  167. ------- ----------------- -----------
  168. 11 That's Amore 1
  169. 12 Christmas Blues 1
  170. 13 My Way 2
  171. sqlite&gt; <i>-- This fails because the value inserted into the trackartist column (3)</i>
  172. sqlite&gt; <i>-- does not correspond to row in the artist table.</i>
  173. sqlite&gt; INSERT INTO track VALUES(14, 'Mr. Bojangles', 3);
  174. <b>SQL error: foreign key constraint failed</b>
  175. sqlite&gt; <i>-- This succeeds because a NULL is inserted into trackartist. A</i>
  176. sqlite&gt; <i>-- corresponding row in the artist table is not required in this case.</i>
  177. sqlite&gt; INSERT INTO track VALUES(14, 'Mr. Bojangles', NULL);
  178. sqlite&gt; <i>-- Trying to modify the trackartist field of the record after it has </i>
  179. sqlite&gt; <i>-- been inserted does not work either, since the new value of trackartist (3)</i>
  180. sqlite&gt; <i>-- Still does not correspond to any row in the artist table.</i>
  181. sqlite&gt; UPDATE track SET trackartist = 3 WHERE trackname = 'Mr. Bojangles';
  182. <b>SQL error: foreign key constraint failed</b>
  183. sqlite&gt; <i>-- Insert the required row into the artist table. It is then possible to</i>
  184. sqlite&gt; <i>-- update the inserted row to set trackartist to 3 (since a corresponding</i>
  185. sqlite&gt; <i>-- row in the artist table now exists).</i>
  186. sqlite&gt; INSERT INTO artist VALUES(3, 'Sammy Davis Jr.');
  187. sqlite&gt; UPDATE track SET trackartist = 3 WHERE trackname = 'Mr. Bojangles';
  188. sqlite&gt; <i>-- Now that "Sammy Davis Jr." (artistid = 3) has been added to the database,</i>
  189. sqlite&gt; <i>-- it is possible to INSERT new tracks using this artist without violating</i>
  190. sqlite&gt; <i>-- the foreign key constraint:</i>
  191. sqlite&gt; INSERT INTO track VALUES(15, 'Boogie Woogie', 3);
  192. </table></div>
  193. <p>
  194. As you would expect, it is not possible to manipulate the database to a state
  195. that violates the foreign key constraint by deleting or updating rows in the
  196. <i>artist</i> table either:
  197. <div class=codeblock><table width=100%><tr><td><pre>sqlite&gt; <i>-- Attempting to delete the artist record for "Frank Sinatra" fails, since</i>
  198. sqlite&gt; <i>-- the track table contains a row that refer to it.</i>
  199. sqlite&gt; DELETE FROM artist WHERE artistname = 'Frank Sinatra';
  200. <b>SQL error: foreign key constraint failed</b>
  201. sqlite&gt; <i>-- Delete all the records from the track table that refer to the artist</i>
  202. sqlite&gt; <i>-- "Frank Sinatra". Only then is it possible to delete the artist.</i>
  203. sqlite&gt; DELETE FROM track WHERE trackname = 'My Way';
  204. sqlite&gt; DELETE FROM artist WHERE artistname = 'Frank Sinatra';
  205. sqlite&gt; <i>-- Try to update the artistid of a row in the artist table while there</i>
  206. sqlite&gt; <i>-- exists records in the track table that refer to it. </i>
  207. sqlite&gt; UPDATE artist SET artistid=4 WHERE artistname = 'Dean Martin';
  208. <b>SQL error: foreign key constraint failed</b>
  209. sqlite&gt; <i>-- Once all the records that refer to a row in the artist table have</i>
  210. sqlite&gt; <i>-- been deleted, it is possible to modify the artistid of the row.</i>
  211. sqlite&gt; DELETE FROM track WHERE trackname IN('That''s Amore', 'Christmas Blues');
  212. sqlite&gt; UPDATE artist SET artistid=4 WHERE artistname = 'Dean Martin';
  213. </table></div>
  214. <p>
  215. SQLite uses the following terminology:
  216. <a name="parentchild"></a>
  217. <ul>
  218. <li><p>The <b>parent table</b> is the table that a foreign key constraint
  219. refers to. The parent table in the example in this section is the
  220. <i>artist</i> table. Some books and articles refer to this as the
  221. <i>referenced table</i>, which is arguably more correct, but tends
  222. to lead to confusion.
  223. <li><p>The <b>child table</b> is the table that a foreign key constraint
  224. is applied to and the table that contains the REFERENCES clause.
  225. The example in this section uses the <i>track</i> table
  226. as the child table. Other books and articles refer to this as the
  227. <i>referencing table</i>.
  228. <li><p>The <b>parent key</b> is the column or set of columns in the parent
  229. table that the foreign key constraint refers to. This is normally, but
  230. not always, the primary key of the parent table.
  231. <li><p>The <b>child key</b> is the column or set of columns in the child
  232. table that are constrained by the foreign key constraint and which
  233. hold the REFERENCES clause.
  234. </ul>
  235. <p>
  236. The foreign key constraint is satisfied if for each row in the child table
  237. either one or more of the child key columns are NULL, or there exists a
  238. row in the parent table for which each parent key column contains a value
  239. equal to the value in its associated child key column.
  240. <p>
  241. In the above paragraph, the term "equal" means equal when values are
  242. compared using the rules <a href="datatype3.html#comparisons">specified
  243. here</a>. The following clarifications apply:
  244. <ul>
  245. <li><p>When comparing text values, the <a href="datatype3.html#collation">collating sequence</a>
  246. associated with the parent key column is always used.
  247. <li><p>When comparing values, if the parent key column has an <a href="datatype3.html#affinity">affinity</a>,
  248. then that affinity is applied to the child key value before the
  249. comparison is performed.
  250. </ul>
  251. <h1 id="fk_enable">2 Enabling Foreign Key Support</h1>
  252. <p>
  253. In order to use foreign key constraints in SQLite, the library must
  254. be compiled with neither <a href="compile.html#omit_foreign_key">SQLITE_OMIT_FOREIGN_KEY</a> or
  255. <a href="compile.html#omit_trigger">SQLITE_OMIT_TRIGGER</a> defined. If SQLITE_OMIT_TRIGGER is defined
  256. but SQLITE_OMIT_FOREIGN_KEY is not, then SQLite behaves as it did prior
  257. to version 3.6.19 - foreign key definitions are parsed and may be
  258. queried using <a href="pragma.html#pragma_foreign_key_list">PRAGMA foreign_key_list</a>, but foreign key constraints
  259. are not enforced. The <a href="pragma.html#pragma_foreign_keys">PRAGMA foreign_keys</a> command is a no-op in this
  260. configuration. If OMIT_FOREIGN_KEY is defined, then foreign key
  261. definitions cannot even be parsed (attempting to specify a foreign
  262. key definition is a syntax error).
  263. <p>
  264. Assuming the library is compiled with foreign key constraints enabled,
  265. it must still be enabled by the application at runtime, using the
  266. <a href="pragma.html#pragma_foreign_keys">PRAGMA foreign_keys</a> command. For example:
  267. <div class=codeblock><table width=100%><tr><td><pre>sqlite&gt; PRAGMA foreign_keys = ON;
  268. </table></div>
  269. <p>
  270. Foreign key constraints are disabled by default
  271. (for backwards compatibility),
  272. so must be enabled separately for each <a href="c3ref/sqlite3.html">database connection</a>
  273. separately.
  274. (Note, however, that future releases of SQLite might change
  275. so that foreign key constraints enabled by default. Careful
  276. developers will not
  277. make any assumptions about whether or not foreign keys are enabled by
  278. default but will instead enable or disable them as necessary.)
  279. The application can can also use a <a href="pragma.html#pragma_foreign_keys">PRAGMA foreign_keys</a> statement to
  280. determine if foreign keys are currently enabled. The following
  281. command-line session demonstrates this:
  282. <div class=codeblock><table width=100%><tr><td><pre>sqlite> PRAGMA foreign_keys;
  283. 0
  284. sqlite> PRAGMA foreign_keys = ON;
  285. sqlite> PRAGMA foreign_keys;
  286. 1
  287. sqlite> PRAGMA foreign_keys = OFF;
  288. sqlite> PRAGMA foreign_keys;
  289. 0
  290. </table></div>
  291. <p>Tip: If the command "PRAGMA foreign_keys" returns no data instead of a
  292. single row containing "0" or "1", then the version of SQLite you are
  293. using does not support foreign keys (either because it is older than
  294. 3.6.19 or because it was compiled with <a href="compile.html#omit_foreign_key">SQLITE_OMIT_FOREIGN_KEY</a> or
  295. <a href="compile.html#omit_trigger">SQLITE_OMIT_TRIGGER</a> defined).
  296. <p>
  297. It is not possible to enable or disable foreign key constraints
  298. in the middle of a <a href="lang_transaction.html">multi-statement transaction</a> (when SQLite
  299. is not in <a href="c3ref/get_autocommit.html">autocommit mode</a>). Attempting to do so does not return
  300. an error; it simply has no effect.
  301. <h1 id="fk_indexes">3 Required and Suggested Database Indexes</h1>
  302. <p>
  303. Usually, the parent key of a foreign key constraint is the primary key of
  304. the parent table. If they are not the primary key, then the parent key
  305. columns must be collectively subject to a UNIQUE constraint or have
  306. a UNIQUE index.
  307. If the parent key columns have a UNIQUE index,
  308. then that index must use the collation sequences that are specified
  309. in the CREATE TABLE statement for the parent table.
  310. For example,
  311. <div class=codeblock><table width=100%><tr><td><pre>CREATE TABLE parent(a PRIMARY KEY, b UNIQUE, c, d, e, f);
  312. CREATE UNIQUE INDEX i1 ON parent(c, d);
  313. CREATE INDEX i2 ON parent(e);
  314. CREATE UNIQUE INDEX i3 ON parent(f COLLATE nocase);
  315. CREATE TABLE child1(f, g REFERENCES parent(a)); <i>-- Ok</i>
  316. CREATE TABLE child2(h, i REFERENCES parent(b)); <i>-- Ok</i>
  317. CREATE TABLE child3(j, k, FOREIGN KEY(j, k) REFERENCES parent(c, d)); <i>-- Ok</i>
  318. CREATE TABLE child4(l, m REFERENCES parent(e)); <i>-- Error!</i>
  319. CREATE TABLE child5(n, o REFERENCES parent(f)); <i>-- Error!</i>
  320. CREATE TABLE child6(p, q, FOREIGN KEY(p, q) REFERENCES parent(b, c)); <i>-- Error!</i>
  321. CREATE TABLE child7(r REFERENCES parent(c)); <i>-- Error!</i>
  322. </table></div>
  323. <p>
  324. The foreign key constraints created as part of tables <i>child1</i>,
  325. <i>child2</i> and <i>child3</i> are all fine. The foreign key
  326. declared as part of table <i>child4</i> is an error because even though
  327. the parent key column is indexed, the index is not UNIQUE.
  328. The foreign key for table <i>child5</i>
  329. is an error because even though the parent key column has a unique
  330. index, the index uses a different collating sequence.
  331. Tables <i>child6</i> and <i>child7</i> are incorrect because while
  332. both have UNIQUE indices on their parent keys, the keys are not an
  333. exact match to the columns of a single UNIQUE index.
  334. <p>
  335. If the database schema contains foreign key errors that require looking
  336. at more than one table definition to identify, then those errors are not
  337. detected when the tables are created. Instead, such errors prevent
  338. the application from preparing SQL statements that modify the content
  339. of the child or parent tables in ways that use the foreign keys.
  340. Errors reported when content is changed are "DML errors" and errors
  341. reported when the schema is changed are "DDL errors".
  342. So, in other words, misconfigured foreign key constraints that require
  343. looking at both the child and parent are DML errors.
  344. The English language error message for foreign key DML errors is usually
  345. "foreign key mismatch" but can also be "no such table" if the parent
  346. table does not exist.
  347. Foreign key DML errors are may be reported if:
  348. <ul>
  349. <li> The parent table does not exist, or
  350. <li> The parent key columns named in the foreign key constraint do
  351. not exist, or
  352. <li> The parent key columns named in the foreign key constraint are not
  353. the primary key of the parent table and are not subject to a unique
  354. constraint using collating sequence specified in the CREATE TABLE, or
  355. <li> The child table references the primary key of the parent without
  356. specifying the primary key columns and the number of primary key
  357. columns in the parent do not match the number of child key columns.
  358. </ul>
  359. <p>
  360. The last bullet above is illustrated by the following:
  361. <div class=codeblock><table width=100%><tr><td><pre>CREATE TABLE parent2(a, b, PRIMARY KEY(a,b));
  362. CREATE TABLE child8(x, y, FOREIGN KEY(x,y) REFERENCES parent2); <i>-- Ok</i>
  363. CREATE TABLE child9(x REFERENCES parent2); <i>-- Error!</i>
  364. CREATE TABLE child10(x,y,z, FOREIGN KEY(x,y,z) REFERENCES parent2); <i>-- Error!</i>
  365. </table></div>
  366. <p>
  367. By contrast, if foreign key errors can be recognized simply by looking
  368. at the definition of the child table and without having to consult the
  369. parent table definition, then the
  370. <a href="lang_createtable.html">CREATE TABLE</a> statement for the child table fails. Because the error
  371. occurs during a schema change, this is a DDL error.
  372. Foreign key DDL errors are reported regardless of
  373. whether or not foreign key constraints are enabled when the
  374. table is created.
  375. <p>
  376. Indices are not required for child key columns but they are almost
  377. always beneficial. Returning to
  378. the example in <a href=#fk_basics>section 1</a>, each time an application
  379. deletes a row from the <i>artist</i> table (the parent table), it
  380. performs the equivalent of the following SELECT statement to search
  381. for referencing rows in the <i>track</i> table (the child table).
  382. <div class=codeblock><table width=100%><tr><td><pre>SELECT rowid FROM track WHERE trackartist = ?
  383. </table></div>
  384. <p>
  385. where ? in the above is replaced with the value of the <i>artistid</i>
  386. column of the record being deleted from the <i>artist</i> table (recall
  387. that the <i>trackartist</i> column is the child key and the <i>artistid</i>
  388. column is the parent key). Or, more generally:
  389. <div class=codeblock><table width=100%><tr><td><pre>SELECT rowid FROM &lt;child-table&gt; WHERE &lt;child-key&gt; = :parent_key_value
  390. </table></div>
  391. <p>
  392. If this SELECT returns any rows at all, then SQLite concludes that
  393. deleting the row from the parent table would violate the foreign key
  394. constraint and returns an error.
  395. Similar queries may be run if the content of the parent key
  396. is modified or a new row is inserted into the parent table.
  397. If these queries cannot use an index, they are forced to do a
  398. linear scan of the entire child table. In a non-trivial database, this may
  399. be prohibitively expensive.
  400. <p>
  401. So, in most real systems, an index should be created on the child key columns
  402. of each foreign key constraint. The child key index does not have
  403. to be (and usually will not be) a UNIQUE index.
  404. Returning again to the example in section 1, the
  405. complete database schema for efficient implementation of the foreign key
  406. constraint might be:
  407. <div class=codeblock><table width=100%><tr><td><pre>CREATE TABLE artist(
  408. artistid INTEGER PRIMARY KEY,
  409. artistname TEXT
  410. );
  411. CREATE TABLE track(
  412. trackid INTEGER,
  413. trackname TEXT,
  414. trackartist INTEGER REFERENCES artist
  415. );
  416. CREATE INDEX trackindex ON track(trackartist);
  417. </table></div>
  418. <p>
  419. The block above uses a shorthand form to create the foreign key constraint.
  420. Attaching a "REFERENCES <i>&lt;parent-table&gt;</i>" clause to a column
  421. definition creates a foreign key constraint that maps the column to the
  422. primary key of <i>&lt;parent-table&gt;</i>. Refer to the <a href="lang_createtable.html">CREATE TABLE</a>
  423. documentation for further details.
  424. <h1 id="fk_advanced">4 Advanced Foreign Key Constraint Features</h1>
  425. <h2 id="fk_composite">4.1 Composite Foreign Key Constraints</h2>
  426. <p>
  427. A composite foreign key constraint is one where the child and parent keys
  428. are both composite keys. For example, consider
  429. the following database schema:
  430. <div class=codeblock><table width=100%><tr><td><pre>CREATE TABLE album(
  431. albumartist TEXT,
  432. albumname TEXT,
  433. albumcover BINARY,
  434. PRIMARY KEY(albumartist, albumname)
  435. );
  436. CREATE TABLE song(
  437. songid INTEGER,
  438. songartist TEXT,
  439. songalbum TEXT,
  440. songname TEXT,
  441. <b>FOREIGN KEY(songartist, songalbum) REFERENCES album(albumartist, albumname)</b>
  442. );
  443. </table></div>
  444. <p>
  445. In this system, each entry in the song table is required to map to an entry
  446. in the album table with the same combination of artist and album.
  447. <p>
  448. Parent and child keys must have the same cardinality.
  449. In SQLite, if any of the child key columns (in this case songartist
  450. and songalbum) are NULL, then there is no requirement for a corresponding
  451. row in the parent table.
  452. <h2 id="fk_deferred">4.2 Deferred Foreign Key Constraints</h2>
  453. <p>
  454. Each foreign key constraint in SQLite is classified as either immediate
  455. or deferred. Foreign key constraints are immediate by default.
  456. All the foreign key examples presented
  457. so far have been of immediate foreign key constraints.
  458. <p>
  459. If a statement modifies the contents of the database so that an immediate
  460. foreign key constraint is in violation at the conclusion the statement,
  461. an exception is thrown and
  462. the effects of the statement are reverted. By contrast, if
  463. a statement modifies the contents of the database such that a deferred
  464. foreign key constraint is violated, the violation is not reported
  465. immediately. Deferred foreign key constraints are not checked
  466. until the transaction tries to <a href="lang_transaction.html">COMMIT</a>.
  467. For as long as the user has
  468. an open transaction, the database is allowed to exist in a state that
  469. violates any number of deferred foreign key constraints. However,
  470. <a href="lang_transaction.html">COMMIT</a> will fail as long as foreign key constraints remain in
  471. violation.
  472. <p>
  473. If the current statement is not inside an explicit transaction (a
  474. <a href="lang_transaction.html">BEGIN</a>/<a href="lang_transaction.html">COMMIT</a>/<a href="lang_transaction.html">ROLLBACK</a> block), then an implicit
  475. transaction is committed
  476. as soon as the statement has finished executing. In this case deferred
  477. constraints behave the same as immediate constraints.
  478. <p>
  479. To mark a foreign key constraint as deferred, its declaration must
  480. include the following clause:
  481. <div class=codeblock><table width=100%><tr><td><pre>DEFERRABLE INITIALLY DEFERRED <i>-- A deferred foreign key constraint</i>
  482. </table></div>
  483. <p>
  484. The full syntax for specifying foreign key constraints is available as part
  485. of the <a href="lang_createtable.html">CREATE TABLE</a> documentation. Replacing the phrase above
  486. with any of the following
  487. creates an immediate foreign key constraint.
  488. <div class=codeblock><table width=100%><tr><td><pre>NOT DEFERRABLE INITIALLY DEFERRED <i>-- An immediate foreign key constraint</i>
  489. NOT DEFERRABLE INITIALLY IMMEDIATE <i>-- An immediate foreign key constraint</i>
  490. NOT DEFERRABLE <i>-- An immediate foreign key constraint</i>
  491. DEFERRABLE INITIALLY IMMEDIATE <i>-- An immediate foreign key constraint</i>
  492. DEFERRABLE <i>-- An immediate foreign key constraint</i>
  493. </table></div>
  494. <p>
  495. The following example illustrates the effect of using a deferred foreign
  496. key constraint.
  497. <div class=codeblock><table width=100%><tr><td><pre><i>-- Database schema. Both tables are initially empty. </i>
  498. CREATE TABLE artist(
  499. artistid INTEGER PRIMARY KEY,
  500. artistname TEXT
  501. );
  502. CREATE TABLE track(
  503. trackid INTEGER,
  504. trackname TEXT,
  505. trackartist INTEGER REFERENCES artist(artistid) <b>DEFERRABLE INITIALLY DEFERRED</b>
  506. );
  507. sqlite3&gt; <i>-- If the foreign key constraint were immediate, this INSERT would</i>
  508. sqlite3&gt; <i>-- cause an error (since as there is no row in table artist with</i>
  509. sqlite3&gt; <i>-- artistid=5). But as the constraint is deferred and there is an</i>
  510. sqlite3&gt; <i>-- open transaction, no error occurs.</i>
  511. sqlite3&gt; BEGIN;
  512. sqlite3&gt; INSERT INTO track VALUES(1, 'White Christmas', 5);
  513. sqlite3&gt; <i>-- The following COMMIT fails, as the database is in a state that</i>
  514. sqlite3&gt; <i>-- does not satisfy the deferred foreign key constraint. The</i>
  515. sqlite3&gt; <i>-- transaction remains open.</i>
  516. sqlite3&gt; COMMIT;
  517. <b>SQL error: foreign key constraint failed</b>
  518. sqlite3&gt; <i>-- After inserting a row into the artist table with artistid=5, the</i>
  519. sqlite3&gt; <i>-- deferred foreign key constraint is satisfied. It is then possible</i>
  520. sqlite3&gt; <i>-- to commit the transaction without error.</i>
  521. sqlite3&gt; INSERT INTO artist VALUES(5, 'Bing Crosby');
  522. sqlite3&gt; COMMIT;
  523. </table></div>
  524. <p>
  525. A <a href="lang_savepoint.html">nested savepoint</a> transaction may be RELEASEd while the
  526. database is in a state that does not satisfy a deferred foreign key
  527. constraint. A transaction savepoint (a non-nested savepoint that was
  528. opened while there was not currently an open transaction), on the
  529. other hand, is subject to the same restrictions as a COMMIT - attempting
  530. to RELEASE it while the database is in such a state will fail.
  531. <p>
  532. If a COMMIT statement (or the RELEASE of a transaction SAVEPOINT) fails
  533. because the database is currently in a state that violates a deferred
  534. foreign key constraint and there are currently
  535. <a href="lang_savepoint.html">nested savepoints</a>, the nested savepoints remain open.
  536. <h2 id="fk_actions">4.3 ON DELETE and ON UPDATE Actions</h2>
  537. <p>
  538. Foreign key ON DELETE and ON UPDATE clauses are used to configure actions
  539. that take place when deleting rows from the parent table (ON DELETE), or
  540. modifying the parent key values of existing rows (ON UPDATE). A single
  541. foreign key constraint may have different actions configured for ON DELETE
  542. and ON UPDATE. Foreign key actions are similar to triggers in many ways.
  543. <p>
  544. The ON DELETE and ON UPDATE action associated with each foreign key in an
  545. SQLite database is one of "NO ACTION", "RESTRICT", "SET NULL",
  546. "SET DEFAULT" or "CASCADE". If an action is not explicitly specified, it
  547. defaults to "NO ACTION".
  548. <ul>
  549. <li><p> <b>NO ACTION</b>: Configuring "NO ACTION" means just that: when a
  550. parent key is modified or deleted from the database, no special action is
  551. taken.
  552. <li><p> <b>RESTRICT</b>: The "RESTRICT" action means that the application
  553. is prohibited from deleting (for ON DELETE RESTRICT) or modifying
  554. (for ON UPDATE RESTRICT) a parent key when there exists one or more child
  555. keys mapped to it. The difference between the effect of a RESTRICT
  556. action and normal foreign key constraint enforcement is that the
  557. RESTRICT action processing happens as soon as the field is updated -
  558. not at the end of the current statement as it would with an immediate
  559. constraint, or at the end of the current transaction as it would with
  560. a deferred constraint.
  561. Even if the foreign key constraint it is
  562. attached to is deferred, configuring a RESTRICT action causes SQLite to
  563. return an error immediately if a parent key with dependent child keys is
  564. deleted or modified.
  565. <li><p> <b>SET NULL</b>: If the configured action is "SET NULL", then when
  566. a parent key is deleted (for ON DELETE SET NULL) or modified (for ON
  567. UPDATE SET NULL), the child key columns of all rows in the child table
  568. that mapped to the parent key are set to contain SQL NULL values.
  569. <li><p> <b>SET DEFAULT</b>: The "SET DEFAULT" actions are similar to
  570. "SET NULL",
  571. except that each of the child key columns is set to contain the columns
  572. default value instead of NULL. Refer to the <a href="lang_createtable.html">CREATE TABLE</a>
  573. documentation for details on how default values are assigned to table
  574. columns.
  575. <li><p> <b>CASCADE</b>: A "CASCADE" action propagates the delete or update
  576. operation on the parent key to each dependent child key. For an "ON
  577. DELETE CASCADE" action, this means that each row in the child table that
  578. was associated with the deleted parent row is also deleted. For an "ON
  579. UPDATE CASCADE" action, it means that the values stored in each dependent
  580. child key are modified to match the new parent key values.
  581. </ul>
  582. <p>
  583. For example, adding an "ON UPDATE CASCADE" clause to the foreign key as
  584. shown below enhances the example schema from section 1 to allow the user
  585. to update the artistid (the parent key of the foreign key constraint)
  586. column without breaking referential integrity:
  587. <div class=codeblock><table width=100%><tr><td><pre><i>-- Database schema</i>
  588. CREATE TABLE artist(
  589. artistid INTEGER PRIMARY KEY,
  590. artistname TEXT
  591. );
  592. CREATE TABLE track(
  593. trackid INTEGER,
  594. trackname TEXT,
  595. trackartist INTEGER REFERENCES artist(artistid) <b>ON UPDATE CASCADE</b>
  596. );
  597. sqlite&gt; SELECT * FROM artist;
  598. artistid artistname
  599. -------- -----------------
  600. 1 Dean Martin
  601. 2 Frank Sinatra
  602. sqlite&gt; SELECT * FROM track;
  603. trackid trackname trackartist
  604. ------- ----------------- -----------
  605. 11 That's Amore 1
  606. 12 Christmas Blues 1
  607. 13 My Way 2
  608. sqlite&gt; <i>-- Update the artistid column of the artist record for "Dean Martin".</i>
  609. sqlite&gt; <i>-- Normally, this would raise a constraint, as it would orphan the two</i>
  610. sqlite&gt; <i>-- dependent records in the track table. However, the ON UPDATE CASCADE clause</i>
  611. sqlite&gt; <i>-- attached to the foreign key definition causes the update to "cascade"</i>
  612. sqlite&gt; <i>-- to the child table, preventing the foreign key constraint violation.</i>
  613. sqlite&gt; UPDATE artist SET artistid = 100 WHERE artistname = 'Dean Martin';
  614. sqlite&gt; SELECT * FROM artist;
  615. artistid artistname
  616. -------- -----------------
  617. 2 Frank Sinatra
  618. 100 Dean Martin
  619. sqlite&gt; SELECT * FROM track;
  620. trackid trackname trackartist
  621. ------- ----------------- -----------
  622. 11 That's Amore 100
  623. 12 Christmas Blues 100
  624. 13 My Way 2
  625. </table></div>
  626. <p>
  627. Configuring an ON UPDATE or ON DELETE action does not mean that the foreign
  628. key constraint does not need to be satisfied. For example, if an
  629. "ON DELETE SET DEFAULT" action is configured,
  630. but there is no row in the parent table
  631. that corresponds to the default values of the child key columns, deleting
  632. a parent key while dependent child keys exist still causes a foreign key
  633. violation. For example:
  634. <div class=codeblock><table width=100%><tr><td><pre><i>-- Database schema</i>
  635. CREATE TABLE artist(
  636. artistid INTEGER PRIMARY KEY,
  637. artistname TEXT
  638. );
  639. CREATE TABLE track(
  640. trackid INTEGER,
  641. trackname TEXT,
  642. trackartist INTEGER <b>DEFAULT 0</b> REFERENCES artist(artistid) <b>ON DELETE SET DEFAULT</b>
  643. );
  644. sqlite&gt; SELECT * FROM artist;
  645. artistid artistname
  646. -------- -----------------
  647. 3 Sammy Davis Jr.
  648. sqlite&gt; SELECT * FROM track;
  649. trackid trackname trackartist
  650. ------- ----------------- -----------
  651. 14 Mr. Bojangles 3
  652. sqlite&gt; <i>-- Deleting the row from the parent table causes the child key</i>
  653. sqlite&gt; <i>-- value of the dependent row to be set to integer value 0. However, this</i>
  654. sqlite&gt; <i>-- value does not correspond to any row in the parent table. Therefore</i>
  655. sqlite&gt; <i>-- the foreign key constraint is violated and an is exception thrown.</i>
  656. sqlite&gt; DELETE FROM artist WHERE artistname = 'Sammy Davis Jr.';
  657. <b>SQL error: foreign key constraint failed</b>
  658. sqlite&gt; <i>-- This time, the value 0 does correspond to a parent table row. And</i>
  659. sqlite&gt; <i>-- so the DELETE statement does not violate the foreign key constraint</i>
  660. sqlite&gt; <i>-- and no exception is thrown.</i>
  661. sqlite&gt; INSERT INTO artist VALUES(0, 'Unknown Artist');
  662. sqlite&gt; DELETE FROM artist WHERE artistname = 'Sammy Davis Jr.';
  663. sqlite&gt; SELECT * FROM artist;
  664. artistid artistname
  665. -------- -----------------
  666. 0 Unknown Artist
  667. sqlite&gt; SELECT * FROM track;
  668. trackid trackname trackartist
  669. ------- ----------------- -----------
  670. 14 Mr. Bojangles 0
  671. </table></div>
  672. <p>
  673. Those familiar with <a href="lang_createtrigger.html">SQLite triggers</a>
  674. will have noticed that the
  675. "ON DELETE SET DEFAULT" action demonstrated in the example above is
  676. similar in effect to the following AFTER DELETE trigger:
  677. <div class=codeblock><table width=100%><tr><td><pre>CREATE TRIGGER on_delete_set_default AFTER DELETE ON artist BEGIN
  678. UPDATE child SET trackartist = 0 WHERE trackartist = old.artistid;
  679. END;
  680. </table></div>
  681. <p>
  682. Whenever a row in the parent table of a foreign key constraint is deleted,
  683. or when the values stored in the parent key column or columns are modified,
  684. the logical sequence of events is:
  685. <ol>
  686. <li> Execute applicable BEFORE trigger programs,
  687. <li> Check local (non foreign key) constraints,
  688. <li> Update or delete the row in the parent table,
  689. <li> Perform any required foreign key actions,
  690. <li> Execute applicable AFTER trigger programs.
  691. </ol>
  692. <p>
  693. There is one important difference between ON UPDATE foreign key actions and
  694. SQL triggers. An ON UPDATE action is only taken if the values of the
  695. parent key are modified so that the new parent key values are
  696. not equal to the old. For example:
  697. <div class=codeblock><table width=100%><tr><td><pre><i>-- Database schema</i>
  698. CREATE TABLE parent(x PRIMARY KEY);
  699. CREATE TABLE child(y REFERENCES parent ON UPDATE SET NULL);
  700. sqlite&gt; SELECT * FROM parent;
  701. x
  702. ----
  703. key
  704. sqlite&gt; SELECT * FROM child;
  705. y
  706. ----
  707. key
  708. sqlite&gt; <i>-- Since the following UPDATE statement does not actually modify</i>
  709. sqlite&gt; <i>-- the parent key value, the ON UPDATE action is not performed and</i>
  710. sqlite&gt; <i>-- the child key value is not set to NULL.</i>
  711. sqlite&gt; UPDATE parent SET x = 'key';
  712. sqlite&gt; SELECT IFNULL(y, 'null') FROM child;
  713. y
  714. ----
  715. key
  716. sqlite&gt; <i>-- This time, since the UPDATE statement does modify the parent key</i>
  717. sqlite&gt; <i>-- value, the ON UPDATE action is performed and the child key is set</i>
  718. sqlite&gt; <i>-- to NULL.</i>
  719. sqlite&gt; UPDATE parent SET x = 'key2';
  720. sqlite&gt; SELECT IFNULL(y, 'null' FROM child;
  721. y
  722. ----
  723. null
  724. </table></div>
  725. <h1 id="fk_schemacommands">5 CREATE, ALTER and DROP TABLE commands</h1>
  726. <p>
  727. This section describes the way the <a href="lang_createtable.html">CREATE TABLE</a>, <a href="lang_altertable.html">ALTER TABLE</a>,
  728. and <a href="lang_droptable.html">DROP TABLE</a> commands
  729. interact with SQLite's foreign keys.
  730. <p>
  731. A <a href="lang_createtable.html">CREATE TABLE</a> command operates the same whether or not
  732. <a href="foreignkeys.html#fk_enable">foreign key constraints are enabled</a>. The parent key definitions of
  733. foreign key constraints are not checked when a table is created. There is
  734. nothing stopping the user from creating a foreign key definition that
  735. refers to a parent table that does not exist, or to parent key columns that
  736. do not exist or are not collectively bound by a PRIMARY KEY or UNIQUE constraint.
  737. <p>
  738. The <a href="lang_altertable.html">ALTER TABLE</a> command works differently in two respects when foreign
  739. key constraints are enabled:
  740. <ul>
  741. <li><p>
  742. It is not possible to use the "ALTER TABLE ... ADD COLUMN" syntax
  743. to add a column that includes a REFERENCES clause, unless the default
  744. value of the new column is NULL. Attempting to do so returns an
  745. error.
  746. <li><p>
  747. If an "ALTER TABLE ... RENAME TO" command is used to rename a table
  748. that is the parent table of one or more foreign key constraints, the
  749. definitions of the foreign key constraints are modified to refer to
  750. the parent table by its new name. The text of the child CREATE
  751. TABLE statement or statements stored in the sqlite_master table are
  752. modified to reflect the new parent table name.
  753. </ul>
  754. <p>
  755. If foreign key constraints are enabled when it is prepared, the
  756. <a href="lang_droptable.html">DROP TABLE</a> command performs an implicit <a href="lang_delete.html">DELETE</a> to remove all
  757. rows from the table before dropping it. The implicit DELETE does not cause
  758. any SQL triggers to fire, but may invoke foreign key actions or constraint
  759. violations. If an immediate foreign key constraint is violated, the DROP
  760. TABLE statement fails and the table is not dropped. If a deferred foreign
  761. key constraint is violated, then an error is reported when the user attempts
  762. to commit the transaction if the foreign key constraint violations still
  763. exist at that point. Any "foreign key mismatch" errors encountered as part
  764. of an implicit DELETE are ignored.
  765. <p>
  766. The intent of these enhancements to the <a href="lang_altertable.html">ALTER TABLE</a> and <a href="lang_droptable.html">DROP TABLE</a>
  767. commands is to ensure that they cannot be used to create a database that
  768. contains foreign key violations, at least while foreign key constraints are
  769. enabled. There is one exception to this rule though. If a parent key is
  770. not subject to a PRIMARY KEY or UNIQUE constraint created as part of the
  771. parent table definition, but is subject to a UNIQUE constraint by virtue
  772. of an index created using the <a href="lang_createindex.html">CREATE INDEX</a> command, then the child
  773. table may be populated without causing a "foreign key mismatch" error. If
  774. the UNIQUE index is dropped from the database schema, then the parent table
  775. itself is dropped, no error will be reported. However the database may be
  776. left in a state where the child table of the foreign key constraint contains
  777. rows that do not refer to any parent table row. This case can be avoided
  778. if all parent keys in the database schema are constrained by PRIMARY KEY
  779. or UNIQUE constraints added as part of the parent table definition, not
  780. by external UNIQUE indexes.
  781. <p>
  782. The properties of the <a href="lang_droptable.html">DROP TABLE</a> and <a href="lang_altertable.html">ALTER TABLE</a> commands described
  783. above only apply if foreign keys are enabled. If the user considers them
  784. undesirable, then the workaround is to use <a href="pragma.html#pragma_foreign_keys">PRAGMA foreign_keys</a> to
  785. disable foreign key constraints before executing the DROP or ALTER TABLE
  786. command. Of course, while foreign key constraints are disabled, there is nothing
  787. to stop the user from violating foreign key constraints and thus creating
  788. an internally inconsistent database.
  789. <h1 id="fk_unsupported">6 Limits and Unsupported Features</h1>
  790. <p>
  791. This section lists a few limitations and omitted features that are not
  792. mentioned elsewhere.
  793. <ol>
  794. <li><p>
  795. <b>No support for the MATCH clause.</b> According to SQL92, a MATCH clause
  796. may be attached to a composite foreign key definition to modify the way
  797. NULL values that occur in child keys are handled. If "MATCH SIMPLE" is
  798. specified, then a child key is not required to correspond to any row
  799. of the parent table if one or more of the child key values are NULL.
  800. If "MATCH FULL" is specified, then if any of the child key values is
  801. NULL, no corresponding row in the parent table is required, but all
  802. child key values must be NULL. Finally, if the foreign key constraint
  803. is declared as "MATCH PARTIAL" and one of the child key values is NULL,
  804. there must exist at least one row in the parent table for which the
  805. non-NULL child key values match the parent key values.
  806. <p>
  807. SQLite parses MATCH clauses (i.e. does not report a syntax error
  808. if you specify one), but does not enforce them. All foreign key
  809. constraints in SQLite are handled as if MATCH SIMPLE were specified.
  810. <li> <p>
  811. <b>No support for switching constraints between deferred and immediate
  812. mode.</b> Many systems allow the user to toggle individual foreign key
  813. constraints between <a href=#fk_deferred>deferred</a> and immediate
  814. mode at runtime (for example using the Oracle "SET CONSTRAINT" command).
  815. SQLite does not support this. In SQLite, a foreign key constraint is
  816. permanently marked as deferred or immediate when it is created.
  817. <li><p>
  818. <b>Recursion limit on foreign key actions.</b> The
  819. <a href="limits.html#max_trigger_depth">SQLITE_MAX_TRIGGER_DEPTH</a> and <a href="c3ref/c_limit_attached.html">SQLITE_LIMIT_TRIGGER_DEPTH</a>
  820. settings determine the maximum allowable depth of trigger
  821. program recursion. For the purposes of these limits,
  822. <a href="foreignkeys.html#fk_actions">foreign key actions</a> are considered trigger programs. The
  823. <a href="pragma.html#pragma_recursive_triggers">PRAGMA recursive_triggers</a> setting does not not affect the operation
  824. of foreign key actions. It is not possible to disable recursive foreign
  825. key actions.
  826. </ol>