Search GimmeJob

Type at least 2 characters. Enter also searches by meaning.
QA interview question
Databases, SQL & BIDatabase conceptJuniorCommonTheory

How do primary keys, foreign keys, UNIQUE, NOT NULL, CHECK and DEFAULT constraints differ?

Answer

A primary key uniquely identifies each row. A foreign key constrains a non-NULL referencing value to a valid referenced key; whether NULL is allowed depends on the column definition. UNIQUE prevents duplicate key values under the DBMS's NULL rules, NOT NULL requires a value, CHECK enforces a predicate and DEFAULT supplies a value when one is omitted. Tests should cover valid writes, each violation, composite keys, update/delete actions and product-specific NULL behavior.

Strong answer includes

  • explains identity and referential integrity
  • distinguishes all major constraint types
  • tests negative writes and update/delete behaviour

Practical example

Declare and then challenge integrity constraints
Dialect · SQL standardRuntime · static example

Static negative-test example: it intentionally triggers constraint errors and needs an isolated schema with foreign-key enforcement enabled.

CREATE TABLE users (
  id BIGINT PRIMARY KEY,
  email TEXT NOT NULL UNIQUE,
  age INTEGER CHECK (age >= 18),
  status TEXT DEFAULT 'active'
);

CREATE TABLE orders (
  id BIGINT PRIMARY KEY,
  user_id BIGINT NOT NULL REFERENCES users(id)
);

-- Negative tests:
INSERT INTO users (id, email, age) VALUES (1, 'a@example.com', 17);
INSERT INTO orders (id, user_id) VALUES (10, 999);

The first negative insert should violate CHECK; the second should violate the foreign key. Similar tests should cover duplicate email, NULL email, updates and delete behavior on referenced users.

Expected result: Both negative inserts are rejected by the database.

#database#sql#constraints#keys

Sources

PostgreSQL documentationPostgreSQL Global Development Group · Relational modelling, SQL, joins, constraints, transactions, concurrency, indexes, query plans and recovery