Scrivio Interview library
CodingFoundations7 min read · updated 12 November 2026

Write PostgreSQL DDL for orders and order_lines where an order line belongs to exactly one order, deleting an order deletes its lines, a product referenced by a line cannot be deleted, and a line number is unique within an order.

We give both tables a bigint identity primary key, make order_lines.order_id NOT NULL with a foreign key ON DELETE CASCADE, make product_id NOT NULL with a foreign key ON DELETE RESTRICT, and add UNIQUE (order_id, line_no). Because PostgreSQL does not index foreign key columns for us, we also create an index on order_lines(order_id) and usually one on product_id.

Why this question is asked

Orders and their lines are the textbook parent and child pair, and almost every business system has one. Interviewers like this exercise because each sentence of the requirement maps to one precise piece of DDL, and a candidate who knows the details (nullability, the difference between RESTRICT and NO ACTION, missing indexes) stands out from one who only remembers the REFERENCES keyword. In this answer, we will translate each requirement into SQL, look at what each foreign key action really does, add the indexes PostgreSQL does not create on its own, and finally compare the design with a composite primary key.

1A Quick Recap of Keys and Foreign Keys

A primary key is the column (or set of columns) that identifies one row. It is unique and never null. A surrogate key is a primary key with no business meaning, usually a number generated by the database, while a natural key is a value from the business, such as an order number printed on an invoice.

A foreign key is a column in one table that must match a primary key (or unique key) in another table. The database checks it on every insert and update of the child, and on every delete or key update of the parent. The ON DELETE clause tells the database what to do with child rows when someone deletes the parent: cascade the delete, refuse it, or set the child column to null.

2Translating Each Requirement Into DDL

Here is the full schema. The products table is included only so the example runs on its own.

SQL
CREATE TABLE products (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
name text NOT NULL
);
CREATE TABLE orders (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
customer_id bigint NOT NULL,
placed_at timestamptz NOT NULL DEFAULT now()
);
CREATE TABLE order_lines (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
order_id bigint NOT NULL REFERENCES orders(id) ON DELETE CASCADE,
product_id bigint NOT NULL REFERENCES products(id) ON DELETE RESTRICT,
line_no int NOT NULL CHECK (line_no > 0),
quantity int NOT NULL CHECK (quantity > 0),
CONSTRAINT order_lines_order_line_uq UNIQUE (order_id, line_no)
);

GENERATED ALWAYS AS IDENTITY is the SQL standard way to get an auto-incrementing key in PostgreSQL 10 and later, and it is preferred over the older serial type because the sequence belongs to the column and nobody can insert their own value by accident.

Notice that order_id is NOT NULL. That is what turns the phrase 'belongs to exactly one order' into a rule. A foreign key only checks values that are present, so a nullable order_id would mean 'belongs to zero or one order', and an orphan line with a null order_id would be perfectly legal. The UNIQUE (order_id, line_no) constraint says line 1, line 2 and so on can repeat across orders but never twice inside the same order.

3What CASCADE, RESTRICT and NO ACTION Do

Let us see each rule in action with a few statements.

SQL
INSERT INTO products (name) VALUES ('Lamp'); -- product id 1
INSERT INTO orders (customer_id) VALUES (7); -- order id 1
INSERT INTO order_lines (order_id, product_id, line_no, quantity)
VALUES (1, 1, 1, 2), (1, 1, 2, 1); -- INSERT 0 2
INSERT INTO order_lines (order_id, product_id, line_no, quantity)
VALUES (1, 1, 2, 5);
-- ERROR: duplicate key value violates unique constraint "order_lines_order_line_uq"
DELETE FROM products WHERE id = 1;
-- ERROR: update or delete on table "products" violates foreign key constraint ...
DELETE FROM orders WHERE id = 1; -- DELETE 1
SELECT count(*) FROM order_lines; -- 0, the lines went with the order
Foreign key actions on delete of the parent
ActionWhat happens to child rowsCan be deferred?
CASCADEDeleted together with the parentNot applicable
RESTRICTDelete refused immediatelyNo
NO ACTION (default)Delete refused at end of statementYes, if DEFERRABLE
SET NULLChild column set to null (needs a nullable column)Not applicable

RESTRICT refuses the delete immediately, as soon as the statement finds a referencing row. The default action, NO ACTION, also refuses it, but checks at the end of the statement, and if the constraint is declared DEFERRABLE the check can wait until commit. That difference matters when a transaction deletes a product and then fixes the referencing lines before committing: NO ACTION with a deferred check allows it, RESTRICT never does. For a product that must simply never disappear while lines point to it, either works, and RESTRICT states the intent most clearly.

4Adding the Indexes PostgreSQL Does Not Create

PostgreSQL automatically creates an index for every primary key and every unique constraint, but not for foreign key columns. Our unique constraint happens to start with order_id, so its index already serves lookups by order. If we had chosen a different unique rule, we would need an explicit index.

SQL
-- Already covered by order_lines_order_line_uq, which starts with order_id
-- CREATE INDEX order_lines_order_id_idx ON order_lines (order_id);
CREATE INDEX order_lines_product_id_idx ON order_lines (product_id);

The order_id index matters for two things: joining an order to its lines, and the cascade itself. When we delete an order, PostgreSQL must find every line with that order_id. With an index this is a quick lookup; without one it is a full scan of order_lines for every order deleted. The product_id index serves the RESTRICT check: deleting or trying to delete a product makes PostgreSQL search order_lines for that product, and without the index that search scans the whole table.

5The Alternative: A Composite Primary Key

We could drop the surrogate id on order_lines and make (order_id, line_no) the primary key. The line is then identified by its order and its position, which is how people talk about it anyway, and we save one column and one index.

SQL
CREATE TABLE order_lines (
order_id bigint NOT NULL REFERENCES orders(id) ON DELETE CASCADE,
line_no int NOT NULL,
product_id bigint NOT NULL REFERENCES products(id) ON DELETE RESTRICT,
quantity int NOT NULL,
PRIMARY KEY (order_id, line_no)
);

The cost shows up later. Any table that references an order line, such as shipments or returns, must now carry both columns as its foreign key, and JPA needs an @EmbeddedId or @IdClass to map the key, which is more ceremony than a single Long id. A good rule of thumb is to use the composite key when nothing else references the line, and the surrogate key plus a unique constraint when other tables will.

6Follow-up questions

What happens to cascade delete performance without the index?

Every deleted order makes PostgreSQL look for matching lines in order_lines. Without an index on order_id, each lookup is a sequential scan of the whole child table, so deleting one order from a table with ten million lines reads ten million rows, and deleting a thousand orders in one statement repeats that scan a thousand times. The transaction stays open the whole time and holds its locks, so other writers queue behind it. With the index each lookup touches only the few matching rows.

Why not use ON DELETE CASCADE for products as well?

Because an order line is a record of something that was sold. If deleting a product silently removed lines from past orders, order totals and invoices would change after the fact. Products that are no longer sold should be marked inactive instead of deleted, and RESTRICT makes sure nobody deletes one by mistake.

Should line_no be generated by the database?

Usually the application assigns it when it builds the order, because the numbering is per order and a global sequence would leave gaps and not restart at 1. The unique constraint protects us if two requests try to add the same line number at the same time: one insert fails and can be retried.

7Conclusion

In this answer, we turned each sentence of the requirement into DDL: identity primary keys, a NOT NULL foreign key with ON DELETE CASCADE for 'exactly one order whose deletion removes its lines', a foreign key with ON DELETE RESTRICT so products in use cannot be deleted, and a unique constraint on (order_id, line_no). We saw the difference between RESTRICT and NO ACTION, added the indexes PostgreSQL leaves to us, and weighed a composite primary key against the surrogate one.

What to say in the interviewAbout 80 seconds aloud

Open with

I would give orders a bigint identity primary key, and order_lines its own identity id plus order_id bigint not null references orders on delete cascade, product_id bigint not null references products on delete restrict, line_no int not null, and a unique constraint on order_id and line_no.

Then, if they want more

The not null on order_id is what makes it exactly one order; a nullable foreign key would allow orphan lines. On delete cascade means deleting the order removes its lines in the same statement.

For products, restrict refuses the delete straight away; the default no action also refuses it but checks at the end of the statement and can be deferred to commit, restrict cannot. Then I would think about indexes, because PostgreSQL indexes primary and unique keys but not foreign key columns.

Here the unique constraint starts with order_id so it already serves joins and the cascade, and I would add an index on product_id so the restrict check does not scan the whole table. As an alternative, I could make order_id and line_no a composite primary key and drop the surrogate id.

That is neat if nothing references a line, but if shipments or returns point to lines they would need a two-column foreign key, so I usually keep the surrogate key.

About this answer

Last updated
12 November 2026
Versions it names
PostgreSQL 10
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "Write PostgreSQL DDL for orders and order_lines where an order line belongs to exactly...": https://scrivio-interview-library.netlify.app/databases/data-modeling/b6588cdb18/