Skip to content

Commit 8e4e5f0

Browse files
enhance the foreign key chapter
1 parent 839f963 commit 8e4e5f0

File tree

3 files changed

+111
-59
lines changed

3 files changed

+111
-59
lines changed

.devcontainer/cheatsheet.txt

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
docker compose up --build -d
2+
docker compose ps -a
3+
docker compose exec app bash
4+
docker compose down
5+
6+
docker stop $(docker ps -aq)
7+
docker rm $(docker ps -aq)
8+
9+
# in home folder
10+
devcontainer build --workspace-folder .
11+
devcontainer up --workspace-folder .
12+
devcontainer exec --workspace-folder . bash
13+

book/30-schema-design/030-foreign-keys.ipynb

Lines changed: 32 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,7 @@
2626
},
2727
{
2828
"cell_type": "code",
29-
"execution_count": 3,
29+
"execution_count": 9,
3030
"metadata": {},
3131
"outputs": [
3232
{
@@ -139,6 +139,37 @@
139139
"The parent table `Title` is above and the child table `Employee` is below."
140140
]
141141
},
142+
{
143+
"cell_type": "markdown",
144+
"metadata": {},
145+
"source": [
146+
"## Defining Foreign Keys in SQL\n",
147+
"In standard SQL, the same relationship is defined with more verbose syntax. The child table must explicitly redefine the columns of the parent's primary key and then declare the foreign key constraint.\n",
148+
"\n",
149+
"Notice that the data type (`char(8)`) of the primary key in `Title` must be exactly repeated for the `title_code` column in `Employee`.\n",
150+
"\n",
151+
"```sql\n",
152+
"-- Parent Table\n",
153+
"CREATE TABLE title (\n",
154+
" title_code CHAR(8) NOT NULL,\n",
155+
" full_title VARCHAR(120) NOT NULL,\n",
156+
" PRIMARY KEY (title_code)\n",
157+
");\n",
158+
"\n",
159+
"-- Child Table\n",
160+
"CREATE TABLE employee (\n",
161+
"person_id INT NOT NULL,\n",
162+
"first_name VARCHAR(30) NOT NULL,\n",
163+
"last_name VARCHAR(30) NOT NULL,\n",
164+
"title_code CHAR(8) NOT NULL,\n",
165+
"PRIMARY KEY (person_id),\n",
166+
"FOREIGN KEY (title_code) REFERENCES title(title_code)\n",
167+
");\n",
168+
"```\n",
169+
"\n",
170+
"The concise `-> Title` syntax in DataJoint handles this automatically, reducing redundancy and preventing potential errors if the parent's primary key definition changes."
171+
]
172+
},
142173
{
143174
"cell_type": "markdown",
144175
"metadata": {},

0 commit comments

Comments
 (0)