QA
Beginner LevelSQL & MySQL

What are Primary Keys, Foreign Keys, and Referential Integrity constraints?

❓ Interview Prompt: Explain Primary Keys, Composite Primary Keys, Foreign Keys, referential integrity constraints, and cascading actions.

Relational database integrity relies on primary and foreign key constraints:

Key Definitions:

•
Primary Key (PK): Uniquely identifies each record in a table. Must contain unique, non-null values.
•
Foreign Key (FK): A column or group of columns in one table referencing the Primary Key of another table, establishing a parent-child relationship.
•
Referential Integrity: Guarantees child FK values always reference a valid existing parent PK record ('ON DELETE CASCADE' or 'ON DELETE SET NULL').

Code Implementation Example

sql
CREATE TABLE users (
    id BIGINT AUTO_INCREMENT PRIMARY KEY,
    email VARCHAR(255) NOT NULL UNIQUE
);

CREATE TABLE orders (
    id BIGINT AUTO_INCREMENT PRIMARY KEY,
    user_id BIGINT NOT NULL,
    total DECIMAL(10, 2) NOT NULL,
    CONSTRAINT fk_orders_user FOREIGN KEY (user_id)
        REFERENCES users(id) ON DELETE CASCADE
);
💡Defining Primary Key and Foreign Key constraints with ON DELETE CASCADE.
🎯 Interview Key Takeaway

Primary Keys enforce row uniqueness; Foreign Keys enforce referential integrity across relational tables.

#SQL#Primary Key#Foreign Key#Constraints#Beginner
Back to all SQL & MySQL Questions→

More SQL & MySQL Interview Questions

Beginner LevelSQL & MySQL

How do B-Tree Indexes work in SQL/MySQL and how do you optimize slow queries using EXPLAIN?

Beginner LevelSQL & MySQL

How do SELECT, WHERE, ORDER BY, and LIMIT clauses filter relational datasets?

Beginner LevelSQL & MySQL

What are INNER JOIN, LEFT JOIN, RIGHT JOIN, and FULL OUTER JOIN?