Start learning free

LESSON 55 OF 173 · BACKEND: SQL

Foreign Keys in C#

Practice

An order doesn't copy its customer's name. It stores the customer's id in the column customer_id. A column that points at the primary key of another table is a foreign key, and you declare it with REFERENCES when you create the table.

For example, a table of reviews could point at the products:

CREATE TABLE reviews (
    id INTEGER PRIMARY KEY,
    product_id INTEGER NOT NULL REFERENCES products(id),
    stars INTEGER
);

By default, SQLite doesn't check foreign keys: a review for a product id that doesn't exist would be stored anyway. The setting PRAGMA foreign_keys = ON; turns the checking on for the connection, and then such an INSERT fails with FOREIGN KEY constraint failed. It only affects the statements that run after it, so it goes first.

Your query is one C# string, built from short strings joined with +, and it holds several statements one after another. The check prints how orders was made, runs your query, then shows the orders with an id above 7. Your code must make it print:

sql
CREATE TABLE orders (id INTEGER PRIMARY KEY, customer_id INTEGER NOT NULL REFERENCES customers(id), ordered TEXT NOT NULL, status TEXT NOT NULL)
(1 row)
Error: FOREIGN KEY constraint failed
id | customer_id | ordered | status
8 | 4 | 2026-06-01 | paid
(1 row)

Your task: in the query, add an order for Dan Weber (customer 4, '2026-06-01', 'paid') and an order for customer 9, who doesn't exist ('2026-06-02', 'paid'). Then turn foreign keys on, on the query's first line, so the second order fails and only Dan's is stored.


Assignment
Follow the Coding Tutorial to add the two orders, then turn foreign keys on so the order for the missing customer fails.


Hint
End every statement with a semicolon inside the quotes, since several follow each other, and put a + after each string. The PRAGMA goes above the INSERTs: it only checks the statements that run after it.


STEP 1 OF 3
    Ctrl + Enter to check

    Sql Foreign Keys in C#

    Keep going with C#1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free