Debian Codegraph @

www/foreignkeys.html

raw
1 <!DOCTYPE html>
2 <html><head>
3 <meta name="viewport" content="width=device-width, initial-scale=1.0">
4 <meta http-equiv="content-type" content="text/html; charset=UTF-8">
5 <link href="sqlite.css" rel="stylesheet">
6 <title>SQLite Foreign Key Support</title>
7 <!-- path= -->
8 </head>
9 <body>
10 <div class=nosearch>
11 <a href="index.html">
12 <img class="logo" src="images/sqlite370_banner.gif" alt="SQLite" border="0">
13 </a>
14 <div><!-- IE hack to prevent disappearing logo --></div>
15 <div class="tagline desktoponly">
16 Small. Fast. Reliable.<br>Choose any three.
17 </div>
18 <div class="menu mainmenu">
19 <ul>
20 <li><a href="index.html">Home</a>
21 <li class='mobileonly'><a href="javascript:void(0)" onclick='toggle_div("submenu")'>Menu</a>
22 <li class='wideonly'><a href='about.html'>About</a>
23 <li class='desktoponly'><a href="docs.html">Documentation</a>
24 <li class='desktoponly'><a href="download.html">Download</a>
25 <li class='wideonly'><a href='copyright.html'>License</a>
26 <li class='desktoponly'><a href="support.html">Support</a>
27 <li class='desktoponly'><a href="prosupport.html">Purchase</a>
28 <li class='search' id='search_menubutton'>
29 <a href="javascript:void(0)" onclick='toggle_search()'>Search</a>
30 </ul>
31 </div>
32 <div class="menu submenu" id="submenu">
33 <ul>
34 <li><a href='about.html'>About</a>
35 <li><a href='docs.html'>Documentation</a>
36 <li><a href='download.html'>Download</a>
37 <li><a href='support.html'>Support</a>
38 <li><a href='prosupport.html'>Purchase</a>
39 </ul>
40 </div>
41 <div class="searchmenu" id="searchmenu">
42 <form method="GET" action="search">
43 <select name="s" id="searchtype">
44 <option value="d">Search Documentation</option>
45 <option value="c">Search Changelog</option>
46 </select>
47 <input type="text" name="q" id="searchbox" value="">
48 <input type="submit" value="Go">
49 </form>
50 </div>
51 </div>
52 <script>
53 function toggle_div(nm) {
54 var w = document.getElementById(nm);
55 if( w.style.display=="block" ){
56 w.style.display = "none";
57 }else{
58 w.style.display = "block";
59 }
60 }
61 function toggle_search() {
62 var w = document.getElementById("searchmenu");
63 if( w.style.display=="block" ){
64 w.style.display = "none";
65 } else {
66 w.style.display = "block";
67 setTimeout(function(){
68 document.getElementById("searchbox").focus()
69 }, 30);
70 }
71 }
72 function div_off(nm){document.getElementById(nm).style.display="none";}
73 window.onbeforeunload = function(e){div_off("submenu");}
74 /* Disable the Search feature if we are not operating from CGI, since */
75 /* Search is accomplished using CGI and will not work without it. */
76 if( !location.origin || !location.origin.match || !location.origin.match(/http/) ){
77 document.getElementById("search_menubutton").style.display = "none";
78 }
79 /* Used by the Hide/Show button beside syntax diagrams, to toggle the */
80 function hideorshow(btn,obj){
81 var x = document.getElementById(obj);
82 var b = document.getElementById(btn);
83 if( x.style.display!='none' ){
84 x.style.display = 'none';
85 b.innerHTML='show';
86 }else{
87 x.style.display = '';
88 b.innerHTML='hide';
89 }
90 return false;
91 }
92 var antiRobot = 0;
93 function antiRobotGo(){
94 if( antiRobot!=3 ) return;
95 antiRobot = 7;
96 var j = document.getElementById("mtimelink");
97 if(j && j.hasAttribute("data-href")) j.href=j.getAttribute("data-href");
98 }
99 function antiRobotDefense(){
100 document.body.onmousedown=function(){
101 antiRobot |= 2;
102 antiRobotGo();
103 document.body.onmousedown=null;
104 }
105 document.body.onmousemove=function(){
106 antiRobot |= 2;
107 antiRobotGo();
108 document.body.onmousemove=null;
109 }
110 setTimeout(function(){
111 antiRobot |= 1;
112 antiRobotGo();
113 }, 100)
114 antiRobotGo();
115 }
116 antiRobotDefense();
117 </script>
118 <div class=fancy>
119 <div class=nosearch>
120 <div class="fancy_title">
121 SQLite Foreign Key Support
122 </div>
123 <div class="fancy_toc">
124 <a onclick="toggle_toc()">
125 <span class="fancy_toc_mark" id="toc_mk">&#x25ba;</span>
126 Table Of Contents
127 </a>
128 <div id="toc_sub"><div class="fancy-toc1"><a href="#fk_basics">1. Introduction to Foreign Key Constraints</a></div>
129 <div class="fancy-toc1"><a href="#fk_enable">2.
130 Enabling Foreign Key Support
131 </a></div>
132 <div class="fancy-toc1"><a href="#fk_indexes">3. Required and Suggested Database Indexes</a></div>
133 <div class="fancy-toc1"><a href="#fk_advanced">4. Advanced Foreign Key Constraint Features</a></div>
134 <div class="fancy-toc2"><a href="#fk_composite">4.1. Composite Foreign Key Constraints</a></div>
135 <div class="fancy-toc2"><a href="#fk_deferred">4.2. Deferred Foreign Key Constraints</a></div>
136 <div class="fancy-toc2"><a href="#fk_actions">4.3.
137 ON DELETE and ON UPDATE Actions
138 </a></div>
139 <div class="fancy-toc1"><a href="#fk_schemacommands">5. CREATE, ALTER and DROP TABLE commands</a></div>
140 <div class="fancy-toc1"><a href="#fk_unsupported">6. Limits and Unsupported Features</a></div>
141 </div>
142 </div>
143 <script>
144 function toggle_toc(){
145 var sub = document.getElementById("toc_sub")
146 var mk = document.getElementById("toc_mk")
147 if( sub.style.display!="block" ){
148 sub.style.display = "block";
149 mk.innerHTML = "&#x25bc;";
150 } else {
151 sub.style.display = "none";
152 mk.innerHTML = "&#x25ba;";
153 }
154 }
155 </script>
156 </div>
157
158
159
160
161
162 <h2 style="margin-left:1.0em" notoc="1" id="overview"> Overview</h2>
163
164 <p>This document describes the support for SQL foreign key constraints
165 introduced in SQLite <a href="releaselog/3_6_19.html">version 3.6.19</a> (2009-10-14).
166
167 </p><p>The first section introduces the
168 concept of an SQL foreign key by example and defines the terminology
169 used for the remainder of the document. Section 2 describes the steps
170 an application must take in order to enable foreign key constraints in
171 SQLite (it is disabled by default). The next section, section 3,
172 describes the indexes that the user must create in order to use
173 foreign key constraints, and those that should be created in order for
174 foreign key constraints to function efficiently. Section 4 describes
175 the advanced foreign key related features supported by SQLite and
176 section 5 describes the way the <a href="lang_altertable.html">ALTER</a> and <a href="lang_droptable.html">DROP TABLE</a> commands are
177 enhanced to support foreign key constraints. Finally, section 6
178 enumerates the missing features and limits of the current implementation.
179
180 </p><p>This document does not contain a full description of the syntax used
181 to create foreign key constraints in SQLite. This may be found as
182 part of the documentation for the <a href="lang_createtable.html">CREATE TABLE</a> statement.
183
184 </p><h1 id="fk_basics"><span>1. </span>Introduction to Foreign Key Constraints</h1>
185
186 <p>
187 SQL foreign key constraints are used to enforce "exists" relationships
188 between tables. For example, consider a database schema created using
189 the following SQL commands:
190
191 </p><div class="codeblock"><pre>CREATE TABLE artist(
192 artistid INTEGER PRIMARY KEY,
193 artistname TEXT
194 );
195 CREATE TABLE track(
196 trackid INTEGER,
197 trackname TEXT,
198 trackartist INTEGER <b>-- Must map to an artist.artistid!</b>
199 );
200 </pre></div>
201
202 <p>
203 The applications using this database are entitled to assume that for
204 each row in the <i>track</i> table there exists a corresponding row in the
205 <i>artist</i> table. After all, the comment in the declaration says so.
206 Unfortunately, if a user edits the database using an external tool or
207 if there is a bug in an application, rows might be inserted into the
208 <i>track</i> table that do not correspond to any row in the <i>artist</i>
209 table. Or rows might be deleted from the <i>artist</i> table, leaving
210 orphaned rows in the <i>track</i> table that do not correspond to any of
211 the remaining rows in <i>artist</i>. This might cause the application
212 or applications to malfunction later on, or at least make coding the
213 application more difficult.
214
215 </p><p>
216 One solution is to add an SQL foreign key constraint to the database
217 schema to enforce the relationship between the <i>artist</i> and
218 <i>track</i> table. To do so, a foreign key definition may be added
219 by modifying the declaration of the <i>track</i> table to the following:
220
221 </p><div class="codeblock"><pre>CREATE TABLE track(
222 trackid INTEGER,
223 trackname TEXT,
224 trackartist INTEGER,
225 <b>FOREIGN KEY(trackartist) REFERENCES artist(artistid)</b>
226 );
227 </pre></div>
228
229 <p>
230 This way, the constraint is enforced by SQLite. Attempting to insert
231 a row into the <i>track</i> table that does not correspond to any
232 row in the <i>artist</i> table will fail, as will attempting to
233 delete a row from the <i>artist</i> table when there exist dependent
234 rows in the <i>track</i> table There is one exception: if the foreign
235 key column in the <i>track</i> table is NULL, then no corresponding
236 entry in the <i>artist</i> table is required. Expressed in SQL, this
237 means that for every row in the <i>track</i> table, the following
238 expression evaluates to true:
239 </p><div class="codeblock"><pre>trackartist IS NULL OR EXISTS(SELECT 1 FROM artist WHERE artistid=trackartist)
240 </pre></div>
241
242 <p>Tip: If the application requires a stricter relationship between
243 <i>artist</i> and <i>track</i>, where NULL values are not permitted
244 in the <i>trackartist</i> column, simply add the appropriate
245 "NOT NULL" constraint to the schema.
246
247 </p><p>There are several other ways to add an equivalent foreign key declaration
248 to a <a href="lang_createtable.html">CREATE TABLE</a> statement. Refer to the
249 <a href="lang_createtable.html">CREATE TABLE documentation</a> for details.
250
251 </p><p>The following SQLite command-line session illustrates the effect of the
252 foreign key constraint added to the <i>track</i> table:
253
254 </p><div class="codeblock"><pre>sqlite&gt; SELECT * FROM artist;
255 artistid artistname
256 -------- -----------------
257 1 Dean Martin
258 2 Frank Sinatra
259
260 sqlite> SELECT * FROM track;
261 trackid trackname trackartist
262 ------- ----------------- -----------
263 11 That's Amore 1
264 12 Christmas Blues 1
265 13 My Way 2
266
267 sqlite&gt; <i>-- This fails because the value inserted into the trackartist column (3)</i>
268 sqlite&gt; <i>-- does not correspond to row in the artist table.</i>
269 sqlite&gt; INSERT INTO track VALUES(14, 'Mr. Bojangles', 3);
270 <b>SQL error: foreign key constraint failed</b>
271
272 sqlite&gt; <i>-- This succeeds because a NULL is inserted into trackartist. A</i>
273 sqlite&gt; <i>-- corresponding row in the artist table is not required in this case.</i>
274 sqlite&gt; INSERT INTO track VALUES(14, 'Mr. Bojangles', NULL);
275
276 sqlite&gt; <i>-- Trying to modify the trackartist field of the record after it has </i>
277 sqlite&gt; <i>-- been inserted does not work either, since the new value of trackartist (3)</i>
278 sqlite&gt; <i>-- Still does not correspond to any row in the artist table.</i>
279 sqlite&gt; UPDATE track SET trackartist = 3 WHERE trackname = 'Mr. Bojangles';
280 <b>SQL error: foreign key constraint failed</b>
281
282 sqlite&gt; <i>-- Insert the required row into the artist table. It is then possible to</i>
283 sqlite&gt; <i>-- update the inserted row to set trackartist to 3 (since a corresponding</i>
284 sqlite&gt; <i>-- row in the artist table now exists).</i>
285 sqlite&gt; INSERT INTO artist VALUES(3, 'Sammy Davis Jr.');
286 sqlite&gt; UPDATE track SET trackartist = 3 WHERE trackname = 'Mr. Bojangles';
287
288 sqlite&gt; <i>-- Now that "Sammy Davis Jr." (artistid = 3) has been added to the database,</i>
289 sqlite&gt; <i>-- it is possible to INSERT new tracks using this artist without violating</i>
290 sqlite&gt; <i>-- the foreign key constraint:</i>
291 sqlite&gt; INSERT INTO track VALUES(15, 'Boogie Woogie', 3);
292 </pre></div>
293
294 <p>
295 As you would expect, it is not possible to manipulate the database to a state
296 that violates the foreign key constraint by deleting or updating rows in the
297 <i>artist</i> table either:
298 </p><div class="codeblock"><pre>sqlite&gt; <i>-- Attempting to delete the artist record for "Frank Sinatra" fails, since</i>
299 sqlite&gt; <i>-- the track table contains a row that refer to it.</i>
300 sqlite&gt; DELETE FROM artist WHERE artistname = 'Frank Sinatra';
301 <b>SQL error: foreign key constraint failed</b>
302
303 sqlite&gt; <i>-- Delete all the records from the track table that refer to the artist</i>
304 sqlite&gt; <i>-- "Frank Sinatra". Only then is it possible to delete the artist.</i>
305 sqlite&gt; DELETE FROM track WHERE trackname = 'My Way';
306 sqlite&gt; DELETE FROM artist WHERE artistname = 'Frank Sinatra';
307
308 sqlite&gt; <i>-- Try to update the artistid of a row in the artist table while there</i>
309 sqlite&gt; <i>-- exists records in the track table that refer to it. </i>
310 sqlite&gt; UPDATE artist SET artistid=4 WHERE artistname = 'Dean Martin';
311 <b>SQL error: foreign key constraint failed</b>
312
313 sqlite&gt; <i>-- Once all the records that refer to a row in the artist table have</i>
314 sqlite&gt; <i>-- been deleted, it is possible to modify the artistid of the row.</i>
315 sqlite&gt; DELETE FROM track WHERE trackname IN('That''s Amore', 'Christmas Blues');
316 sqlite&gt; UPDATE artist SET artistid=4 WHERE artistname = 'Dean Martin';
317 </pre></div>
318
319 <p>
320 SQLite uses the following terminology:
321 <a name="parentchild"></a>
322
323 </p><ul>
324 <li><p>The <b>parent table</b> is the table that a foreign key constraint
325 refers to. The parent table in the example in this section is the
326 <i>artist</i> table. Some books and articles refer to this as the
327 <i>referenced table</i>, which is arguably more correct, but tends
328 to lead to confusion.
329
330 </p></li><li><p>The <b>child table</b> is the table that a foreign key constraint
331 is applied to and the table that contains the REFERENCES clause.
332 The example in this section uses the <i>track</i> table
333 as the child table. Other books and articles refer to this as the
334 <i>referencing table</i>.
335
336 </p></li><li><p>The <b>parent key</b> is the column or set of columns in the parent
337 table that the foreign key constraint refers to. This is normally, but
338 not always, the primary key of the parent table. The parent key must
339 be a named column or columns in the parent table, not the <a href="lang_createtable.html#rowid">rowid</a>.
340
341 </p></li><li><p>The <b>child key</b> is the column or set of columns in the child
342 table that are constrained by the foreign key constraint and which
343 hold the REFERENCES clause.
344 </p></li></ul>
345
346 <p>
347 The foreign key constraint is satisfied if for each row in the child table
348 either one or more of the child key columns are NULL, or there exists a
349 row in the parent table for which each parent key column contains a value
350 equal to the value in its associated child key column.
351
352 </p><p>
353 In the above paragraph, the term "equal" means equal when values are
354 compared using the rules <a href="datatype3.html#comparisons">specified
355 here</a>. The following clarifications apply:
356
357 </p><ul>
358 <li><p>When comparing text values, the <a href="datatype3.html#collation">collating sequence</a>
359 associated with the parent key column is always used.
360 </p></li><li><p>When comparing values, if the parent key column has an <a href="datatype3.html#affinity">affinity</a>,
361 then that affinity is applied to the child key value before the
362 comparison is performed.
363 </p></li></ul>
364
365 <a name="fk_enable"></a>
366 <h1 id="fk_enable" tags="foreign key constraints are enabled"><span>2. </span>
367 Enabling Foreign Key Support
368 </h1>
369 <p>
370 In order to use foreign key constraints in SQLite, the library must
371 be compiled with neither <a href="compile.html#omit_foreign_key">SQLITE_OMIT_FOREIGN_KEY</a> nor
372 <a href="compile.html#omit_trigger">SQLITE_OMIT_TRIGGER</a> defined. If SQLITE_OMIT_TRIGGER is defined
373 but SQLITE_OMIT_FOREIGN_KEY is not, then SQLite behaves as it did prior
374 to <a href="releaselog/3_6_19.html">version 3.6.19</a> (2009-10-14)
375 - foreign key definitions are parsed and may be
376 queried using <a href="pragma.html#pragma_foreign_key_list">PRAGMA foreign_key_list</a>, but foreign key constraints
377 are not enforced. The <a href="pragma.html#pragma_foreign_keys">PRAGMA foreign_keys</a> command is a no-op in this
378 configuration. If OMIT_FOREIGN_KEY is defined, then foreign key
379 definitions cannot even be parsed (attempting to specify a foreign
380 key definition is a syntax error).
381
382 </p><p>
383 Assuming the library is compiled with foreign key constraints enabled,
384 it must still be enabled by the application at runtime, using the
385 <a href="pragma.html#pragma_foreign_keys">PRAGMA foreign_keys</a> command. For example:
386
387 </p><div class="codeblock"><pre>sqlite&gt; PRAGMA foreign_keys = ON;
388 </pre></div>
389
390 <p>
391 Foreign key constraints are disabled by default
392 (for backwards compatibility),
393 so must be enabled separately for each <a href="c3ref/sqlite3.html">database connection</a>.
394 (Note, however, that future releases of SQLite might change
395 so that foreign key constraints enabled by default. Careful
396 developers will not
397 make any assumptions about whether or not foreign keys are enabled by
398 default but will instead enable or disable them as necessary.)
399 The application can also use a <a href="pragma.html#pragma_foreign_keys">PRAGMA foreign_keys</a> statement to
400 determine if foreign keys are currently enabled. The following
401 command-line session demonstrates this:
402 </p><div class="codeblock"><pre>sqlite> PRAGMA foreign_keys;
403 0
404 sqlite> PRAGMA foreign_keys = ON;
405 sqlite> PRAGMA foreign_keys;
406 1
407 sqlite> PRAGMA foreign_keys = OFF;
408 sqlite> PRAGMA foreign_keys;
409 0
410 </pre></div>
411
412 <p>Tip: If the command "PRAGMA foreign_keys" returns no data instead of a
413 single row containing "0" or "1", then the version of SQLite you are
414 using does not support foreign keys (either because it is older than
415 3.6.19 or because it was compiled with <a href="compile.html#omit_foreign_key">SQLITE_OMIT_FOREIGN_KEY</a> or
416 <a href="compile.html#omit_trigger">SQLITE_OMIT_TRIGGER</a> defined).
417
418 </p><p>
419 It is not possible to enable or disable foreign key constraints
420 in the middle of a <a href="lang_transaction.html">multi-statement transaction</a> (when SQLite
421 is not in <a href="c3ref/get_autocommit.html">autocommit mode</a>). Attempting to do so does not return
422 an error; it simply has no effect.
423
424 </p><h1 id="fk_indexes"><span>3. </span>Required and Suggested Database Indexes</h1>
425
426 <p>
427 Usually, the parent key of a foreign key constraint is the primary key of
428 the parent table. If they are not the primary key, then the parent key
429 columns must be collectively subject to a UNIQUE constraint or have
430 a UNIQUE index.
431 If the parent key columns have a UNIQUE index,
432 then that index must use the collation sequences that are specified
433 in the CREATE TABLE statement for the parent table.
434 For example,
435
436 </p><div class="codeblock"><pre>CREATE TABLE parent(a PRIMARY KEY, b UNIQUE, c, d, e, f);
437 CREATE UNIQUE INDEX i1 ON parent(c, d);
438 CREATE INDEX i2 ON parent(e);
439 CREATE UNIQUE INDEX i3 ON parent(f COLLATE nocase);
440
441 CREATE TABLE child1(f, g REFERENCES parent(a)); <i>-- Ok</i>
442 CREATE TABLE child2(h, i REFERENCES parent(b)); <i>-- Ok</i>
443 CREATE TABLE child3(j, k, FOREIGN KEY(j, k) REFERENCES parent(c, d)); <i>-- Ok</i>
444 CREATE TABLE child4(l, m REFERENCES parent(e)); <i>-- Error!</i>
445 CREATE TABLE child5(n, o REFERENCES parent(f)); <i>-- Error!</i>
446 CREATE TABLE child6(p, q, FOREIGN KEY(p, q) REFERENCES parent(b, c)); <i>-- Error!</i>
447 CREATE TABLE child7(r REFERENCES parent(c)); <i>-- Error!</i>
448 </pre></div>
449
450 <p>
451 The foreign key constraints created as part of tables <i>child1</i>,
452 <i>child2</i> and <i>child3</i> are all fine. The foreign key
453 declared as part of table <i>child4</i> is an error because even though
454 the parent key column is indexed, the index is not UNIQUE.
455 The foreign key for table <i>child5</i>
456 is an error because even though the parent key column has a unique
457 index, the index uses a different collating sequence.
458 Tables <i>child6</i> and <i>child7</i> are incorrect because while
459 both have UNIQUE indices on their parent keys, the keys are not an
460 exact match to the columns of a single UNIQUE index.
461
462 </p><p>
463 If the database schema contains foreign key errors that require looking
464 at more than one table definition to identify, then those errors are not
465 detected when the tables are created. Instead, such errors prevent
466 the application from preparing SQL statements that modify the content
467 of the child or parent tables in ways that use the foreign keys.
468 Errors reported when content is changed are "DML errors" and errors
469 reported when the schema is changed are "DDL errors".
470 So, in other words, misconfigured foreign key constraints that require
471 looking at both the child and parent are DML errors.
472 The English language error message for foreign key DML errors is usually
473 "foreign key mismatch" but can also be "no such table" if the parent
474 table does not exist.
475 Foreign key DML errors are reported if:
476
477 </p><ul>
478 <li> The parent table does not exist, or
479 </li><li> The parent key columns named in the foreign key constraint do
480 not exist, or
481 </li><li> The parent key columns named in the foreign key constraint are not
482 the primary key of the parent table and are not subject to a unique
483 constraint using collating sequence specified in the CREATE TABLE, or
484 </li><li> The child table references the primary key of the parent without
485 specifying the primary key columns and the number of primary key
486 columns in the parent do not match the number of child key columns.
487 </li></ul>
488
489 <p>
490 The last bullet above is illustrated by the following:
491
492 </p><div class="codeblock"><pre>CREATE TABLE parent2(a, b, PRIMARY KEY(a,b));
493
494 CREATE TABLE child8(x, y, FOREIGN KEY(x,y) REFERENCES parent2); <i>-- Ok</i>
495 CREATE TABLE child9(x REFERENCES parent2); <i>-- Error!</i>
496 CREATE TABLE child10(x,y,z, FOREIGN KEY(x,y,z) REFERENCES parent2); <i>-- Error!</i>
497 </pre></div>
498
499 <p>
500 By contrast, if foreign key errors can be recognized simply by looking
501 at the definition of the child table and without having to consult the
502 parent table definition, then the
503 <a href="lang_createtable.html">CREATE TABLE</a> statement for the child table fails. Because the error
504 occurs during a schema change, this is a DDL error.
505 Foreign key DDL errors are reported regardless of
506 whether or not foreign key constraints are enabled when the
507 table is created.
508
509 </p><p>
510 Indices are not required for child key columns but they are almost
511 always beneficial. Returning to
512 the example in <a href="#fk_basics">section 1</a>, each time an application
513 deletes a row from the <i>artist</i> table (the parent table), it
514 performs the equivalent of the following SELECT statement to search
515 for referencing rows in the <i>track</i> table (the child table).
516
517 </p><div class="codeblock"><pre>SELECT rowid FROM track WHERE trackartist = ?
518 </pre></div>
519
520 <p>
521 where ? in the above is replaced with the value of the <i>artistid</i>
522 column of the record being deleted from the <i>artist</i> table (recall
523 that the <i>trackartist</i> column is the child key and the <i>artistid</i>
524 column is the parent key). Or, more generally:
525
526 </p><div class="codeblock"><pre>SELECT rowid FROM &lt;child-table&gt; WHERE &lt;child-key&gt; = :parent_key_value
527 </pre></div>
528
529 <p>
530 If this SELECT returns any rows at all, then SQLite concludes that
531 deleting the row from the parent table would violate the foreign key
532 constraint and returns an error.
533 Similar queries may be run if the content of the parent key
534 is modified or a new row is inserted into the parent table.
535 If these queries cannot use an index, they are forced to do a
536 linear scan of the entire child table. In a non-trivial database, this may
537 be prohibitively expensive.
538
539 </p><p>
540 So, in most real systems, an index should be created on the child key columns
541 of each foreign key constraint. The child key index does not have
542 to be (and usually will not be) a UNIQUE index.
543 Returning again to the example in section 1, the
544 complete database schema for efficient implementation of the foreign key
545 constraint might be:
546
547 </p><div class="codeblock"><pre>CREATE TABLE artist(
548 artistid INTEGER PRIMARY KEY,
549 artistname TEXT
550 );
551 CREATE TABLE track(
552 trackid INTEGER,
553 trackname TEXT,
554 trackartist INTEGER REFERENCES artist
555 );
556 CREATE INDEX trackindex ON track(trackartist);
557 </pre></div>
558
559 <p>
560 The block above uses a shorthand form to create the foreign key constraint.
561 Attaching a "REFERENCES <i>&lt;parent-table&gt;</i>" clause to a column
562 definition creates a foreign key constraint that maps the column to the
563 primary key of <i>&lt;parent-table&gt;</i>. Refer to the <a href="lang_createtable.html">CREATE TABLE</a>
564 documentation for further details.
565
566
567 </p><h1 id="fk_advanced"><span>4. </span>Advanced Foreign Key Constraint Features</h1>
568
569 <h2 id="fk_composite"><span>4.1. </span>Composite Foreign Key Constraints</h2>
570
571 <p>
572 A composite foreign key constraint is one where the child and parent keys
573 are both composite keys. For example, consider
574 the following database schema:
575
576 </p><div class="codeblock"><pre>CREATE TABLE album(
577 albumartist TEXT,
578 albumname TEXT,
579 albumcover BINARY,
580 PRIMARY KEY(albumartist, albumname)
581 );
582
583 CREATE TABLE song(
584 songid INTEGER,
585 songartist TEXT,
586 songalbum TEXT,
587 songname TEXT,
588 <b>FOREIGN KEY(songartist, songalbum) REFERENCES album(albumartist, albumname)</b>
589 );
590 </pre></div>
591
592 <p>
593 In this system, each entry in the song table is required to map to an entry
594 in the album table with the same combination of artist and album.
595
596 </p><p>
597 Parent and child keys must have the same cardinality.
598 In SQLite, if any of the child key columns (in this case songartist
599 and songalbum) are NULL, then there is no requirement for a corresponding
600 row in the parent table.
601
602 </p><h2 id="fk_deferred"><span>4.2. </span>Deferred Foreign Key Constraints</h2>
603
604 <p>
605 Each foreign key constraint in SQLite is classified as either immediate
606 or deferred. Foreign key constraints are immediate by default.
607 All the foreign key examples presented
608 so far have been of immediate foreign key constraints.
609
610 </p><p>
611 If a statement modifies the contents of the database so that an immediate
612 foreign key constraint is in violation at the conclusion the statement,
613 an exception is thrown and
614 the effects of the statement are reverted. By contrast, if
615 a statement modifies the contents of the database such that a deferred
616 foreign key constraint is violated, the violation is not reported
617 immediately. Deferred foreign key constraints are not checked
618 until the transaction tries to <a href="lang_transaction.html">COMMIT</a>.
619 For as long as the user has
620 an open transaction, the database is allowed to exist in a state that
621 violates any number of deferred foreign key constraints. However,
622 <a href="lang_transaction.html">COMMIT</a> will fail as long as foreign key constraints remain in
623 violation.
624
625 </p><p>
626 If the current statement is not inside an explicit transaction (a
627 <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
628 transaction is committed
629 as soon as the statement has finished executing. In this case deferred
630 constraints behave the same as immediate constraints.
631
632 </p><p>
633 To mark a foreign key constraint as deferred, its declaration must
634 include the following clause:
635
636 </p><div class="codeblock"><pre>DEFERRABLE INITIALLY DEFERRED <i>-- A deferred foreign key constraint</i>
637 </pre></div>
638
639 <p>
640 The full syntax for specifying foreign key constraints is available as part
641 of the <a href="lang_createtable.html">CREATE TABLE</a> documentation. Replacing the phrase above
642 with any of the following
643 creates an immediate foreign key constraint.
644
645 </p><div class="codeblock"><pre>NOT DEFERRABLE INITIALLY DEFERRED <i>-- An immediate foreign key constraint</i>
646 NOT DEFERRABLE INITIALLY IMMEDIATE <i>-- An immediate foreign key constraint</i>
647 NOT DEFERRABLE <i>-- An immediate foreign key constraint</i>
648 DEFERRABLE INITIALLY IMMEDIATE <i>-- An immediate foreign key constraint</i>
649 DEFERRABLE <i>-- An immediate foreign key constraint</i>
650 </pre></div>
651
652 <p>The <a href="pragma.html#pragma_defer_foreign_keys">defer_foreign_keys pragma</a> can be used to temporarily change all foreign
653 key constraints to deferred regardless of how they are declared.
654
655 </p><p>
656 The following example illustrates the effect of using a deferred foreign
657 key constraint.
658
659 </p><div class="codeblock"><pre><i>-- Database schema. Both tables are initially empty. </i>
660 CREATE TABLE artist(
661 artistid INTEGER PRIMARY KEY,
662 artistname TEXT
663 );
664 CREATE TABLE track(
665 trackid INTEGER,
666 trackname TEXT,
667 trackartist INTEGER REFERENCES artist(artistid) <b>DEFERRABLE INITIALLY DEFERRED</b>
668 );
669
670 sqlite3&gt; <i>-- If the foreign key constraint were immediate, this INSERT would</i>
671 sqlite3&gt; <i>-- cause an error (since as there is no row in table artist with</i>
672 sqlite3&gt; <i>-- artistid=5). But as the constraint is deferred and there is an</i>
673 sqlite3&gt; <i>-- open transaction, no error occurs.</i>
674 sqlite3&gt; BEGIN;
675 sqlite3&gt; INSERT INTO track VALUES(1, 'White Christmas', 5);
676
677 sqlite3&gt; <i>-- The following COMMIT fails, as the database is in a state that</i>
678 sqlite3&gt; <i>-- does not satisfy the deferred foreign key constraint. The</i>
679 sqlite3&gt; <i>-- transaction remains open.</i>
680 sqlite3&gt; COMMIT;
681 <b>SQL error: foreign key constraint failed</b>
682
683 sqlite3&gt; <i>-- After inserting a row into the artist table with artistid=5, the</i>
684 sqlite3&gt; <i>-- deferred foreign key constraint is satisfied. It is then possible</i>
685 sqlite3&gt; <i>-- to commit the transaction without error.</i>
686 sqlite3&gt; INSERT INTO artist VALUES(5, 'Bing Crosby');
687 sqlite3&gt; COMMIT;
688 </pre></div>
689 <p>
690 A <a href="lang_savepoint.html">nested savepoint</a> transaction may be RELEASEd while the
691 database is in a state that does not satisfy a deferred foreign key
692 constraint. A transaction savepoint (a non-nested savepoint that was
693 opened while there was not currently an open transaction), on the
694 other hand, is subject to the same restrictions as a COMMIT - attempting
695 to RELEASE it while the database is in such a state will fail.
696
697 </p><p>
698 If a COMMIT statement (or the RELEASE of a transaction SAVEPOINT) fails
699 because the database is currently in a state that violates a deferred
700 foreign key constraint and there are currently
701 <a href="lang_savepoint.html">nested savepoints</a>, the nested savepoints remain open.
702
703
704 </p><a name="fk_actions"></a>
705 <h2 id="fk_actions" tags="foreign key actions"><span>4.3. </span>
706 ON DELETE and ON UPDATE Actions
707 </h2>
708
709 <p>
710 Foreign key ON DELETE and ON UPDATE clauses are used to configure actions
711 that take place when deleting rows from the parent table (ON DELETE), or
712 modifying the parent key values of existing rows (ON UPDATE). A single
713 foreign key constraint may have different actions configured for ON DELETE
714 and ON UPDATE. Foreign key actions are similar to triggers in many ways.
715
716 </p><p>
717 The ON DELETE and ON UPDATE action associated with each foreign key in an
718 SQLite database is one of "NO ACTION", "RESTRICT", "SET NULL",
719 "SET DEFAULT" or "CASCADE". If an action is not explicitly specified, it
720 defaults to "NO ACTION".
721
722 </p><ul>
723 <li><p> <b>NO ACTION</b>: Configuring "NO ACTION" means just that: when a
724 parent key is modified or deleted from the database, no special action is
725 taken.
726
727 </p></li><li><p> <b>RESTRICT</b>: The "RESTRICT" action means that the application
728 is prohibited from deleting (for ON DELETE RESTRICT) or modifying
729 (for ON UPDATE RESTRICT) a parent key when there exists one or more child
730 keys mapped to it. The difference between the effect of a RESTRICT
731 action and normal foreign key constraint enforcement is that the
732 RESTRICT action processing happens as soon as the field is updated -
733 not at the end of the current statement as it would with an immediate
734 constraint, or at the end of the current transaction as it would with
735 a deferred constraint.
736 Even if the foreign key constraint it is
737 attached to is deferred, configuring a RESTRICT action causes SQLite to
738 return an error immediately if a parent key with dependent child keys is
739 deleted or modified.
740
741 </p></li><li><p> <b>SET NULL</b>: If the configured action is "SET NULL", then when
742 a parent key is deleted (for ON DELETE SET NULL) or modified (for ON
743 UPDATE SET NULL), the child key columns of all rows in the child table
744 that mapped to the parent key are set to contain SQL NULL values.
745
746 </p></li><li><p> <b>SET DEFAULT</b>: The "SET DEFAULT" actions are similar to
747 "SET NULL",
748 except that each of the child key columns is set to contain the column's
749 default value instead of NULL. Refer to the <a href="lang_createtable.html">CREATE TABLE</a>
750 documentation for details on how default values are assigned to table
751 columns.
752
753 </p></li><li><p> <b>CASCADE</b>: A "CASCADE" action propagates the delete or update
754 operation on the parent key to each dependent child key. For an "ON
755 DELETE CASCADE" action, this means that each row in the child table that
756 was associated with the deleted parent row is also deleted. For an "ON
757 UPDATE CASCADE" action, it means that the values stored in each dependent
758 child key are modified to match the new parent key values.
759 </p></li></ul>
760
761 <p>
762 For example, adding an "ON UPDATE CASCADE" clause to the foreign key as
763 shown below enhances the example schema from section 1 to allow the user
764 to update the artistid (the parent key of the foreign key constraint)
765 column without breaking referential integrity:
766 </p><div class="codeblock"><pre><i>-- Database schema</i>
767 CREATE TABLE artist(
768 artistid INTEGER PRIMARY KEY,
769 artistname TEXT
770 );
771 CREATE TABLE track(
772 trackid INTEGER,
773 trackname TEXT,
774 trackartist INTEGER REFERENCES artist(artistid) <b>ON UPDATE CASCADE</b>
775 );
776
777 sqlite&gt; SELECT * FROM artist;
778 artistid artistname
779 -------- -----------------
780 1 Dean Martin
781 2 Frank Sinatra
782
783 sqlite&gt; SELECT * FROM track;
784 trackid trackname trackartist
785 ------- ----------------- -----------
786 11 That's Amore 1
787 12 Christmas Blues 1
788 13 My Way 2
789
790 sqlite&gt; <i>-- Update the artistid column of the artist record for "Dean Martin".</i>
791 sqlite&gt; <i>-- Normally, this would raise a constraint, as it would orphan the two</i>
792 sqlite&gt; <i>-- dependent records in the track table. However, the ON UPDATE CASCADE clause</i>
793 sqlite&gt; <i>-- attached to the foreign key definition causes the update to "cascade"</i>
794 sqlite&gt; <i>-- to the child table, preventing the foreign key constraint violation.</i>
795 sqlite&gt; UPDATE artist SET artistid = 100 WHERE artistname = 'Dean Martin';
796
797 sqlite&gt; SELECT * FROM artist;
798 artistid artistname
799 -------- -----------------
800 2 Frank Sinatra
801 100 Dean Martin
802
803 sqlite&gt; SELECT * FROM track;
804 trackid trackname trackartist
805 ------- ----------------- -----------
806 11 That's Amore 100
807 12 Christmas Blues 100
808 13 My Way 2
809 </pre></div>
810
811 <p>
812 Configuring an ON UPDATE or ON DELETE action does not mean that the foreign
813 key constraint does not need to be satisfied. For example, if an
814 "ON DELETE SET DEFAULT" action is configured,
815 but there is no row in the parent table
816 that corresponds to the default values of the child key columns, deleting
817 a parent key while dependent child keys exist still causes a foreign key
818 violation. For example:
819
820 </p><div class="codeblock"><pre><i>-- Database schema</i>
821 CREATE TABLE artist(
822 artistid INTEGER PRIMARY KEY,
823 artistname TEXT
824 );
825 CREATE TABLE track(
826 trackid INTEGER,
827 trackname TEXT,
828 trackartist INTEGER <b>DEFAULT 0</b> REFERENCES artist(artistid) <b>ON DELETE SET DEFAULT</b>
829 );
830
831 sqlite&gt; SELECT * FROM artist;
832 artistid artistname
833 -------- -----------------
834 3 Sammy Davis Jr.
835
836 sqlite&gt; SELECT * FROM track;
837 trackid trackname trackartist
838 ------- ----------------- -----------
839 14 Mr. Bojangles 3
840
841 sqlite&gt; <i>-- Deleting the row from the parent table causes the child key</i>
842 sqlite&gt; <i>-- value of the dependent row to be set to integer value 0. However, this</i>
843 sqlite&gt; <i>-- value does not correspond to any row in the parent table. Therefore</i>
844 sqlite&gt; <i>-- the foreign key constraint is violated and an is exception thrown.</i>
845 sqlite&gt; DELETE FROM artist WHERE artistname = 'Sammy Davis Jr.';
846 <b>SQL error: foreign key constraint failed</b>
847
848 sqlite&gt; <i>-- This time, the value 0 does correspond to a parent table row. And</i>
849 sqlite&gt; <i>-- so the DELETE statement does not violate the foreign key constraint</i>
850 sqlite&gt; <i>-- and no exception is thrown.</i>
851 sqlite&gt; INSERT INTO artist VALUES(0, 'Unknown Artist');
852 sqlite&gt; DELETE FROM artist WHERE artistname = 'Sammy Davis Jr.';
853
854 sqlite&gt; SELECT * FROM artist;
855 artistid artistname
856 -------- -----------------
857 0 Unknown Artist
858
859 sqlite&gt; SELECT * FROM track;
860 trackid trackname trackartist
861 ------- ----------------- -----------
862 14 Mr. Bojangles 0
863 </pre></div>
864
865 <p>
866 Those familiar with <a href="lang_createtrigger.html">SQLite triggers</a>
867 will have noticed that the
868 "ON DELETE SET DEFAULT" action demonstrated in the example above is
869 similar in effect to the following AFTER DELETE trigger:
870 </p><div class="codeblock"><pre>CREATE TRIGGER on_delete_set_default AFTER DELETE ON artist BEGIN
871 UPDATE child SET trackartist = 0 WHERE trackartist = old.artistid;
872 END;
873 </pre></div>
874
875 <p>
876 Whenever a row in the parent table of a foreign key constraint is deleted,
877 or when the values stored in the parent key column or columns are modified,
878 the logical sequence of events is:
879
880 </p><ol>
881 <li> Execute applicable BEFORE trigger programs,
882 </li><li> Check local (non foreign key) constraints,
883 </li><li> Update or delete the row in the parent table,
884 </li><li> Perform any required foreign key actions,
885 </li><li> Execute applicable AFTER trigger programs.
886 </li></ol>
887
888 <p>
889 There is one important difference between ON UPDATE foreign key actions and
890 SQL triggers. An ON UPDATE action is only taken if the values of the
891 parent key are modified so that the new parent key values are
892 not equal to the old. For example:
893
894 </p><div class="codeblock"><pre><i>-- Database schema</i>
895 CREATE TABLE parent(x PRIMARY KEY);
896 CREATE TABLE child(y REFERENCES parent ON UPDATE SET NULL);
897
898 sqlite&gt; SELECT * FROM parent;
899 x
900 ----
901 key
902
903 sqlite&gt; SELECT * FROM child;
904 y
905 ----
906 key
907
908 sqlite&gt; <i>-- Since the following UPDATE statement does not actually modify</i>
909 sqlite&gt; <i>-- the parent key value, the ON UPDATE action is not performed and</i>
910 sqlite&gt; <i>-- the child key value is not set to NULL.</i>
911 sqlite&gt; UPDATE parent SET x = 'key';
912 sqlite&gt; SELECT IFNULL(y, 'null') FROM child;
913 y
914 ----
915 key
916
917 sqlite&gt; <i>-- This time, since the UPDATE statement does modify the parent key</i>
918 sqlite&gt; <i>-- value, the ON UPDATE action is performed and the child key is set</i>
919 sqlite&gt; <i>-- to NULL.</i>
920 sqlite&gt; UPDATE parent SET x = 'key2';
921 sqlite&gt; SELECT IFNULL(y, 'null') FROM child;
922 y
923 ----
924 null
925 </pre></div>
926
927 <h1 id="fk_schemacommands"><span>5. </span>CREATE, ALTER and DROP TABLE commands</h1>
928
929 <p>
930 This section describes the way the <a href="lang_createtable.html">CREATE TABLE</a>, <a href="lang_altertable.html">ALTER TABLE</a>,
931 and <a href="lang_droptable.html">DROP TABLE</a> commands
932 interact with SQLite's foreign keys.
933
934 </p><p>
935 A <a href="lang_createtable.html">CREATE TABLE</a> command operates the same whether or not
936 <a href="foreignkeys.html#fk_enable">foreign key constraints are enabled</a>. The parent key definitions of
937 foreign key constraints are not checked when a table is created. There is
938 nothing stopping the user from creating a foreign key definition that
939 refers to a parent table that does not exist, or to parent key columns that
940 do not exist or are not collectively bound by a PRIMARY KEY or UNIQUE
941 constraint.
942
943 </p><p>
944 The <a href="lang_altertable.html">ALTER TABLE</a> command works differently in two respects when foreign
945 key constraints are enabled:
946
947 </p><ul>
948 <li><p>
949 It is not possible to use the "ALTER TABLE ... ADD COLUMN" syntax
950 to add a column that includes a REFERENCES clause, unless the default
951 value of the new column is NULL. Attempting to do so returns an
952 error.
953
954 </p></li><li><p>
955 If an "ALTER TABLE ... RENAME TO" command is used to rename a table
956 that is the parent table of one or more foreign key constraints, the
957 definitions of the foreign key constraints are modified to refer to
958 the parent table by its new name. The text of the child CREATE
959 TABLE statement or statements stored in the <a href="schematab.html">sqlite_schema table</a> are
960 modified to reflect the new parent table name.
961 </p></li></ul>
962
963 <p>
964 If foreign key constraints are enabled when it is prepared, the
965 <a href="lang_droptable.html">DROP TABLE</a> command performs an implicit <a href="lang_delete.html">DELETE</a> to remove all
966 rows from the table before dropping it. The implicit DELETE does not cause
967 any SQL triggers to fire, but may invoke foreign key actions or constraint
968 violations. If an immediate foreign key constraint is violated, the DROP
969 TABLE statement fails and the table is not dropped. If a deferred foreign
970 key constraint is violated, then an error is reported when the user attempts
971 to commit the transaction if the foreign key constraint violations still
972 exist at that point. Any "foreign key mismatch" errors encountered as part
973 of an implicit DELETE are ignored.
974
975 </p><p>
976 The intent of these enhancements to the <a href="lang_altertable.html">ALTER TABLE</a> and <a href="lang_droptable.html">DROP TABLE</a>
977 commands is to ensure that they cannot be used to create a database that
978 contains foreign key violations, at least while foreign key constraints are
979 enabled. There is one exception to this rule though. If a parent key is
980 not subject to a PRIMARY KEY or UNIQUE constraint created as part of the
981 parent table definition, but is subject to a UNIQUE constraint by virtue
982 of an index created using the <a href="lang_createindex.html">CREATE INDEX</a> command, then the child
983 table may be populated without causing a "foreign key mismatch" error. If
984 the UNIQUE index is dropped from the database schema, then the parent table
985 itself is dropped, no error will be reported. However the database may be
986 left in a state where the child table of the foreign key constraint contains
987 rows that do not refer to any parent table row. This case can be avoided
988 if all parent keys in the database schema are constrained by PRIMARY KEY
989 or UNIQUE constraints added as part of the parent table definition, not
990 by external UNIQUE indexes.
991
992 </p><p>
993 The properties of the <a href="lang_droptable.html">DROP TABLE</a> and <a href="lang_altertable.html">ALTER TABLE</a> commands described
994 above only apply if foreign keys are enabled. If the user considers them
995 undesirable, then the workaround is to use <a href="pragma.html#pragma_foreign_keys">PRAGMA foreign_keys</a> to
996 disable foreign key constraints before executing the DROP or ALTER TABLE
997 command. Of course, while foreign key constraints are disabled, there is nothing
998 to stop the user from violating foreign key constraints and thus creating
999 an internally inconsistent database.
1000
1001
1002
1003 </p><h1 id="fk_unsupported"><span>6. </span>Limits and Unsupported Features</h1>
1004
1005 <p>
1006 This section lists a few limitations and omitted features that are not
1007 mentioned elsewhere.
1008
1009 </p><ol>
1010 <li><p>
1011 <b>No support for the MATCH clause.</b> According to SQL92, a MATCH clause
1012 may be attached to a composite foreign key definition to modify the way
1013 NULL values that occur in child keys are handled. If "MATCH SIMPLE" is
1014 specified, then a child key is not required to correspond to any row
1015 of the parent table if one or more of the child key values are NULL.
1016 If "MATCH FULL" is specified, then if any of the child key values is
1017 NULL, no corresponding row in the parent table is required, but all
1018 child key values must be NULL. Finally, if the foreign key constraint
1019 is declared as "MATCH PARTIAL" and one of the child key values is NULL,
1020 there must exist at least one row in the parent table for which the
1021 non-NULL child key values match the parent key values.
1022
1023 </p><p>
1024 SQLite parses MATCH clauses (i.e. does not report a syntax error
1025 if you specify one), but does not enforce them. All foreign key
1026 constraints in SQLite are handled as if MATCH SIMPLE were specified.
1027 </p></li><li> <p>
1028 <b>No support for switching constraints between deferred and immediate
1029 mode.</b> Many systems allow the user to toggle individual foreign key
1030 constraints between <a href="#fk_deferred">deferred</a> and immediate
1031 mode at runtime (for example using the Oracle "SET CONSTRAINT" command).
1032 SQLite does not support this. In SQLite, a foreign key constraint is
1033 permanently marked as deferred or immediate when it is created.
1034
1035 </p></li><li><p>
1036 <b>Recursion limit on foreign key actions.</b> The
1037 <a href="limits.html#max_trigger_depth">SQLITE_MAX_TRIGGER_DEPTH</a> and <a href="c3ref/c_limit_attached.html#sqlitelimittriggerdepth">SQLITE_LIMIT_TRIGGER_DEPTH</a>
1038 settings determine the maximum allowable depth of trigger
1039 program recursion. For the purposes of these limits,
1040 <a href="foreignkeys.html#fk_actions">foreign key actions</a> are considered trigger programs. The
1041 <a href="pragma.html#pragma_recursive_triggers">PRAGMA recursive_triggers</a> setting does not affect the operation
1042 of foreign key actions. It is not possible to disable recursive foreign
1043 key actions.
1044
1045 </p></li><li><p>
1046 <b>Foreign keys may not cross schema boundaries.</b> That is, in
1047 <code>REFERENCES (X.Y)</code> table <code>X</code> will only be resolved
1048 within the schema which contains the <code>REFERENCES</code> clause.
1049 </p></li></ol>
1050 <p align="center"><small><i>This page last modified on <a href="https://sqlite.org/docsrc/honeypot" id="mtimelink" data-href="https://sqlite.org/docsrc/finfo/pages/foreignkeys.in?m=a8733ccf86">2024-01-23 13:08:17</a> UTC </small></i></p>
1051