SQL Constraints · Primary Key · Foreign Key · Guide + 25 Interview Questions

SQL Constraints: Enforcing Data Integrity at the Database Level

SQL constraints are rules enforced by the database to maintain data integrity. They prevent invalid data from being inserted, updated, or deleted — without relying on application code. This guide covers all constraint types: NOT NULL, UNIQUE, PRIMARY KEY, FOREIGN KEY, CHECK, DEFAULT, composite keys, cascading actions, referential integrity, and deferred constraints, with the 25 interview questions that actually come up.

🎯 Key Takeaways
25 Interview Questions Beginner to Advanced Oracle, MySQL, PostgreSQL & SQL Server Updated Dec 3, 2026
Kailas Warade ✓ Verified Author
Data Engineer · Oracle Certified · SQL & PL/SQL
Kailas works with SQL, PL/SQL, Python, and PySpark to build data pipelines. He writes the SQL interview guides at Sankalan Data Tech, focused on practical, real-world answers.
🏆 Oracle Certified 💼 Data Engineer 📝 SQL & PL/SQL Guides 📍 Pune, India
📤 Share:

On This Page

What Constraints Really Are

A constraint is a rule enforced by the database to maintain data integrity. It prevents invalid data from being inserted, updated, or deleted — without relying on application code.

The key idea is that the database itself enforces the rule. Even if application code has a bug, the database will reject invalid data. This is the last line of defense for data quality.

Constraints are defined at the table level and apply to all rows. They are checked on every INSERT, UPDATE, and DELETE that affects the constrained column.

Constraints are essential for data quality, referential integrity, and business rule enforcement. Every well-designed database uses them.

All Constraint Types

SQL supports several types of constraints, each solving a different data integrity problem.

Constraint What It Enforces Example
NOT NULL Column must have a value name VARCHAR(100) NOT NULL
UNIQUE Values must be unique email VARCHAR(255) UNIQUE
PRIMARY KEY Uniquely identifies each row id INT PRIMARY KEY
FOREIGN KEY References primary key of another table dept_id INT REFERENCES departments(id)
CHECK Value must satisfy a condition salary DECIMAL CHECK (salary > 0)
DEFAULT Value used when none specified status VARCHAR(20) DEFAULT 'Active'

Some databases also support EXCLUDE constraints (PostgreSQL) and assertion constraints, but the six above are the universal core.

Primary Key

A primary key uniquely identifies each row in a table. It combines NOT NULL and UNIQUE, and a table can have only one primary key.

CREATE TABLE employees (
    employee_id INT PRIMARY KEY,
    employee_name VARCHAR(100) NOT NULL,
    salary DECIMAL(10,2)
);

The primary key is the most important constraint in a relational database. It is the anchor for all relationships (foreign keys) and the basis for indexing.

A primary key can be a single column or a combination of columns (composite key). In either case, uniqueness is enforced on the combination.

Foreign Key and Referential Integrity

A foreign key is a column that references the primary key of another table. It enforces referential integrity between tables.

CREATE TABLE departments (
    department_id INT PRIMARY KEY,
    department_name VARCHAR(100)
);

CREATE TABLE employees (
    employee_id INT PRIMARY KEY,
    employee_name VARCHAR(100),
    department_id INT,
    FOREIGN KEY (department_id) REFERENCES departments(department_id)
);

Referential integrity means that a foreign key value must always match an existing primary key value in the referenced table. You cannot insert an employee with a department_id that does not exist in departments.

This prevents orphan records — child rows with no valid parent. It is one of the most important integrity guarantees in relational databases.

Cascading Actions

Cascading actions define what happens to child rows when a parent row is deleted or updated. The two main options are CASCADE and SET NULL.

-- ON DELETE CASCADE: delete child rows when parent is deleted
FOREIGN KEY (department_id) REFERENCES departments(department_id)
ON DELETE CASCADE

-- ON DELETE SET NULL: set child FK to NULL when parent is deleted
FOREIGN KEY (department_id) REFERENCES departments(department_id)
ON DELETE SET NULL

CASCADE is useful for true parent-child relationships (like order-items). SET NULL is useful when the relationship is optional (like employee-department).

Choosing the right cascading action is a key design decision. The wrong choice can cause accidental data loss or orphan records.

25 SQL Constraints Interview Questions and Answers

These are the SQL constraint questions that come up most often in interviews. Every answer stands on its own — read them in any order, or work through them in sequence to build a complete understanding of all constraint types.

🔍

No matching questions found

Try a keyword like primary key, foreign key, unique, or cascade.

A constraint is a rule enforced by the database to maintain data integrity. It prevents invalid data from being inserted, updated, or deleted.

CREATE TABLE employees (
    employee_id INT PRIMARY KEY,
    salary DECIMAL(10,2) CHECK (salary > 0)
);

The key idea is that the database itself enforces the rule. Even if application code has a bug, the database will reject invalid data.

Constraints are the last line of defense for data quality. They apply to all rows and are checked on every DML operation.

The main types of constraints in SQL are:

  • NOT NULL — Column must have a value
  • UNIQUE — Values must be unique
  • PRIMARY KEY — Uniquely identifies each row
  • FOREIGN KEY — References primary key of another table
  • CHECK — Value must satisfy a condition
  • DEFAULT — Value used when none specified
CREATE TABLE employees (
    employee_id INT PRIMARY KEY,
    employee_name VARCHAR(100) NOT NULL,
    email VARCHAR(255) UNIQUE,
    salary DECIMAL(10,2) CHECK (salary > 0),
    status VARCHAR(20) DEFAULT 'Active',
    department_id INT REFERENCES departments(department_id)
);

These six constraints cover the vast majority of data integrity needs in relational databases.

A primary key uniquely identifies each row in a table. It combines NOT NULL and UNIQUE, and a table can have only one primary key.

CREATE TABLE employees (
    employee_id INT PRIMARY KEY,
    employee_name VARCHAR(100)
);

The primary key is the anchor for all relationships (foreign keys) and the basis for indexing. It is the most important constraint in a relational database.

A primary key can be a single column or a combination of columns (composite key).

A foreign key is a column that references the primary key of another table. It enforces referential integrity between tables.

CREATE TABLE employees (
    employee_id INT PRIMARY KEY,
    department_id INT,
    FOREIGN KEY (department_id) REFERENCES departments(department_id)
);

Referential integrity means that a foreign key value must always match an existing primary key value in the referenced table. This prevents orphan records.

A foreign key can be NULL unless it is also declared NOT NULL.

A unique constraint ensures that values in a column or set of columns are unique across the table. Unlike a primary key, it can allow NULL values.

CREATE TABLE users (
    user_id INT PRIMARY KEY,
    email VARCHAR(255) UNIQUE
);

A table can have multiple unique constraints, but only one primary key. Unique constraints are useful for columns like email, username, or phone number.

A check constraint enforces a condition on column values, such as salary > 0 or age between 18 and 100.

CREATE TABLE employees (
    employee_id INT PRIMARY KEY,
    salary DECIMAL(10,2) CHECK (salary > 0),
    age INT CHECK (age BETWEEN 18 AND 100)
);

Check constraints enforce business rules at the database level. They are useful for validating data before it enters the table.

Note that check constraints cannot reference other tables or use subqueries.

A NOT NULL constraint ensures that a column cannot contain NULL values. Every row must have a value for that column.

CREATE TABLE employees (
    employee_id INT PRIMARY KEY,
    employee_name VARCHAR(100) NOT NULL
);

NOT NULL is the simplest but most important constraint. It ensures that critical columns always have data.

A primary key implicitly includes NOT NULL.

A DEFAULT constraint provides a value for a column when no value is specified during INSERT.

CREATE TABLE employees (
    employee_id INT PRIMARY KEY,
    status VARCHAR(20) DEFAULT 'Active',
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

DEFAULT constraints reduce the need for application code to set common values. They are useful for status flags, timestamps, and counters.

A primary key does not allow NULL and a table can have only one. A unique key can allow NULL and a table can have multiple unique keys.

Aspect Primary Key Unique Key
NULL allowed No Yes (in most databases)
Count per table One Multiple
Index Usually clustered Usually non-clustered
Purpose Row identity Uniqueness on non-key columns

Use a primary key for row identity. Use unique keys for business uniqueness rules like email or username.

A composite key is a primary key made of two or more columns. Uniqueness is enforced on the combination, not individually.

CREATE TABLE order_items (
    order_id INT,
    product_id INT,
    quantity INT,
    PRIMARY KEY (order_id, product_id)
);

In this example, the same product can appear in different orders, and the same order can have different products. But the combination of order_id and product_id must be unique.

Composite keys are common in junction tables for many-to-many relationships.

ON DELETE CASCADE automatically deletes child rows when the parent row is deleted.

CREATE TABLE order_items (
    order_id INT,
    product_id INT,
    FOREIGN KEY (order_id) REFERENCES orders(order_id)
    ON DELETE CASCADE
);

When an order is deleted, all its order_items are automatically deleted too. This is useful for true parent-child relationships where child rows have no meaning without the parent.

Use with caution — cascading deletes can remove a lot of data quickly.

ON DELETE SET NULL sets the foreign key column to NULL when the parent row is deleted, instead of deleting the child row.

CREATE TABLE employees (
    employee_id INT PRIMARY KEY,
    department_id INT,
    FOREIGN KEY (department_id) REFERENCES departments(department_id)
    ON DELETE SET NULL
);

When a department is deleted, employees in that department are not deleted — their department_id becomes NULL. This is useful when the relationship is optional.

The foreign key column must allow NULL for this to work.

Referential integrity ensures that a foreign key value always matches an existing primary key value in the referenced table.

-- Valid: department_id 10 exists in departments
INSERT INTO employees (employee_id, department_id) VALUES (1, 10);

-- Invalid: department_id 99 does not exist
INSERT INTO employees (employee_id, department_id) VALUES (2, 99);
-- Error: foreign key constraint violation

Referential integrity prevents orphan records — child rows with no valid parent. It is one of the most important integrity guarantees in relational databases.

Yes, a foreign key can be NULL unless it is also declared NOT NULL. A NULL foreign key means no relationship exists.

CREATE TABLE employees (
    employee_id INT PRIMARY KEY,
    department_id INT NULL,  -- can be NULL
    FOREIGN KEY (department_id) REFERENCES departments(department_id)
);

A NULL foreign key is different from an invalid foreign key. NULL means "no relationship", while an invalid value means "relationship points to something that does not exist".

A deferred constraint is checked at the end of a transaction rather than immediately. This allows temporary violations during the transaction.

-- PostgreSQL example
SET CONSTRAINTS ALL DEFERRED;

-- Insert parent and child in any order
INSERT INTO departments VALUES (10, 'Sales');
INSERT INTO employees VALUES (1, 'Alice', 10);
COMMIT;  -- constraint checked here

Deferred constraints are useful when you need to insert parent and child rows in a specific order that would otherwise violate the constraint mid-transaction.

Support varies by database — PostgreSQL supports it, Oracle supports it for some constraint types, MySQL does not.

You can add a constraint to an existing table using ALTER TABLE.

-- Add a CHECK constraint
ALTER TABLE employees
ADD CONSTRAINT chk_salary CHECK (salary > 0);

-- Add a FOREIGN KEY constraint
ALTER TABLE employees
ADD CONSTRAINT fk_department
FOREIGN KEY (department_id) REFERENCES departments(department_id);

Always name constraints explicitly. This makes them easier to find, modify, or drop later.

Adding a constraint to a table with existing data will fail if existing data violates the constraint.

You can drop a constraint using ALTER TABLE DROP CONSTRAINT.

-- Drop a named constraint
ALTER TABLE employees
DROP CONSTRAINT chk_salary;

-- Drop a primary key (syntax varies by database)
ALTER TABLE employees
DROP PRIMARY KEY;

Dropping a constraint removes the integrity rule but does not delete data. Existing data stays, but new data is no longer validated.

Be careful — dropping a foreign key can allow orphan records to be created.

A constraint is a declarative rule enforced automatically by the database. A trigger is procedural code that fires on DML events.

Aspect Constraint Trigger
Nature Declarative rule Procedural code
Enforcement Automatic by database Fires on DML events
Complexity Simple, limited Can be complex
Performance Usually faster Can be slower

Use constraints for simple integrity rules. Use triggers for complex logic that constraints cannot express, like auditing or cross-table validation.

Prefer constraints when possible — they are simpler, faster, and more reliable.

An EXCLUDE constraint is a PostgreSQL-specific constraint that ensures no two rows satisfy a given condition, often used for overlapping ranges.

-- PostgreSQL: no overlapping bookings
CREATE TABLE bookings (
    room_id INT,
    during TSRANGE,
    EXCLUDE USING gist (room_id WITH =, during WITH &&)
);

This prevents two bookings for the same room from overlapping in time. It is more powerful than a simple UNIQUE constraint because it handles ranges, not just exact values.

EXCLUDE constraints are PostgreSQL-specific and require the btree_gist extension.

A self-referencing foreign key is a foreign key that references the primary key of the same table. It is used for hierarchical data like employee-manager relationships.

CREATE TABLE employees (
    employee_id INT PRIMARY KEY,
    employee_name VARCHAR(100),
    manager_id INT,
    FOREIGN KEY (manager_id) REFERENCES employees(employee_id)
);

In this example, manager_id references employee_id in the same table. This models the employee-manager hierarchy.

Self-referencing foreign keys are common in organizational charts, category trees, and bill-of-materials structures.

ON UPDATE CASCADE automatically updates child rows when the parent's primary key is updated.

CREATE TABLE employees (
    employee_id INT PRIMARY KEY,
    department_id INT,
    FOREIGN KEY (department_id) REFERENCES departments(department_id)
    ON UPDATE CASCADE
);

When a department's primary key changes, all employees referencing it are automatically updated too. This keeps referential integrity intact.

ON UPDATE CASCADE is less common than ON DELETE CASCADE because primary keys rarely change in practice.

A constraint is a rule for data integrity. An index is a structure for query performance. They serve different purposes but often work together.

-- Constraint: enforces uniqueness
UNIQUE (email)

-- Index: speeds up queries
CREATE INDEX idx_email ON users(email);

A unique constraint automatically creates an index to enforce uniqueness. A regular index does not enforce any rule — it just speeds up lookups.

Constraints are about correctness. Indexes are about speed. They overlap because enforcing uniqueness requires an index.

No. A CHECK constraint can only reference columns in the same row of the same table. It cannot use subqueries or reference other tables.

-- Valid: references same row
CHECK (salary > 0)

-- Invalid: references another table
CHECK (salary < (SELECT MAX(salary) FROM salary_bands))

For cross-table validation, use a foreign key, a trigger, or application-level validation. CHECK constraints are limited to row-level logic.

The database rejects the operation and raises an error. The INSERT, UPDATE, or DELETE fails, and no changes are made for that statement.

-- Attempt to insert duplicate primary key
INSERT INTO employees (employee_id, employee_name) VALUES (1, 'Alice');
-- Error: duplicate key value violates unique constraint

The error message usually identifies which constraint was violated. In a transaction, the entire statement is rolled back (or the transaction fails, depending on the database).

This is the whole point of constraints — invalid data never enters the table.

Well-designed constraints follow a few key principles.

  • Always name constraints explicitly — makes them easier to manage.
  • Use NOT NULL liberally — most columns should not allow NULL.
  • Use CHECK for business rules — enforce validity at the database level.
  • Use FOREIGN KEY for relationships — never rely on application code alone.
  • Choose cascading actions carefully — CASCADE can cause accidental data loss.
  • Prefer constraints over triggers — simpler, faster, more reliable.
-- Well-designed table
CREATE TABLE employees (
    employee_id INT PRIMARY KEY,
    employee_name VARCHAR(100) NOT NULL,
    email VARCHAR(255) UNIQUE NOT NULL,
    salary DECIMAL(10,2) CHECK (salary > 0),
    status VARCHAR(20) DEFAULT 'Active',
    department_id INT NOT NULL,
    FOREIGN KEY (department_id) REFERENCES departments(department_id)
);

This table enforces identity, uniqueness, validity, defaults, and referential integrity — all at the database level.

Mistakes I Keep Seeing in Interviews

These come up repeatedly. None of them are exotic, and every one of them is easy to avoid once you know it is coming.

Mistake one: confusing primary key with unique key. Candidates often say they are the same — they are not. NULL handling and count-per-table are different.
Mistake two: not knowing what referential integrity means. This is the core purpose of foreign keys, and not knowing it is a red flag.
Mistake three: assuming a foreign key cannot be NULL. It can, unless explicitly declared NOT NULL.
Mistake four: using CASCADE without understanding the consequences. Cascading deletes can remove a lot of data quickly and are hard to undo.
Mistake five: using triggers for simple integrity rules. Constraints are simpler, faster, and more reliable for most integrity needs.
Mistake six: not naming constraints. Unnamed constraints get auto-generated names that are hard to manage later.

Follow-Up Questions Interviewers Ask

Getting the first answer right is only half the interview. What usually decides the outcome is what happens next. Here is what to prepare for on the constraints topic.

After “What is a primary key?” — expect

  • “How does it differ from a unique key?”
  • “Can a primary key be NULL?”
  • “What is a composite key?”
  • “How many primary keys can a table have?”

After “What is a foreign key?” — expect

  • “What is referential integrity?”
  • “Can a foreign key be NULL?”
  • “What is ON DELETE CASCADE?”
  • “What is a self-referencing foreign key?”

After “CHECK constraint” — expect

  • “Can it reference another table?”
  • “What happens if existing data violates it?”
  • “How does it differ from a trigger?”
  • “Can it use subqueries?”

After “Cascading actions” — expect

  • “What is the difference between CASCADE and SET NULL?”
  • “When would you use each?”
  • “What are the risks of CASCADE?”
  • “What is ON UPDATE CASCADE?”

For every question above, prepare a second-level answer. The candidates who pass are not the ones who memorized the first answer — they are the ones who kept going for another thirty seconds and said something useful about why it matters.

Quick Quiz

Three questions to check whether the topics above have landed.

1. Which constraint uniquely identifies each row in a table?
2. What happens to child rows when a parent is deleted with ON DELETE CASCADE?
3. Which constraint enforces a condition on column values?