InterviewTreedInterviewTreed

InterviewTreed Question Bank

SQL & Database Design Interview Questions and Answers

Prepare for SQL and database interviews, covering query writing, joins, stored procedures, indexing, transactions, normalization, database architecture, and performance optimization.

Total Questions

120

Beginner

43

Intermediate

45

Advanced

32

Beginner Questions

Foundational concepts, terminology, and core ideas.

Q1Database design fundamentals

What is database design?

Database design is the process of modeling data, relationships, constraints, and access patterns so information remains accurate, maintainable, and efficie

Answer

Database design is the process of modeling data, relationships, constraints, and access patterns so information remains accurate, maintainable, and efficient.

Example: Example: an online store needs customers, products, orders, and order lines.

Diagram / flow: Requirements → conceptual model → logical schema → physical schema → validation

Syntax

Requirements → conceptual model → logical schema → physical schema → validation

Example

Requirements → conceptual model → logical schema → physical schema → validation

Code example

Requirements → conceptual model → logical schema → physical schema → validation

Diagram

Diagram / flow:
Requirements → conceptual model → logical schema → physical schema → validation

Key Points

  • Design should reflect business rules and query patterns.
Q2Database design fundamentals

What is a DBMS?

A database management system stores, retrieves, secures, and manages data. Examples include SQL Server, PostgreSQL, MySQL, and Oracle Database.

Answer

A database management system stores, retrieves, secures, and manages data. Examples include SQL Server, PostgreSQL, MySQL, and Oracle Database.

Example: A DBMS manages concurrency, transactions, permissions, backup, and recovery.

Diagram / flow: Application → DBMS → data files

Syntax

Application → DBMS → data files

Example

Application → DBMS → data files

Code example

Application → DBMS → data files

Diagram

Diagram / flow:
Application → DBMS → data files

Key Points

  • A DBMS is software
  • a database is the managed collection of data.
Q3Relational model

What is a relational database?

A relational database represents data using tables of rows and columns, with relationships expressed through keys and constraints.

Answer

A relational database represents data using tables of rows and columns, with relationships expressed through keys and constraints.

Example: An order's CustomerId refers to the customer who placed it.

Diagram / flow: Customers(CustomerId PK, Name) Orders(OrderId PK, CustomerId FK)

Syntax

Customers(CustomerId PK, Name)
Orders(OrderId PK, CustomerId FK)

Example

Customers(CustomerId PK, Name) Orders(OrderId PK, CustomerId FK)

Code example

Customers(CustomerId PK, Name)
Orders(OrderId PK, CustomerId FK)

Diagram

Diagram / flow:
Customers(CustomerId PK, Name)
Orders(OrderId PK, CustomerId FK)

Key Points

  • Relational design emphasizes keys, constraints, and predictable relationships.
Q4Relational model

What is a table, row, and column?

A table represents a relation or entity set, a row represents one record, and a column represents an attribute with a defined data type.

Answer

A table represents a relation or entity set, a row represents one record, and a column represents an attribute with a defined data type.

Example: A row might be (1, 'Pen', 12.50).

Syntax

Products(ProductId, Name, Price)

Example

Products(ProductId, Name, Price)

Code example

Products(ProductId, Name, Price)

Diagram

Relational model → database operation → result

Key Points

  • Choose clear column names and appropriate types.
Q5Keys and constraints

What is a primary key?

A primary key uniquely identifies each row and cannot contain NULL. It may consist of one or multiple columns.

Answer

A primary key uniquely identifies each row and cannot contain NULL. It may consist of one or multiple columns.

Example: CustomerId identifies one customer row.

Diagram / flow: CREATE TABLE Customer ( CustomerId INT PRIMARY KEY, Name VARCHAR(100) NOT NULL );

Syntax

CREATE TABLE Customer (
  CustomerId INT PRIMARY KEY,
  Name VARCHAR(100) NOT NULL
);

Example

CREATE TABLE Customer ( CustomerId INT PRIMARY KEY, Name VARCHAR(100) NOT NULL );

Code example

CREATE TABLE Customer (
  CustomerId INT PRIMARY KEY,
  Name VARCHAR(100) NOT NULL
);

Diagram

Diagram / flow:
CREATE TABLE Customer (
  CustomerId INT PRIMARY KEY,
  Name VARCHAR(100) NOT NULL
);

Key Points

  • Choose keys that are unique and stable.
Q6Keys and constraints

What is a foreign key?

A foreign key enforces a relationship by requiring referenced values to exist in a parent key, subject to NULL and constraint rules.

Answer

A foreign key enforces a relationship by requiring referenced values to exist in a parent key, subject to NULL and constraint rules.

Example: An order cannot reference a nonexistent customer while the constraint is enforced.

Diagram / flow: CREATE TABLE Orders ( OrderId INT PRIMARY KEY, CustomerId INT NOT NULL, FOREIGN KEY (CustomerId) REFERENCES Customer(CustomerId) );

Syntax

CREATE TABLE Orders (
  OrderId INT PRIMARY KEY,
  CustomerId INT NOT NULL,
  FOREIGN KEY (CustomerId) REFERENCES Customer(CustomerId)
);

Example

CREATE TABLE Orders ( OrderId INT PRIMARY KEY, CustomerId INT NOT NULL, FOREIGN KEY (CustomerId) REFERENCES Customer(CustomerId) );

Code example

CREATE TABLE Orders (
  OrderId INT PRIMARY KEY,
  CustomerId INT NOT NULL,
  FOREIGN KEY (CustomerId) REFERENCES Customer(CustomerId)
);

Diagram

Diagram / flow:
CREATE TABLE Orders (
  OrderId INT PRIMARY KEY,
  CustomerId INT NOT NULL,
  FOREIGN KEY (CustomerId) REFERENCES Customer(CustomerId)
);

Key Points

  • Foreign keys help prevent orphan records.
Q7Keys and constraints

What is a candidate key?

A candidate key is a minimal set of attributes that uniquely identifies a row. One candidate key is chosen as the primary key; others can be alternate keys

Answer

A candidate key is a minimal set of attributes that uniquely identifies a row. One candidate key is chosen as the primary key; others can be alternate keys.

Example: A unique email may be an alternate candidate key, depending on business rules.

Diagram / flow: CustomerId and Email may each uniquely identify a customer if both are guaranteed unique.

Syntax

CustomerId and Email may each uniquely identify a customer if both are guaranteed unique.

Example

CustomerId and Email may each uniquely identify a customer if both are guaranteed unique.

Code example

CustomerId and Email may each uniquely identify a customer if both are guaranteed unique.

Diagram

Diagram / flow:
CustomerId and Email may each uniquely identify a customer if both are guaranteed unique.

Key Points

  • Candidate keys must be unique and minimal.
Q8Keys and constraints

What is a composite key?

A composite key uses two or more columns together to uniquely identify a row.

Answer

A composite key uses two or more columns together to uniquely identify a row.

Example: An order can contain many products, but each product appears at most once per order in this design.

Diagram / flow: CREATE TABLE OrderItem ( OrderId INT NOT NULL, ProductId INT NOT NULL, Quantity INT NOT NULL, PRIMARY KEY (OrderId, ProductId) );

Syntax

CREATE TABLE OrderItem (
  OrderId INT NOT NULL,
  ProductId INT NOT NULL,
  Quantity INT NOT NULL,
  PRIMARY KEY (OrderId, ProductId)
);

Example

CREATE TABLE OrderItem ( OrderId INT NOT NULL, ProductId INT NOT NULL, Quantity INT NOT NULL, PRIMARY KEY (OrderId, ProductId) );

Code example

CREATE TABLE OrderItem (
  OrderId INT NOT NULL,
  ProductId INT NOT NULL,
  Quantity INT NOT NULL,
  PRIMARY KEY (OrderId, ProductId)
);

Diagram

Diagram / flow:
CREATE TABLE OrderItem (
  OrderId INT NOT NULL,
  ProductId INT NOT NULL,
  Quantity INT NOT NULL,
  PRIMARY KEY (OrderId, ProductId)
);

Key Points

  • Composite keys are common in junction tables.
Q9Keys and constraints

What is a surrogate key?

A surrogate key is an artificial identifier, such as an identity integer or UUID, that has no business meaning.

Answer

A surrogate key is an artificial identifier, such as an identity integer or UUID, that has no business meaning.

Example: A generated numeric ID can remain stable even if a product name changes.

Syntax

CREATE TABLE Product (
  ProductId INT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  Name VARCHAR(100) NOT NULL
);

Example

CREATE TABLE Product ( ProductId INT GENERATED ALWAYS AS IDENTITY PRIMARY KEY, Name VARCHAR(100) NOT NULL );

Code example

CREATE TABLE Product (
  ProductId INT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  Name VARCHAR(100) NOT NULL
);

Diagram

Keys and constraints → database operation → result

Key Points

  • Syntax for generated keys varies by database engine.
Q10Keys and constraints

What is a natural key?

A natural key is derived from real-world business data, such as an ISO country code. Natural keys can be meaningful but may change or have complex validati

Answer

A natural key is derived from real-world business data, such as an ISO country code. Natural keys can be meaningful but may change or have complex validation rules.

Example: A two-letter country code can be a natural key if the domain guarantees its stability.

Syntax

CREATE TABLE Country (
  CountryCode CHAR(2) PRIMARY KEY,
  Name VARCHAR(100) NOT NULL
);

Example

CREATE TABLE Country ( CountryCode CHAR(2) PRIMARY KEY, Name VARCHAR(100) NOT NULL );

Code example

CREATE TABLE Country (
  CountryCode CHAR(2) PRIMARY KEY,
  Name VARCHAR(100) NOT NULL
);

Diagram

Keys and constraints → database operation → result

Key Points

  • Avoid assuming that names are unique.
Q11SQL values and predicates

What is NULL?

NULL represents missing or unknown data, not zero or an empty string. Use IS NULL or IS NOT NULL to test for it.

Answer

NULL represents missing or unknown data, not zero or an empty string. Use IS NULL or IS NOT NULL to test for it.

Example: A comparison such as Phone = NULL does not correctly test for NULL in standard SQL.

Diagram / flow: SELECT * FROM Customer WHERE Phone IS NULL;

Syntax

SELECT * FROM Customer WHERE Phone IS NULL;

Example

SELECT * FROM Customer WHERE Phone IS NULL;

Code example

SELECT * FROM Customer WHERE Phone IS NULL;

Diagram

Diagram / flow:
SELECT * FROM Customer WHERE Phone IS NULL;

Key Points

  • NULL introduces three-valued logic: true, false, and unknown.
Q12SQL values and predicates

What is the difference between NULL and an empty string?

NULL means no known value; an empty string is a known string containing zero characters. Whether empty strings are allowed is a business and engine-specifi

Answer

NULL means no known value; an empty string is a known string containing zero characters. Whether empty strings are allowed is a business and engine-specific decision.

Example: A form may submit an empty string while a database column can be NULL.

Diagram / flow: SELECT * FROM Customer WHERE MiddleName = ''; SELECT * FROM Customer WHERE MiddleName IS NULL;

Syntax

SELECT * FROM Customer WHERE MiddleName = '';
SELECT * FROM Customer WHERE MiddleName IS NULL;

Example

SELECT * FROM Customer WHERE MiddleName = ''; SELECT * FROM Customer WHERE MiddleName IS NULL;

Code example

SELECT * FROM Customer WHERE MiddleName = '';
SELECT * FROM Customer WHERE MiddleName IS NULL;

Diagram

Diagram / flow:
SELECT * FROM Customer WHERE MiddleName = '';
SELECT * FROM Customer WHERE MiddleName IS NULL;

Key Points

  • Normalize input consistently at the application boundary.
Q13Data types

What are SQL data types?

Data types define what values a column can store and how they are represented, compared, and calculated.

Answer

Data types define what values a column can store and how they are represented, compared, and calculated.

Example: Use DECIMAL for exact monetary values rather than approximate floating-point types.

Syntax

CREATE TABLE Product (
  Name VARCHAR(120),
  Price DECIMAL(10,2),
  CreatedAt TIMESTAMP
);

Example

CREATE TABLE Product ( Name VARCHAR(120), Price DECIMAL(10,2), CreatedAt TIMESTAMP );

Code example

CREATE TABLE Product (
  Name VARCHAR(120),
  Price DECIMAL(10,2),
  CreatedAt TIMESTAMP
);

Diagram

Data types → database operation → result

Key Points

  • Exact type names vary between SQL engines.
Q14Data types

What is the difference between CHAR and VARCHAR?

CHAR is fixed-length in many systems; VARCHAR is variable-length up to a declared limit. Padding and storage behavior differ by engine.

Answer

CHAR is fixed-length in many systems; VARCHAR is variable-length up to a declared limit. Padding and storage behavior differ by engine.

Example: CHAR(2) can suit fixed-width codes; VARCHAR suits names with variable length.

Syntax

Code CHAR(2), Name VARCHAR(100)

Example

Code CHAR(2), Name VARCHAR(100)

Code example

Code CHAR(2), Name VARCHAR(100)

Diagram

Data types → database operation → result

Key Points

  • Check engine-specific collation and trailing-space behavior.
Q15Data types

What is DECIMAL and why use it for money?

DECIMAL/NUMERIC stores exact decimal values within defined precision and scale, making it appropriate for currency calculations where rounding rules matter

Answer

DECIMAL/NUMERIC stores exact decimal values within defined precision and scale, making it appropriate for currency calculations where rounding rules matter.

Example: 12,2 allows up to 12 total digits with 2 fractional digits in systems following this definition.

Syntax

Price DECIMAL(12,2) NOT NULL

Example

Price DECIMAL(12,2) NOT NULL

Code example

Price DECIMAL(12,2) NOT NULL

Diagram

Data types → database operation → result

Key Points

  • Define rounding, currency, and scale rules explicitly.
Q16Keys and constraints

What is a constraint?

A constraint is a database-enforced rule, such as PRIMARY KEY, FOREIGN KEY, UNIQUE, NOT NULL, or CHECK.

Answer

A constraint is a database-enforced rule, such as PRIMARY KEY, FOREIGN KEY, UNIQUE, NOT NULL, or CHECK.

Example: A CHECK constraint can prevent negative prices even if an application bug sends one.

Syntax

CREATE TABLE Product (
  Price DECIMAL(10,2) NOT NULL CHECK (Price >= 0)
);

Example

CREATE TABLE Product ( Price DECIMAL(10,2) NOT NULL CHECK (Price >= 0) );

Code example

CREATE TABLE Product (
  Price DECIMAL(10,2) NOT NULL CHECK (Price >= 0)
);

Diagram

Keys and constraints → database operation → result

Key Points

  • Use constraints to protect data integrity at the database boundary.
Q17Keys and constraints

What is a UNIQUE constraint?

UNIQUE prevents duplicate values for a column or combination of columns, subject to each database's handling of NULLs.

Answer

UNIQUE prevents duplicate values for a column or combination of columns, subject to each database's handling of NULLs.

Example: Unique email can prevent duplicate accounts if that matches product rules.

Diagram / flow: ALTER TABLE Customer ADD CONSTRAINT UQ_Customer_Email UNIQUE (Email);

Syntax

ALTER TABLE Customer ADD CONSTRAINT UQ_Customer_Email UNIQUE (Email);

Example

ALTER TABLE Customer ADD CONSTRAINT UQ_Customer_Email UNIQUE (Email);

Code example

ALTER TABLE Customer ADD CONSTRAINT UQ_Customer_Email UNIQUE (Email);

Diagram

Diagram / flow:
ALTER TABLE Customer ADD CONSTRAINT UQ_Customer_Email UNIQUE (Email);

Key Points

  • NULL uniqueness semantics differ by database.
Q18Keys and constraints

What is a CHECK constraint?

CHECK enforces a Boolean condition on inserted or updated values.

Answer

CHECK enforces a Boolean condition on inserted or updated values.

Example: A quantity column can be constrained to values greater than zero.

Syntax

ALTER TABLE Product ADD CONSTRAINT CK_Product_Price CHECK (Price >= 0);

Example

ALTER TABLE Product ADD CONSTRAINT CK_Product_Price CHECK (Price >= 0);

Code example

ALTER TABLE Product ADD CONSTRAINT CK_Product_Price CHECK (Price >= 0);

Diagram

Keys and constraints → database operation → result

Key Points

  • CHECK constraints may have engine-specific limits on expressions.
Q19Keys and constraints

What is a DEFAULT constraint?

A DEFAULT supplies a value when an INSERT omits the column or requests DEFAULT; it does not generally replace an explicitly supplied NULL.

Answer

A DEFAULT supplies a value when an INSERT omits the column or requests DEFAULT; it does not generally replace an explicitly supplied NULL.

Example: New tasks start as Pending if Status is omitted.

Syntax

CREATE TABLE Task (
  Status VARCHAR(20) NOT NULL DEFAULT 'Pending'
);

Example

CREATE TABLE Task ( Status VARCHAR(20) NOT NULL DEFAULT 'Pending' );

Code example

CREATE TABLE Task (
  Status VARCHAR(20) NOT NULL DEFAULT 'Pending'
);

Diagram

Keys and constraints → database operation → result

Key Points

  • Defaults are not a substitute for validation.
Q20Normalization

What is normalization?

Normalization organizes tables to reduce redundancy and update anomalies by separating facts into appropriate relations.

Answer

Normalization organizes tables to reduce redundancy and update anomalies by separating facts into appropriate relations.

Example: Store customer facts once in Customer rather than repeating them in every order row.

Diagram / flow: Customer → Order → OrderItem ← Product

Syntax

Customer → Order → OrderItem ← Product

Example

Customer → Order → OrderItem ← Product

Code example

Customer → Order → OrderItem ← Product

Diagram

Diagram / flow:
Customer → Order → OrderItem ← Product

Key Points

  • Normalize for correctness first
  • denormalize only for measured needs.
Q21Normalization

What is denormalization?

Denormalization deliberately duplicates or precomputes data to improve specific read patterns, at the cost of additional consistency and update complexity.

Answer

Denormalization deliberately duplicates or precomputes data to improve specific read patterns, at the cost of additional consistency and update complexity.

Example: A cached total can speed reports but must stay consistent with line items.

Diagram / flow: Order.TotalAmount may be stored alongside order lines if maintained reliably.

Syntax

Order.TotalAmount may be stored alongside order lines if maintained reliably.

Example

Order.TotalAmount may be stored alongside order lines if maintained reliably.

Code example

Order.TotalAmount may be stored alongside order lines if maintained reliably.

Diagram

Diagram / flow:
Order.TotalAmount may be stored alongside order lines if maintained reliably.

Key Points

  • Document the source of truth and update strategy.
Q22Data modeling

What is an ER diagram?

An entity-relationship diagram shows entities, attributes, and relationships with cardinality and optionality.

Answer

An entity-relationship diagram shows entities, attributes, and relationships with cardinality and optionality.

Example: One customer can have many orders; each order item references one product.

Diagram / flow: Customer 1 ───< Order 1 ───< OrderItem >─── 1 Product

Syntax

Customer 1 ───< Order 1 ───< OrderItem >─── 1 Product

Example

Customer 1 ───< Order 1 ───< OrderItem >─── 1 Product

Code example

Customer 1 ───< Order 1 ───< OrderItem >─── 1 Product

Diagram

An entity-relationship diagram shows entities, attributes, and relationships with cardinality and optionality.

Key Points

  • ERDs are useful before writing DDL.
Q23Relationships

What is cardinality in a relationship?

Cardinality describes how many records can relate, such as one-to-one, one-to-many, or many-to-many.

Answer

Cardinality describes how many records can relate, such as one-to-one, one-to-many, or many-to-many.

Example: One department may employ many employees, while each employee belongs to one department in this model.

Diagram / flow: Department 1 ───< Employee

Syntax

Department 1 ───< Employee

Example

Department 1 ───< Employee

Code example

Department 1 ───< Employee

Diagram

Diagram / flow:
Department 1 ───< Employee

Key Points

  • Business rules determine cardinality.
Q24Relationships

How do you model a one-to-one relationship?

A one-to-one relationship can be implemented with a foreign key constrained to be unique, or by sharing the same primary key between related tables.

Answer

A one-to-one relationship can be implemented with a foreign key constrained to be unique, or by sharing the same primary key between related tables.

Example: A user can have at most one profile when UserId is the profile primary key.

Syntax

CREATE TABLE UserProfile (
  UserId INT PRIMARY KEY REFERENCES AppUser(UserId),
  Bio VARCHAR(500)
);

Example

CREATE TABLE UserProfile ( UserId INT PRIMARY KEY REFERENCES AppUser(UserId), Bio VARCHAR(500) );

Code example

CREATE TABLE UserProfile (
  UserId INT PRIMARY KEY REFERENCES AppUser(UserId),
  Bio VARCHAR(500)
);

Diagram

Relationships → database operation → result

Key Points

  • Choose optionality based on whether every user must have a profile.
Q25Relationships

How do you model a one-to-many relationship?

Place the foreign key on the many side. Each child row references one parent, and one parent can be referenced by multiple children.

Answer

Place the foreign key on the many side. Each child row references one parent, and one parent can be referenced by multiple children.

Example: Customer is the one side; Orders is the many side.

Diagram / flow: CREATE TABLE Orders ( OrderId INT PRIMARY KEY, CustomerId INT NOT NULL REFERENCES Customer(CustomerId) );

Syntax

CREATE TABLE Orders (
  OrderId INT PRIMARY KEY,
  CustomerId INT NOT NULL REFERENCES Customer(CustomerId)
);

Example

CREATE TABLE Orders ( OrderId INT PRIMARY KEY, CustomerId INT NOT NULL REFERENCES Customer(CustomerId) );

Code example

CREATE TABLE Orders (
  OrderId INT PRIMARY KEY,
  CustomerId INT NOT NULL REFERENCES Customer(CustomerId)
);

Diagram

Diagram / flow:
CREATE TABLE Orders (
  OrderId INT PRIMARY KEY,
  CustomerId INT NOT NULL REFERENCES Customer(CustomerId)
);

Key Points

  • Index foreign keys when query patterns and engine behavior justify it.
Q26Relationships

How do you model a many-to-many relationship?

Create a junction table containing foreign keys to both related tables. Add a composite or surrogate primary key and constraints to prevent invalid duplica

Answer

Create a junction table containing foreign keys to both related tables. Add a composite or surrogate primary key and constraints to prevent invalid duplicates.

Example: A student can take many courses and a course can have many students.

Syntax

CREATE TABLE StudentCourse (
  StudentId INT REFERENCES Student(StudentId),
  CourseId INT REFERENCES Course(CourseId),
  PRIMARY KEY (StudentId, CourseId)
);

Example

CREATE TABLE StudentCourse ( StudentId INT REFERENCES Student(StudentId), CourseId INT REFERENCES Course(CourseId), PRIMARY KEY (StudentId, CourseId) );

Code example

CREATE TABLE StudentCourse (
  StudentId INT REFERENCES Student(StudentId),
  CourseId INT REFERENCES Course(CourseId),
  PRIMARY KEY (StudentId, CourseId)
);

Diagram

Relationships → database operation → result

Key Points

  • Put relationship attributes, such as EnrollmentDate, on the junction table.
Q27Relationships

What is a junction table?

A junction or bridge table resolves a many-to-many relationship and may store attributes of the association itself.

Answer

A junction or bridge table resolves a many-to-many relationship and may store attributes of the association itself.

Example: OrderItem records which products were ordered and the quantity and price at the time.

Diagram / flow: OrderItem(OrderId, ProductId, Quantity, UnitPrice)

Syntax

OrderItem(OrderId, ProductId, Quantity, UnitPrice)

Example

OrderItem(OrderId, ProductId, Quantity, UnitPrice)

Code example

OrderItem(OrderId, ProductId, Quantity, UnitPrice)

Diagram

Diagram / flow:
OrderItem(OrderId, ProductId, Quantity, UnitPrice)

Key Points

  • Historical values like UnitPrice may intentionally differ from the current Product price.
Q28Database organization

What is a schema?

A schema is a namespace or logical container for database objects; exact behavior differs by database engine.

Answer

A schema is a namespace or logical container for database objects; exact behavior differs by database engine.

Example: Tables such as sales.Orders and sales.Customers can be grouped by responsibility.

Syntax

CREATE SCHEMA sales;

Example

CREATE SCHEMA sales;

Code example

CREATE SCHEMA sales;

Diagram

Database organization → database operation → result

Key Points

  • Schema is not always synonymous with database.
Q29Indexes

What is an index?

An index is a data structure that can help locate rows without scanning the entire table, at the cost of storage and write overhead.

Answer

An index is a data structure that can help locate rows without scanning the entire table, at the cost of storage and write overhead.

Example: An index may speed up queries filtering orders by CustomerId.

Diagram / flow: CREATE INDEX IX_Orders_CustomerId ON Orders(CustomerId);

Syntax

CREATE INDEX IX_Orders_CustomerId ON Orders(CustomerId);

Example

CREATE INDEX IX_Orders_CustomerId ON Orders(CustomerId);

Code example

CREATE INDEX IX_Orders_CustomerId ON Orders(CustomerId);

Diagram

Diagram / flow:
CREATE INDEX IX_Orders_CustomerId ON Orders(CustomerId);

Key Points

  • Indexes should be based on workload and execution plans.
Q30Indexes

What is a clustered index?

In SQL Server, a clustered index defines how table rows are organized at the leaf level of the index; a table can have only one clustered index. Other engi

Answer

In SQL Server, a clustered index defines how table rows are organized at the leaf level of the index; a table can have only one clustered index. Other engines use different terminology or storage models.

Example: A clustered key often benefits from stable, frequently used access paths.

Diagram / flow: CREATE CLUSTERED INDEX CX_Order_OrderId ON dbo.Orders(OrderId);

Syntax

CREATE CLUSTERED INDEX CX_Order_OrderId ON dbo.Orders(OrderId);

Example

CREATE CLUSTERED INDEX CX_Order_OrderId ON dbo.Orders(OrderId);

Code example

CREATE CLUSTERED INDEX CX_Order_OrderId ON dbo.Orders(OrderId);

Diagram

Diagram / flow:
CREATE CLUSTERED INDEX CX_Order_OrderId ON dbo.Orders(OrderId);

Key Points

  • Clustered-index semantics are engine-specific.
Q31Indexes

What is a nonclustered index?

In SQL Server, a nonclustered index is a separate index structure that points to table rows or clustered keys. Other engines have their own index implement

Answer

In SQL Server, a nonclustered index is a separate index structure that points to table rows or clustered keys. Other engines have their own index implementations.

Example: An index on Name can help searches or sorts using Name, depending on selectivity and query shape.

Syntax

CREATE INDEX IX_Product_Name ON dbo.Product(Name);

Example

CREATE INDEX IX_Product_Name ON dbo.Product(Name);

Code example

CREATE INDEX IX_Product_Name ON dbo.Product(Name);

Diagram

Indexes → database operation → result

Key Points

  • Too many indexes increase insert, update, delete, and storage costs.
Q32Indexes

What is a composite index?

A composite index contains multiple key columns. Column order matters because the leading columns influence which predicates and ordering can use the index

Answer

A composite index contains multiple key columns. Column order matters because the leading columns influence which predicates and ordering can use the index efficiently.

Example: Useful for queries filtering by CustomerId and then ordering or filtering by OrderDate.

Diagram / flow: CREATE INDEX IX_Order_Customer_Date ON Orders(CustomerId, OrderDate);

Syntax

CREATE INDEX IX_Order_Customer_Date ON Orders(CustomerId, OrderDate);

Example

CREATE INDEX IX_Order_Customer_Date ON Orders(CustomerId, OrderDate);

Code example

CREATE INDEX IX_Order_Customer_Date ON Orders(CustomerId, OrderDate);

Diagram

Diagram / flow:
CREATE INDEX IX_Order_Customer_Date ON Orders(CustomerId, OrderDate);

Key Points

  • Design index order from real query predicates and selectivity.
Q33Indexes

What is a covering index?

A covering index contains the key and included/available columns needed by a query, allowing the database to satisfy it from the index without fetching add

Answer

A covering index contains the key and included/available columns needed by a query, allowing the database to satisfy it from the index without fetching additional row data in some cases.

Example: A category listing query may be served from the index.

Syntax

-- SQL Server example
CREATE INDEX IX_Product_Category ON dbo.Product(CategoryId) INCLUDE (Name, Price);

Example

-- SQL Server example CREATE INDEX IX_Product_Category ON dbo.Product(CategoryId) INCLUDE (Name, Price);

Code example

-- SQL Server example
CREATE INDEX IX_Product_Category ON dbo.Product(CategoryId) INCLUDE (Name, Price);

Diagram

Indexes → database operation → result

Key Points

  • INCLUDE syntax is engine-specific
  • avoid overly wide indexes.
Q34Database objects

What is a view?

A view is a named query that presents data as a virtual table. It can simplify repeated queries and help control which columns users can access.

Answer

A view is a named query that presents data as a virtual table. It can simplify repeated queries and help control which columns users can access.

Example: Applications can query ActiveProducts instead of repeating the filter.

Syntax

CREATE VIEW ActiveProducts AS
SELECT ProductId, Name, Price
FROM Product
WHERE IsActive = 1;

Example

CREATE VIEW ActiveProducts AS SELECT ProductId, Name, Price FROM Product WHERE IsActive = 1;

Code example

CREATE VIEW ActiveProducts AS
SELECT ProductId, Name, Price
FROM Product
WHERE IsActive = 1;

Diagram

Database objects → database operation → result

Key Points

  • A regular view does not necessarily store its result.
Q35Database objects

What is a stored procedure?

A stored procedure is a named database program that can accept parameters and execute SQL statements. Syntax and capabilities vary by engine.

Answer

A stored procedure is a named database program that can accept parameters and execute SQL statements. Syntax and capabilities vary by engine.

Example: Stored procedures can encapsulate repeated database operations and permissions.

Diagram / flow: -- SQL Server example CREATE PROCEDURE dbo.GetOrdersByCustomer @CustomerId INT AS SELECT OrderId, OrderDate FROM dbo.Orders WHERE CustomerId = @CustomerId;

Syntax

-- SQL Server example
CREATE PROCEDURE dbo.GetOrdersByCustomer @CustomerId INT
AS
SELECT OrderId, OrderDate FROM dbo.Orders WHERE CustomerId = @CustomerId;

Example

-- SQL Server example CREATE PROCEDURE dbo.GetOrdersByCustomer @CustomerId INT AS SELECT OrderId, OrderDate FROM dbo.Orders WHERE CustomerId = @CustomerId;

Code example

-- SQL Server example
CREATE PROCEDURE dbo.GetOrdersByCustomer @CustomerId INT
AS
SELECT OrderId, OrderDate FROM dbo.Orders WHERE CustomerId = @CustomerId;

Diagram

Diagram / flow:
-- SQL Server example
CREATE PROCEDURE dbo.GetOrdersByCustomer @CustomerId INT
AS
SELECT OrderId, OrderDate FROM dbo.Orders WHERE CustomerId = @CustomerId;

Key Points

  • Use parameters rather than concatenating input into SQL.
Q36Database objects

What is a trigger?

A trigger runs automatically in response to defined database events such as INSERT, UPDATE, or DELETE. Triggers can enforce specialized rules but can make

Answer

A trigger runs automatically in response to defined database events such as INSERT, UPDATE, or DELETE. Triggers can enforce specialized rules but can make side effects less visible.

Example: A trigger may write an audit record after a product update.

Syntax

-- SQL Server trigger syntax varies by event
CREATE TRIGGER dbo.trg_AuditProduct
ON dbo.Product AFTER UPDATE AS
BEGIN
  SET NOCOUNT ON;
  -- audit logic
END;

Example

-- SQL Server trigger syntax varies by event CREATE TRIGGER dbo.trg_AuditProduct ON dbo.Product AFTER UPDATE AS BEGIN SET NOCOUNT ON; -- audit logic END;

Code example

-- SQL Server trigger syntax varies by event
CREATE TRIGGER dbo.trg_AuditProduct
ON dbo.Product AFTER UPDATE AS
BEGIN
  SET NOCOUNT ON;
  -- audit logic
END;

Diagram

Database objects → database operation → result

Key Points

  • Keep triggers predictable and test multi-row operations.
Q37Transactions

What is a transaction?

A transaction groups database changes into a unit that commits or rolls back together, subject to isolation and engine semantics.

Answer

A transaction groups database changes into a unit that commits or rolls back together, subject to isolation and engine semantics.

Example: A transfer should not debit one account without crediting the other.

Syntax

BEGIN TRANSACTION;
UPDATE Account SET Balance = Balance - 100 WHERE AccountId = 1;
UPDATE Account SET Balance = Balance + 100 WHERE AccountId = 2;
COMMIT;

Example

BEGIN TRANSACTION; UPDATE Account SET Balance = Balance - 100 WHERE AccountId = 1; UPDATE Account SET Balance = Balance + 100 WHERE AccountId = 2; COMMIT;

Code example

BEGIN TRANSACTION;
UPDATE Account SET Balance = Balance - 100 WHERE AccountId = 1;
UPDATE Account SET Balance = Balance + 100 WHERE AccountId = 2;
COMMIT;

Diagram

Transactions → database operation → result

Key Points

  • Use TRY/CATCH and rollback patterns appropriate to your database.
Q38Transactions

What does ACID mean?

ACID means Atomicity, Consistency, Isolation, and Durability. These properties describe key transaction guarantees, with exact guarantees influenced by dat

Answer

ACID means Atomicity, Consistency, Isolation, and Durability. These properties describe key transaction guarantees, with exact guarantees influenced by database configuration and storage.

Example: A committed order should remain durable according to the database's durability configuration.

Diagram / flow: Transaction: BEGIN → statements → COMMIT or ROLLBACK

Syntax

Transaction: BEGIN → statements → COMMIT or ROLLBACK

Example

Transaction: BEGIN → statements → COMMIT or ROLLBACK

Code example

Transaction: BEGIN → statements → COMMIT or ROLLBACK

Diagram

Diagram / flow:
Transaction: BEGIN → statements → COMMIT or ROLLBACK

Key Points

  • ACID does not remove the need for good data modeling.
Q39Transactions

What is a deadlock?

A deadlock occurs when transactions wait on resources held by each other in a cycle. The database usually chooses a victim transaction to roll back.

Answer

A deadlock occurs when transactions wait on resources held by each other in a cycle. The database usually chooses a victim transaction to roll back.

Example: Retry a deadlock victim only when the operation is safe to retry.

Diagram / flow: T1 locks A then waits for B; T2 locks B then waits for A.

Syntax

T1 locks A then waits for B; T2 locks B then waits for A.

Example

T1 locks A then waits for B; T2 locks B then waits for A.

Code example

T1 locks A then waits for B; T2 locks B then waits for A.

Diagram

Diagram / flow:
T1 locks A then waits for B; T2 locks B then waits for A.

Key Points

  • Keep transactions short and acquire resources in a consistent order.
Q40Operations

What is a database backup?

A backup is a recoverable copy of database data and sometimes logs or metadata. Backup frequency and type determine recovery options and data-loss exposure

Answer

A backup is a recoverable copy of database data and sometimes logs or metadata. Backup frequency and type determine recovery options and data-loss exposure.

Example: Test restoring backups, not just creating them.

Syntax

Full backup + differential/log backups where supported

Example

Full backup + differential/log backups where supported

Code example

Full backup + differential/log backups where supported

Diagram

Operations → database operation → result

Key Points

  • RPO and RTO should guide backup and recovery design.
Q101Joins

How do INNER JOIN and LEFT JOIN differ?

INNER JOIN returns only rows with matching keys on both sides. LEFT JOIN returns every row from the left table and matching right-side rows, usin

Answer

INNER JOIN returns only rows with matching keys on both sides. LEFT JOIN returns every row from the left table and matching right-side rows, using NULL where no match exists.

Example: SELECT c.CustomerId, o.OrderId FROM Customers c LEFT JOIN Orders o ON o.CustomerId = c.CustomerId;

Diagram / flow: Customers LEFT JOIN Orders → every customer remains; unmatched orders are NULL.

Syntax

SELECT c.CustomerId, o.OrderId FROM Customers c LEFT JOIN Orders o ON o.CustomerId = c.CustomerId;

Example

SELECT c.CustomerId, o.OrderId FROM Customers c LEFT JOIN Orders o ON o.CustomerId = c.CustomerId;

Code example

SELECT c.CustomerId, c.Name, o.OrderId
FROM Customers AS c
LEFT JOIN Orders AS o ON o.CustomerId = c.CustomerId;

Diagram

Customers LEFT JOIN Orders → every customer remains; unmatched orders are NULL.

Key Points

  • INNER JOIN returns only rows with matching keys on both sides.
  • Check execution plans and database-engine-specific behavior.
  • Test with representative data and concurrent workloads where relevant.
Q103Aggregations

What is the difference between WHERE and HAVING?

WHERE filters rows before grouping; HAVING filters groups after aggregation. Use WHERE for row predicates when possible to reduce the rows enteri

Answer

WHERE filters rows before grouping; HAVING filters groups after aggregation. Use WHERE for row predicates when possible to reduce the rows entering aggregation.

Example: SELECT DepartmentId, COUNT(*) FROM Employees GROUP BY DepartmentId HAVING COUNT(*) > 5;

Diagram / flow: Rows → WHERE → GROUP BY/aggregate → HAVING → result groups.

Syntax

SELECT DepartmentId, COUNT(*) FROM Employees GROUP BY DepartmentId HAVING COUNT(*) > 5;

Example

SELECT DepartmentId, COUNT(*) FROM Employees GROUP BY DepartmentId HAVING COUNT(*) > 5;

Code example

SELECT DepartmentId, COUNT(*) AS EmployeeCount
FROM Employees
WHERE IsActive = 1
GROUP BY DepartmentId
HAVING COUNT(*) > 5;

Diagram

Rows → WHERE → GROUP BY/aggregate → HAVING → result groups.

Key Points

  • WHERE filters rows before grouping; HAVING filters groups after aggregation.
  • Check execution plans and database-engine-specific behavior.
  • Test with representative data and concurrent workloads where relevant.
Q114Transactions

Explain ACID transaction properties.

Atomicity means all-or-nothing; consistency preserves declared rules; isolation controls concurrent transaction interference; durability means co

Answer

Atomicity means all-or-nothing; consistency preserves declared rules; isolation controls concurrent transaction interference; durability means committed changes survive failures according to the database's guarantees.

Example: BEGIN TRANSACTION; ... COMMIT; / ROLLBACK;

Diagram / flow: Transaction starts → operations execute → commit all changes or rollback the unit.

Syntax

BEGIN TRANSACTION; ... COMMIT; / ROLLBACK;

Example

BEGIN TRANSACTION; ... COMMIT; / ROLLBACK;

Code example

BEGIN TRANSACTION;
UPDATE Inventory SET Quantity = Quantity - 1 WHERE ProductId = 7;
INSERT INTO OrderLines(OrderId, ProductId, Quantity) VALUES (1001, 7, 1);
COMMIT;

Diagram

Transaction starts → operations execute → commit all changes or rollback the unit.

Key Points

  • Atomicity means all-or-nothing; consistency preserves declared rules; isolation controls concurrent transaction interference; durability means committed changes survive failures according to the database's guarantees.
  • Check execution plans and database-engine-specific behavior.
  • Test with representative data and concurrent workloads where relevant.

Intermediate Questions

Implementation details, practical patterns, and common workflows.

Q41Normalization forms

What is normalization to 1NF?

First Normal Form (1NF) generally requires each column value to be atomic for the chosen model and no repeating groups in a row.

Answer

First Normal Form (1NF) generally requires each column value to be atomic for the chosen model and no repeating groups in a row.

Example: A separate row per order item supports constraints and joins.

Diagram / flow: Bad: ProductIds = '1,2,3' in Order Better: OrderItem rows for each product

Syntax

Bad: ProductIds = '1,2,3' in Order
Better: OrderItem rows for each product

Example

Bad: ProductIds = '1,2,3' in Order Better: OrderItem rows for each product

Code example

Bad: ProductIds = '1,2,3' in Order
Better: OrderItem rows for each product

Diagram

Diagram / flow:
Bad: ProductIds = '1,2,3' in Order
Better: OrderItem rows for each product

Key Points

  • Atomicity depends on the domain
  • avoid packing relational values into delimited strings.
Q42Normalization forms

What is 2NF?

Second Normal Form requires 1NF and no non-key attribute to depend on only part of a candidate key. It matters particularly with composite keys.

Answer

Second Normal Form requires 1NF and no non-key attribute to depend on only part of a candidate key. It matters particularly with composite keys.

Example: Move ProductName to Product when it describes the product rather than the order line.

Diagram / flow: OrderItem(OrderId, ProductId, ProductName, Quantity) is suspect if ProductName depends only on ProductId.

Syntax

OrderItem(OrderId, ProductId, ProductName, Quantity) is suspect if ProductName depends only on ProductId.

Example

OrderItem(OrderId, ProductId, ProductName, Quantity) is suspect if ProductName depends only on ProductId.

Code example

OrderItem(OrderId, ProductId, ProductName, Quantity) is suspect if ProductName depends only on ProductId.

Diagram

Diagram / flow:
OrderItem(OrderId, ProductId, ProductName, Quantity) is suspect if ProductName depends only on ProductId.

Key Points

  • Check functional dependencies, not just table appearance.
Q43Normalization forms

What is 3NF?

Third Normal Form requires 2NF and removes problematic transitive dependencies of non-key attributes on a key, according to formal definitions.

Answer

Third Normal Form requires 2NF and removes problematic transitive dependencies of non-key attributes on a key, according to formal definitions.

Example: Store DepartmentName once in Department if it is determined by DepartmentId.

Diagram / flow: Employee(EmployeeId, DepartmentId, DepartmentName) → separate Department(DepartmentId, DepartmentName)

Syntax

Employee(EmployeeId, DepartmentId, DepartmentName) → separate Department(DepartmentId, DepartmentName)

Example

Employee(EmployeeId, DepartmentId, DepartmentName) → separate Department(DepartmentId, DepartmentName)

Code example

Employee(EmployeeId, DepartmentId, DepartmentName) → separate Department(DepartmentId, DepartmentName)

Diagram

Diagram / flow:
Employee(EmployeeId, DepartmentId, DepartmentName) → separate Department(DepartmentId, DepartmentName)

Key Points

  • Normalization reduces update anomalies and duplicated facts.
Q44Normalization forms

What is BCNF?

Boyce-Codd Normal Form requires every determinant of a nontrivial functional dependency to be a candidate key. It is stricter than 3NF in certain cases.

Answer

Boyce-Codd Normal Form requires every determinant of a nontrivial functional dependency to be a candidate key. It is stricter than 3NF in certain cases.

Example: BCNF can remove anomalies that remain in some 3NF schemas.

Diagram / flow: If Instructor → Room but Instructor is not a candidate key, inspect the relation's dependencies.

Syntax

If Instructor → Room but Instructor is not a candidate key, inspect the relation's dependencies.

Example

If Instructor → Room but Instructor is not a candidate key, inspect the relation's dependencies.

Code example

If Instructor → Room but Instructor is not a candidate key, inspect the relation's dependencies.

Diagram

Diagram / flow:
If Instructor → Room but Instructor is not a candidate key, inspect the relation's dependencies.

Key Points

  • Apply formal functional-dependency reasoning
  • not every schema needs a textbook decomposition.
Q45Normalization forms

What is a functional dependency?

A functional dependency X → Y means each value of X determines exactly one value of Y within the modeled relation.

Answer

A functional dependency X → Y means each value of X determines exactly one value of Y within the modeled relation.

Example: If CustomerId uniquely identifies a customer, it determines the customer's name in that model.

Diagram / flow: CustomerId → CustomerName

Syntax

CustomerId → CustomerName

Example

CustomerId → CustomerName

Code example

CustomerId → CustomerName

Diagram

A functional dependency X → Y means each value of X determines exactly one value of Y within the modeled relation.

Key Points

  • Functional dependencies express business facts and guide normalization.
Q46Normalization and anomalies

How do you identify update, insert, and delete anomalies?

Anomalies occur when unrelated facts are stored together redundantly. Updating duplicated data inconsistently, being unable to insert a fact alone, or dele

Answer

Anomalies occur when unrelated facts are stored together redundantly. Updating duplicated data inconsistently, being unable to insert a fact alone, or deleting one fact accidentally removing another are common examples.

Example: Separating customer, product, order, and order-line facts reduces these risks.

Diagram / flow: Store ProductName once in Product instead of repeating it in every OrderItem.

Syntax

Store ProductName once in Product instead of repeating it in every OrderItem.

Example

Store ProductName once in Product instead of repeating it in every OrderItem.

Code example

Store ProductName once in Product instead of repeating it in every OrderItem.

Diagram

Diagram / flow:
Store ProductName once in Product instead of repeating it in every OrderItem.

Key Points

  • Anomalies often indicate a poor table boundary.
Q47Keys and constraints

How do you choose a primary key?

Choose a key that is unique, non-null, stable, and practical for references. Compare natural and surrogate candidates based on business semantics, size, an

Answer

Choose a key that is unique, non-null, stable, and practical for references. Compare natural and surrogate candidates based on business semantics, size, and change risk.

Example: A generated ID may be preferable to an email address that can change.

Diagram / flow: CustomerId BIGINT PRIMARY KEY

Syntax

CustomerId BIGINT PRIMARY KEY

Example

CustomerId BIGINT PRIMARY KEY

Code example

CustomerId BIGINT PRIMARY KEY

Diagram

Diagram / flow:
CustomerId BIGINT PRIMARY KEY

Key Points

  • Still enforce natural uniqueness when the business requires it.
Q48Keys and constraints

Should every table have an identity column?

No. A surrogate identity is common but not mandatory. Junction tables may use a composite primary key; lookup tables may use stable natural codes. The desi

Answer

No. A surrogate identity is common but not mandatory. Junction tables may use a composite primary key; lookup tables may use stable natural codes. The design should enforce real uniqueness rules.

Example: Use a surrogate key when it simplifies references or lifecycle management, but retain unique constraints for business keys.

Syntax

PRIMARY KEY (StudentId, CourseId)

Example

PRIMARY KEY (StudentId, CourseId)

Code example

PRIMARY KEY (StudentId, CourseId)

Diagram

Keys and constraints → database operation → result

Key Points

  • An identity column does not automatically prevent duplicate business records.
Q49Relationships

How do you model optional relationships?

An optional relationship commonly uses a nullable foreign key. A required relationship uses NOT NULL plus a foreign key.

Answer

An optional relationship commonly uses a nullable foreign key. A required relationship uses NOT NULL plus a foreign key.

Example: An employee may have no manager if ManagerId is NULL.

Syntax

ManagerId INT NULL REFERENCES Employee(EmployeeId)

Example

ManagerId INT NULL REFERENCES Employee(EmployeeId)

Code example

ManagerId INT NULL REFERENCES Employee(EmployeeId)

Diagram

Relationships → database operation → result

Key Points

  • Optionality should be explicit in both schema and API validation.
Q50Historical data

How do you model historical prices for order items?

Store the agreed unit price on the order line as a snapshot. The current product price may change later and should not rewrite past transactions.

Answer

Store the agreed unit price on the order line as a snapshot. The current product price may change later and should not rewrite past transactions.

Example: An item bought for $10 remains recorded as $10 even if the catalog price becomes $12.

Diagram / flow: OrderItem(OrderId, ProductId, Quantity, UnitPrice DECIMAL(12,2))

Syntax

OrderItem(OrderId, ProductId, Quantity, UnitPrice DECIMAL(12,2))

Example

OrderItem(OrderId, ProductId, Quantity, UnitPrice DECIMAL(12,2))

Code example

OrderItem(OrderId, ProductId, Quantity, UnitPrice DECIMAL(12,2))

Diagram

Diagram / flow:
OrderItem(OrderId, ProductId, Quantity, UnitPrice DECIMAL(12,2))

Key Points

  • Decide whether discounts, tax, currency, and product description also need snapshots.
Q51Data modeling patterns

How do you model addresses for customers?

If customers can have multiple addresses, use a CustomerAddress table with an address type and a foreign key. Avoid many numbered address columns when the

Answer

If customers can have multiple addresses, use a CustomerAddress table with an address type and a foreign key. Avoid many numbered address columns when the number can vary.

Example: A customer may have billing and several shipping addresses.

Diagram / flow: Customer 1 ───< CustomerAddress CustomerAddress(CustomerAddressId, CustomerId, Type, Line1, City, PostalCode)

Syntax

Customer 1 ───< CustomerAddress
CustomerAddress(CustomerAddressId, CustomerId, Type, Line1, City, PostalCode)

Example

Customer 1 ───< CustomerAddress CustomerAddress(CustomerAddressId, CustomerId, Type, Line1, City, PostalCode)

Code example

Customer 1 ───< CustomerAddress
CustomerAddress(CustomerAddressId, CustomerId, Type, Line1, City, PostalCode)

Diagram

Diagram / flow:
Customer 1 ───< CustomerAddress
CustomerAddress(CustomerAddressId, CustomerId, Type, Line1, City, PostalCode)

Key Points

  • Enforce one default address per type if required, using engine-appropriate constraints.
Q52Lifecycle and audit

How do you model soft deletes?

A soft delete marks a row as inactive or deleted rather than physically removing it. Queries must consistently filter deleted rows, and uniqueness rules ne

Answer

A soft delete marks a row as inactive or deleted rather than physically removing it. Queries must consistently filter deleted rows, and uniqueness rules need to account for deleted records.

Example: Soft deletion can preserve history or enable recovery.

Syntax

IsDeleted BOOLEAN NOT NULL DEFAULT FALSE
-- Query: WHERE IsDeleted = FALSE

Example

IsDeleted BOOLEAN NOT NULL DEFAULT FALSE -- Query: WHERE IsDeleted = FALSE

Code example

IsDeleted BOOLEAN NOT NULL DEFAULT FALSE
-- Query: WHERE IsDeleted = FALSE

Diagram

Lifecycle and audit → database operation → result

Key Points

  • Plan retention, privacy deletion, and index/unique-key semantics.
Q53Historical data

What is a temporal table?

A temporal table stores row history over time in supported database engines, allowing queries of past versions. Implementations and syntax differ by engine

Answer

A temporal table stores row history over time in supported database engines, allowing queries of past versions. Implementations and syntax differ by engine.

Example: Temporal history can support auditing and point-in-time row analysis.

Syntax

-- SQL Server example
CREATE TABLE dbo.EmployeeHistory (...,
  ValidFrom datetime2 GENERATED ALWAYS AS ROW START,
  ValidTo datetime2 GENERATED ALWAYS AS ROW END,
  PERIOD FOR SYSTEM_TIME (ValidFrom, ValidTo)
) WITH (SYSTEM_VERSIONING = ON (HISTORY_TABLE = dbo.EmployeeHistoryArchive));

Example

-- SQL Server example CREATE TABLE dbo.EmployeeHistory (..., ValidFrom datetime2 GENERATED ALWAYS AS ROW START, ValidTo datetime2 GENERATED ALWAYS AS ROW END, PERIOD FOR SYSTEM_TIME (ValidFrom, ValidTo) ) WITH (SYSTEM_VERSIONING = ON (HISTORY_TABLE = dbo.EmployeeHistoryArchive));

Code example

-- SQL Server example
CREATE TABLE dbo.EmployeeHistory (...,
  ValidFrom datetime2 GENERATED ALWAYS AS ROW START,
  ValidTo datetime2 GENERATED ALWAYS AS ROW END,
  PERIOD FOR SYSTEM_TIME (ValidFrom, ValidTo)
) WITH (SYSTEM_VERSIONING = ON (HISTORY_TABLE = dbo.EmployeeHistoryArchive));

Diagram

Historical data → database operation → result

Key Points

  • It is not a replacement for every domain event or audit requirement.
Q54Analytics modeling

What is a slowly changing dimension?

In data warehousing, a slowly changing dimension (SCD) strategy manages attribute changes over time. Type 1 overwrites; Type 2 adds a new version row with

Answer

In data warehousing, a slowly changing dimension (SCD) strategy manages attribute changes over time. Type 1 overwrites; Type 2 adds a new version row with effective dates or current flags.

Example: Type 2 can preserve a customer's historical city for historical reporting.

Diagram / flow: CustomerDimension(CustomerKey, CustomerId, City, StartDate, EndDate, IsCurrent)

Syntax

CustomerDimension(CustomerKey, CustomerId, City, StartDate, EndDate, IsCurrent)

Example

CustomerDimension(CustomerKey, CustomerId, City, StartDate, EndDate, IsCurrent)

Code example

CustomerDimension(CustomerKey, CustomerId, City, StartDate, EndDate, IsCurrent)

Diagram

Diagram / flow:
CustomerDimension(CustomerKey, CustomerId, City, StartDate, EndDate, IsCurrent)

Key Points

  • Choose the type based on whether reports need historical attribute values.
Q55Analytics modeling

What is a star schema?

A star schema has a central fact table connected to denormalized dimension tables. It is common in analytical warehouses for understandable, performant rep

Answer

A star schema has a central fact table connected to denormalized dimension tables. It is common in analytical warehouses for understandable, performant reporting.

Example: FactSales may contain measures such as quantity and sales amount, with keys to dimensions.

Diagram / flow: DimDate | DimProduct — FactSales — DimCustomer | DimStore

Syntax

       DimDate
          |
DimProduct — FactSales — DimCustomer
          |
       DimStore

Example

DimDate | DimProduct — FactSales — DimCustomer | DimStore

Code example

       DimDate
          |
DimProduct — FactSales — DimCustomer
          |
       DimStore

Diagram

Diagram / flow:
       DimDate
          |
DimProduct — FactSales — DimCustomer
          |
       DimStore

Key Points

  • Fact grain must be clearly defined.
Q56Analytics modeling

What is the grain of a fact table?

Grain states exactly what one row represents, such as one product per order line or one daily total per store. Keys and measures should align with that gra

Answer

Grain states exactly what one row represents, such as one product per order line or one daily total per store. Keys and measures should align with that grain.

Example: A clear grain prevents double counting when dimensions are joined.

Syntax

FactSales grain: one row per order line

Example

FactSales grain: one row per order line

Code example

FactSales grain: one row per order line

Diagram

Analytics modeling → database operation → result

Key Points

  • Declare grain before choosing fact table columns.
Q57Workload modeling

What is OLTP versus OLAP?

OLTP systems support frequent transactional reads and writes with integrity constraints. OLAP systems support analytical queries over large volumes, often

Answer

OLTP systems support frequent transactional reads and writes with integrity constraints. OLAP systems support analytical queries over large volumes, often with dimensional models and aggregates.

Example: A transactional order database and a reporting warehouse may have different schema priorities.

Diagram / flow: OLTP order write → ETL/ELT → warehouse star schema → analytics

Syntax

OLTP order write → ETL/ELT → warehouse star schema → analytics

Example

OLTP order write → ETL/ELT → warehouse star schema → analytics

Code example

OLTP order write → ETL/ELT → warehouse star schema → analytics

Diagram

Diagram / flow:
OLTP order write → ETL/ELT → warehouse star schema → analytics

Key Points

  • Avoid running heavy reports on a production OLTP system without evaluating impact.
Q58Analytics modeling

What is a surrogate dimension key in a warehouse?

A warehouse surrogate key identifies a dimension row independently of the source-system business key. It supports multiple source systems and Type 2 histor

Answer

A warehouse surrogate key identifies a dimension row independently of the source-system business key. It supports multiple source systems and Type 2 history.

Example: A customer may have several dimension versions with different CustomerKey values.

Diagram / flow: CustomerKey (warehouse PK), CustomerId (source business ID)

Syntax

CustomerKey (warehouse PK), CustomerId (source business ID)

Example

CustomerKey (warehouse PK), CustomerId (source business ID)

Code example

CustomerKey (warehouse PK), CustomerId (source business ID)

Diagram

Diagram / flow:
CustomerKey (warehouse PK), CustomerId (source business ID)

Key Points

  • Keep source identifiers for lineage and reconciliation.
Q59Physical design

How do you choose between normalized and denormalized schemas?

Normalize transactional data to protect consistency and reduce duplication; denormalize selected read models when measurements show a performance or usabil

Answer

Normalize transactional data to protect consistency and reduce duplication; denormalize selected read models when measurements show a performance or usability need.

Example: A reporting table may pre-aggregate monthly sales for frequent dashboards.

Diagram / flow: Normalized write model → materialized/reporting projection

Syntax

Normalized write model → materialized/reporting projection

Example

Normalized write model → materialized/reporting projection

Code example

Normalized write model → materialized/reporting projection

Diagram

Diagram / flow:
Normalized write model → materialized/reporting projection

Key Points

  • Document refresh, ownership, and staleness of derived data.
Q60Physical design

How do you choose data types for identifiers?

Use integer types for compact sequential identifiers when appropriate, or UUID/GUID values for distributed generation and other requirements. Consider inde

Answer

Use integer types for compact sequential identifiers when appropriate, or UUID/GUID values for distributed generation and other requirements. Consider index size, locality, exposure, and integration needs.

Example: Sequential numeric IDs often have compact indexes; random UUIDs can increase index fragmentation in some engines.

Syntax

ProductId BIGINT PRIMARY KEY

Example

ProductId BIGINT PRIMARY KEY

Code example

ProductId BIGINT PRIMARY KEY

Diagram

Physical design → database operation → result

Key Points

  • Never use a key type solely because it is fashionable.
Q61Keys and constraints

When should you use a UUID/GUID primary key?

UUIDs can be generated across services without a central allocator and can reduce exposure of sequential counts. They are wider than integer keys and their

Answer

UUIDs can be generated across services without a central allocator and can reduce exposure of sequential counts. They are wider than integer keys and their index behavior depends on generation strategy and engine.

Example: A distributed import process can generate identifiers before connecting to the central database.

Syntax

ProductId UUID PRIMARY KEY

Example

ProductId UUID PRIMARY KEY

Code example

ProductId UUID PRIMARY KEY

Diagram

Keys and constraints → database operation → result

Key Points

  • Consider time-ordered UUID variants or sequential strategies when supported and appropriate.
Q62Data integrity

What is a check constraint versus application validation?

Application validation provides friendly feedback and domain-specific rules; database constraints protect data from all writers, including scripts and othe

Answer

Application validation provides friendly feedback and domain-specific rules; database constraints protect data from all writers, including scripts and other services. Important invariants may need both.

Example: The UI can show a message while the database rejects invalid quantities from any client.

Syntax

CHECK (Quantity > 0)

Example

CHECK (Quantity > 0)

Code example

CHECK (Quantity > 0)

Diagram

Data integrity → database operation → result

Key Points

  • Constraints cannot easily express every cross-row or external business rule.
Q63Lifecycle and audit

How do cascading deletes differ from soft deletes?

Cascading deletes physically remove dependent rows according to FK rules. Soft deletes mark rows as deleted and require consistent filtering and retention

Answer

Cascading deletes physically remove dependent rows according to FK rules. Soft deletes mark rows as deleted and require consistent filtering and retention policies.

Example: Use physical cascade for dependent ephemeral rows; use soft delete when retention or restore is needed.

Syntax

ON DELETE CASCADE vs IsDeleted = TRUE

Example

ON DELETE CASCADE vs IsDeleted = TRUE

Code example

ON DELETE CASCADE vs IsDeleted = TRUE

Diagram

Lifecycle and audit → database operation → result

Key Points

  • Review legal, audit, and privacy obligations before choosing.
Q64Auditability

How do you design audit columns?

Common audit fields include CreatedAt, CreatedBy, UpdatedAt, and UpdatedBy. Define UTC handling, trusted identity source, and whether history must be retai

Answer

Common audit fields include CreatedAt, CreatedBy, UpdatedAt, and UpdatedBy. Define UTC handling, trusted identity source, and whether history must be retained separately.

Example: An update can set UpdatedAt and UpdatedBy from trusted server-side context.

Syntax

CreatedAt TIMESTAMP NOT NULL
UpdatedAt TIMESTAMP NULL

Example

CreatedAt TIMESTAMP NOT NULL UpdatedAt TIMESTAMP NULL

Code example

CreatedAt TIMESTAMP NOT NULL
UpdatedAt TIMESTAMP NULL

Diagram

Auditability → database operation → result

Key Points

  • Audit columns show latest metadata, not a full history of every change.
Q65Concurrency design

What is optimistic concurrency?

Optimistic concurrency allows concurrent reads but detects conflicting writes using a version column or concurrency token. The application then rejects, me

Answer

Optimistic concurrency allows concurrent reads but detects conflicting writes using a version column or concurrency token. The application then rejects, merges, or retries the change.

Example: Zero affected rows can indicate that another transaction changed the record.

Syntax

UPDATE Product SET Price = @price, Version = Version + 1 WHERE ProductId = @id AND Version = @oldVersion

Example

UPDATE Product SET Price = @price, Version = Version + 1 WHERE ProductId = @id AND Version = @oldVersion

Code example

UPDATE Product SET Price = @price, Version = Version + 1 WHERE ProductId = @id AND Version = @oldVersion

Diagram

Concurrency design → database operation → result

Key Points

  • Make conflict handling visible to callers.
Q66Concurrency design

What is pessimistic locking?

Pessimistic locking locks rows or ranges to prevent conflicting operations while a transaction runs. It can be appropriate for highly contended operations

Answer

Pessimistic locking locks rows or ranges to prevent conflicting operations while a transaction runs. It can be appropriate for highly contended operations but may reduce concurrency or cause deadlocks.

Example: A stock reservation might lock a row while checking and updating quantity.

Syntax

-- SQL Server example
SELECT * FROM dbo.Inventory WITH (UPDLOCK, ROWLOCK) WHERE ProductId = @id;

Example

-- SQL Server example SELECT * FROM dbo.Inventory WITH (UPDLOCK, ROWLOCK) WHERE ProductId = @id;

Code example

-- SQL Server example
SELECT * FROM dbo.Inventory WITH (UPDLOCK, ROWLOCK) WHERE ProductId = @id;

Diagram

Concurrency design → database operation → result

Key Points

  • Lock hints are engine-specific
  • keep lock duration short.
Q67Concurrency design

What is transaction isolation level?

Isolation level controls how concurrent transactions observe changes and which anomalies are prevented. Common levels include Read Uncommitted, Read Commit

Answer

Isolation level controls how concurrent transactions observe changes and which anomalies are prevented. Common levels include Read Uncommitted, Read Committed, Repeatable Read, Serializable, and Snapshot where supported.

Example: Stronger isolation can reduce anomalies but may increase blocking or conflict retries.

Syntax

SET TRANSACTION ISOLATION LEVEL READ COMMITTED;

Example

SET TRANSACTION ISOLATION LEVEL READ COMMITTED;

Code example

SET TRANSACTION ISOLATION LEVEL READ COMMITTED;

Diagram

Concurrency design → database operation → result

Key Points

  • Understand your engine's default and snapshot behavior.
Q68Concurrency design

What is a dirty read?

A dirty read occurs when a transaction reads data written by another transaction that has not committed and may later roll back.

Answer

A dirty read occurs when a transaction reads data written by another transaction that has not committed and may later roll back.

Example: Avoid dirty reads for financial or correctness-sensitive data.

Diagram / flow: T1: UPDATE balance; (uncommitted) T2: reads changed balance T1: ROLLBACK

Syntax

T1: UPDATE balance; (uncommitted)
T2: reads changed balance
T1: ROLLBACK

Example

T1: UPDATE balance; (uncommitted) T2: reads changed balance T1: ROLLBACK

Code example

T1: UPDATE balance; (uncommitted)
T2: reads changed balance
T1: ROLLBACK

Diagram

Diagram / flow:
T1: UPDATE balance; (uncommitted)
T2: reads changed balance
T1: ROLLBACK

Key Points

  • READ UNCOMMITTED permits dirty reads in many systems.
Q69Concurrency design

What is a non-repeatable read?

A non-repeatable read occurs when a transaction reads the same row twice and sees different committed values because another transaction updated it between

Answer

A non-repeatable read occurs when a transaction reads the same row twice and sees different committed values because another transaction updated it between reads.

Example: Isolation choices determine whether repeated reads are protected.

Diagram / flow: T1 reads Price=10; T2 commits Price=12; T1 reads Price=12.

Syntax

T1 reads Price=10; T2 commits Price=12; T1 reads Price=12.

Example

T1 reads Price=10; T2 commits Price=12; T1 reads Price=12.

Code example

T1 reads Price=10; T2 commits Price=12; T1 reads Price=12.

Diagram

Diagram / flow:
T1 reads Price=10; T2 commits Price=12; T1 reads Price=12.

Key Points

  • Do not confuse it with a phantom row.
Q70Concurrency design

What is a phantom read?

A phantom read occurs when repeating a predicate query returns a different set of rows because another transaction inserted or deleted matching rows.

Answer

A phantom read occurs when repeating a predicate query returns a different set of rows because another transaction inserted or deleted matching rows.

Example: Serializable isolation or suitable range protection can prevent phantoms, depending on the engine.

Diagram / flow: T1: SELECT * WHERE Price > 100 T2 inserts matching product and commits T1 repeats query

Syntax

T1: SELECT * WHERE Price > 100
T2 inserts matching product and commits
T1 repeats query

Example

T1: SELECT * WHERE Price > 100 T2 inserts matching product and commits T1 repeats query

Code example

T1: SELECT * WHERE Price > 100
T2 inserts matching product and commits
T1 repeats query

Diagram

Diagram / flow:
T1: SELECT * WHERE Price > 100
T2 inserts matching product and commits
T1 repeats query

Key Points

  • Snapshot isolation semantics differ from serializable semantics.
Q71Query performance

What is an execution plan?

An execution plan describes how the database intends to execute a query, including scans, seeks, joins, sorts, and estimated or actual row counts.

Answer

An execution plan describes how the database intends to execute a query, including scans, seeks, joins, sorts, and estimated or actual row counts.

Example: Compare estimated and actual row counts to find bad assumptions.

Diagram / flow: EXPLAIN SELECT * FROM Orders WHERE CustomerId = 10;

Syntax

EXPLAIN SELECT * FROM Orders WHERE CustomerId = 10;

Example

EXPLAIN SELECT * FROM Orders WHERE CustomerId = 10;

Code example

EXPLAIN SELECT * FROM Orders WHERE CustomerId = 10;

Diagram

Diagram / flow:
EXPLAIN SELECT * FROM Orders WHERE CustomerId = 10;

Key Points

  • EXPLAIN syntax and available detail differ by engine.
Q72Index design

How do you decide which columns to index?

Start with frequent and slow queries, predicates, joins, sorting, and grouping. Consider selectivity, key order, included columns, write volume, and index

Answer

Start with frequent and slow queries, predicates, joins, sorting, and grouping. Consider selectivity, key order, included columns, write volume, and index maintenance cost.

Example: A query filtering by Status and sorting by OrderDate may benefit from a matching index.

Diagram / flow: CREATE INDEX IX_Order_Status_Date ON Orders(Status, OrderDate);

Syntax

CREATE INDEX IX_Order_Status_Date ON Orders(Status, OrderDate);

Example

CREATE INDEX IX_Order_Status_Date ON Orders(Status, OrderDate);

Code example

CREATE INDEX IX_Order_Status_Date ON Orders(Status, OrderDate);

Diagram

Diagram / flow:
CREATE INDEX IX_Order_Status_Date ON Orders(Status, OrderDate);

Key Points

  • Validate using actual plans and representative data.
Q73Index design

Why can too many indexes hurt performance?

Each index consumes storage and must be maintained when rows are inserted, updated, or deleted. Unused or overlapping indexes increase cost and complicate

Answer

Each index consumes storage and must be maintained when rows are inserted, updated, or deleted. Unused or overlapping indexes increase cost and complicate optimization.

Example: Drop redundant indexes only after checking constraints and workload usage.

Syntax

Review index usage and write workload before adding another index.

Example

Review index usage and write workload before adding another index.

Code example

Review index usage and write workload before adding another index.

Diagram

Index design → database operation → result

Key Points

  • Some indexes exist to enforce uniqueness or support foreign keys.
Q74Query performance

What is a sargable predicate?

A sargable predicate can use an index search efficiently. Applying a function or conversion to an indexed column may prevent an efficient seek, depending o

Answer

A sargable predicate can use an index search efficiently. Applying a function or conversion to an indexed column may prevent an efficient seek, depending on the optimizer and expression.

Example: Use range predicates with matching types when appropriate.

Diagram / flow: Less sargable: WHERE YEAR(OrderDate) = 2025 Often better: WHERE OrderDate >= '2025-01-01' AND OrderDate < '2026-01-01'

Syntax

Less sargable: WHERE YEAR(OrderDate) = 2025
Often better: WHERE OrderDate >= '2025-01-01' AND OrderDate < '2026-01-01'

Example

Less sargable: WHERE YEAR(OrderDate) = 2025 Often better: WHERE OrderDate >= '2025-01-01' AND OrderDate < '2026-01-01'

Code example

Less sargable: WHERE YEAR(OrderDate) = 2025
Often better: WHERE OrderDate >= '2025-01-01' AND OrderDate < '2026-01-01'

Diagram

Diagram / flow:
Less sargable: WHERE YEAR(OrderDate) = 2025
Often better: WHERE OrderDate >= '2025-01-01' AND OrderDate < '2026-01-01'

Key Points

  • Always verify the actual plan
  • optimizers can transform some expressions.
Q75Index design

What is a covering index and when is it useful?

A covering index contains all columns required by a query, potentially avoiding extra row lookups. It is useful for high-frequency read paths when the addi

Answer

A covering index contains all columns required by a query, potentially avoiding extra row lookups. It is useful for high-frequency read paths when the additional index size is justified.

Example: A customer order-history endpoint may benefit from this index.

Diagram / flow: CREATE INDEX IX_Order_Customer ON Orders(CustomerId) INCLUDE (OrderDate, Total);

Syntax

CREATE INDEX IX_Order_Customer ON Orders(CustomerId) INCLUDE (OrderDate, Total);

Example

CREATE INDEX IX_Order_Customer ON Orders(CustomerId) INCLUDE (OrderDate, Total);

Code example

CREATE INDEX IX_Order_Customer ON Orders(CustomerId) INCLUDE (OrderDate, Total);

Diagram

Diagram / flow:
CREATE INDEX IX_Order_Customer ON Orders(CustomerId) INCLUDE (OrderDate, Total);

Key Points

  • Included-column syntax varies by engine.
Q102Joins

When would you use a FULL OUTER JOIN?

A FULL OUTER JOIN returns matched rows plus unmatched rows from both inputs. It is useful for reconciliation, such as comparing two exports; supp

Answer

A FULL OUTER JOIN returns matched rows plus unmatched rows from both inputs. It is useful for reconciliation, such as comparing two exports; support varies by database engine.

Example: SELECT ... FROM A FULL OUTER JOIN B ON A.Id = B.Id;

Diagram / flow: A and B → join → matches plus A-only and B-only rows.

Syntax

SELECT ... FROM A FULL OUTER JOIN B ON A.Id = B.Id;

Example

SELECT ... FROM A FULL OUTER JOIN B ON A.Id = B.Id;

Code example

SELECT COALESCE(a.Id, b.Id) AS Id, a.Value AS OldValue, b.Value AS NewValue
FROM SourceA AS a
FULL OUTER JOIN SourceB AS b ON b.Id = a.Id;

Diagram

A and B → join → matches plus A-only and B-only rows.

Key Points

  • A FULL OUTER JOIN returns matched rows plus unmatched rows from both inputs.
  • Check execution plans and database-engine-specific behavior.
  • Test with representative data and concurrent workloads where relevant.
Q104Window functions

What is a window function and how does it differ from GROUP BY?

Window functions calculate across related rows while preserving each input row. GROUP BY collapses rows into groups, whereas a window aggregate o

Answer

Window functions calculate across related rows while preserving each input row. GROUP BY collapses rows into groups, whereas a window aggregate or ranking function can return a value beside every row.

Example: ROW_NUMBER() OVER (PARTITION BY DepartmentId ORDER BY Salary DESC)

Diagram / flow: Rows → partition by department → order by salary → assign rank per row.

Syntax

ROW_NUMBER() OVER (PARTITION BY DepartmentId ORDER BY Salary DESC)

Example

ROW_NUMBER() OVER (PARTITION BY DepartmentId ORDER BY Salary DESC)

Code example

SELECT EmployeeId, DepartmentId, Salary,
       ROW_NUMBER() OVER (PARTITION BY DepartmentId ORDER BY Salary DESC) AS SalaryRank
FROM Employees;

Diagram

Rows → partition by department → order by salary → assign rank per row.

Key Points

  • Window functions calculate across related rows while preserving each input row.
  • Check execution plans and database-engine-specific behavior.
  • Test with representative data and concurrent workloads where relevant.
Q106Subqueries

What is a correlated subquery?

A correlated subquery references columns from the outer query. It may be evaluated in a way that depends on each outer row, though optimizers can

Answer

A correlated subquery references columns from the outer query. It may be evaluated in a way that depends on each outer row, though optimizers can transform it; compare its plan with an equivalent join or window query.

Example: WHERE EXISTS (SELECT 1 FROM Orders o WHERE o.CustomerId = c.CustomerId)

Diagram / flow: Outer customer row → correlated EXISTS check → include customer when a matching order exists.

Syntax

WHERE EXISTS (SELECT 1 FROM Orders o WHERE o.CustomerId = c.CustomerId)

Example

WHERE EXISTS (SELECT 1 FROM Orders o WHERE o.CustomerId = c.CustomerId)

Code example

SELECT c.CustomerId, c.Name
FROM Customers c
WHERE EXISTS (
  SELECT 1 FROM Orders o WHERE o.CustomerId = c.CustomerId
);

Diagram

Outer customer row → correlated EXISTS check → include customer when a matching order exists.

Key Points

  • A correlated subquery references columns from the outer query.
  • Check execution plans and database-engine-specific behavior.
  • Test with representative data and concurrent workloads where relevant.
Q107Subqueries

When should you use EXISTS instead of IN?

EXISTS expresses whether a matching row exists and is often natural for semi-join logic. IN compares against a set; NULL semantics can make NOT I

Answer

EXISTS expresses whether a matching row exists and is often natural for semi-join logic. IN compares against a set; NULL semantics can make NOT IN especially surprising when the subquery can return NULL.

Example: WHERE EXISTS (SELECT 1 FROM Orders o WHERE o.CustomerId = c.CustomerId)

Diagram / flow: Customer → existence test on Orders → include if a matching row is found.

Syntax

WHERE EXISTS (SELECT 1 FROM Orders o WHERE o.CustomerId = c.CustomerId)

Example

WHERE EXISTS (SELECT 1 FROM Orders o WHERE o.CustomerId = c.CustomerId)

Code example

SELECT c.CustomerId
FROM Customers c
WHERE EXISTS (SELECT 1 FROM Orders o WHERE o.CustomerId = c.CustomerId);

Diagram

Customer → existence test on Orders → include if a matching row is found.

Key Points

  • EXISTS expresses whether a matching row exists and is often natural for semi-join logic.
  • Check execution plans and database-engine-specific behavior.
  • Test with representative data and concurrent workloads where relevant.
Q108Indexing

How does column order affect a composite index?

A composite index is ordered by its leading columns. Choose column order based on equality predicates, range predicates, joins, ordering, selecti

Answer

A composite index is ordered by its leading columns. Choose column order based on equality predicates, range predicates, joins, ordering, selectivity, and workload; one index rarely optimizes every query.

Example: CREATE INDEX IX_Orders_Customer_Date ON Orders(CustomerId, OrderDate);

Diagram / flow: Index key (CustomerId, OrderDate) → supports leading CustomerId lookups and date ranges within a customer.

Syntax

CREATE INDEX IX_Orders_Customer_Date ON Orders(CustomerId, OrderDate);

Example

CREATE INDEX IX_Orders_Customer_Date ON Orders(CustomerId, OrderDate);

Code example

CREATE INDEX IX_Orders_Customer_Date
ON Orders (CustomerId, OrderDate);

Diagram

Index key (CustomerId, OrderDate) → supports leading CustomerId lookups and date ranges within a customer.

Key Points

  • A composite index is ordered by its leading columns.
  • Check execution plans and database-engine-specific behavior.
  • Test with representative data and concurrent workloads where relevant.
Q111Performance

How do you read an execution plan to diagnose a slow query?

Inspect actual versus estimated row counts, scans/seeks, join algorithms, sorts, spills, key lookups, and expensive operators. Use representative

Answer

Inspect actual versus estimated row counts, scans/seeks, join algorithms, sorts, spills, key lookups, and expensive operators. Use representative parameters and data; a single cost percentage is not a complete diagnosis.

Example: EXPLAIN (or the database's actual execution plan feature)

Diagram / flow: SQL statement → optimizer plan → operators and row estimates → compare with actual execution.

Syntax

EXPLAIN (or the database's actual execution plan feature)

Example

EXPLAIN (or the database's actual execution plan feature)

Code example

SET STATISTICS IO, TIME ON;
SELECT CustomerId, COUNT(*)
FROM Orders
WHERE OrderDate >= '2026-01-01'
GROUP BY CustomerId;
-- Inspect the actual execution plan and IO/time output.

Diagram

SQL statement → optimizer plan → operators and row estimates → compare with actual execution.

Key Points

  • Inspect actual versus estimated row counts, scans/seeks, join algorithms, sorts, spills, key lookups, and expensive operators.
  • Check execution plans and database-engine-specific behavior.
  • Test with representative data and concurrent workloads where relevant.
Q113Transactions

Compare common transaction isolation levels.

Read Uncommitted may permit dirty reads; Read Committed prevents dirty reads; Repeatable Read protects rows already read from changes; Serializab

Answer

Read Uncommitted may permit dirty reads; Read Committed prevents dirty reads; Repeatable Read protects rows already read from changes; Serializable adds range protection. Snapshot-style isolation uses row versions, with behavior varying by engine and configuration.

Example: SET TRANSACTION ISOLATION LEVEL READ COMMITTED;

Diagram / flow: Choose isolation → begin transaction → reads/writes observe the engine's concurrency guarantees.

Syntax

SET TRANSACTION ISOLATION LEVEL READ COMMITTED;

Example

SET TRANSACTION ISOLATION LEVEL READ COMMITTED;

Code example

SET TRANSACTION ISOLATION LEVEL READ COMMITTED;
BEGIN TRANSACTION;
SELECT Balance FROM Accounts WHERE AccountId = 42;
COMMIT;

Diagram

Choose isolation → begin transaction → reads/writes observe the engine's concurrency guarantees.

Key Points

  • Read Uncommitted may permit dirty reads; Read Committed prevents dirty reads; Repeatable Read protects rows already read from changes; Serializable adds range protection.
  • Check execution plans and database-engine-specific behavior.
  • Test with representative data and concurrent workloads where relevant.
Q115Normalization

What does Third Normal Form (3NF) aim to prevent?

3NF reduces problematic transitive dependencies so non-key attributes depend on keys rather than other non-key attributes. Normalize to protect c

Answer

3NF reduces problematic transitive dependencies so non-key attributes depend on keys rather than other non-key attributes. Normalize to protect consistency, then denormalize deliberately only for measured needs.

Example: CustomerId → CustomerName, RegionId; RegionId → RegionName

Diagram / flow: Orders storing RegionName repeatedly → update anomalies; separate Regions and reference RegionId.

Syntax

CustomerId → CustomerName, RegionId; RegionId → RegionName

Example

CustomerId → CustomerName, RegionId; RegionId → RegionName

Code example

CREATE TABLE Regions (
  RegionId int PRIMARY KEY,
  RegionName varchar(100) NOT NULL
);
CREATE TABLE Customers (
  CustomerId int PRIMARY KEY,
  CustomerName varchar(100) NOT NULL,
  RegionId int NOT NULL REFERENCES Regions(RegionId)
);

Diagram

Orders storing RegionName repeatedly → update anomalies; separate Regions and reference RegionId.

Key Points

  • 3NF reduces problematic transitive dependencies so non-key attributes depend on keys rather than other non-key attributes.
  • Check execution plans and database-engine-specific behavior.
  • Test with representative data and concurrent workloads where relevant.
Q116Constraints

When should you use ON DELETE CASCADE?

ON DELETE CASCADE removes dependent rows when a referenced parent is deleted. Use it only when child rows have no independent lifecycle; otherwis

Answer

ON DELETE CASCADE removes dependent rows when a referenced parent is deleted. Use it only when child rows have no independent lifecycle; otherwise use RESTRICT/NO ACTION or explicit deletion logic. Cascades can affect many rows.

Example: FOREIGN KEY (OrderId) REFERENCES Orders(OrderId) ON DELETE CASCADE

Diagram / flow: Delete order → database deletes its dependent order lines atomically.

Syntax

FOREIGN KEY (OrderId) REFERENCES Orders(OrderId) ON DELETE CASCADE

Example

FOREIGN KEY (OrderId) REFERENCES Orders(OrderId) ON DELETE CASCADE

Code example

CREATE TABLE OrderLines (
  OrderLineId int PRIMARY KEY,
  OrderId int NOT NULL,
  FOREIGN KEY (OrderId) REFERENCES Orders(OrderId) ON DELETE CASCADE
);

Diagram

Delete order → database deletes its dependent order lines atomically.

Key Points

  • ON DELETE CASCADE removes dependent rows when a referenced parent is deleted.
  • Check execution plans and database-engine-specific behavior.
  • Test with representative data and concurrent workloads where relevant.
Q117Data modification

What is an upsert and what concurrency issues should you consider?

An upsert inserts when a row is absent and updates when it exists. Use engine-supported syntax and a unique constraint to enforce identity; concu

Answer

An upsert inserts when a row is absent and updates when it exists. Use engine-supported syntax and a unique constraint to enforce identity; concurrent attempts must be handled safely.

Example: Engine-specific: MERGE, INSERT ... ON CONFLICT, or INSERT ... ON DUPLICATE KEY UPDATE

Diagram / flow: Incoming key → unique constraint check → insert new row or update existing row.

Syntax

Engine-specific: MERGE, INSERT ... ON CONFLICT, or INSERT ... ON DUPLICATE KEY UPDATE

Example

Engine-specific: MERGE, INSERT ... ON CONFLICT, or INSERT ... ON DUPLICATE KEY UPDATE

Code example

INSERT INTO Settings (SettingKey, SettingValue)
VALUES ('theme', 'dark')
ON CONFLICT (SettingKey)
DO UPDATE SET SettingValue = EXCLUDED.SettingValue; -- PostgreSQL

Diagram

Incoming key → unique constraint check → insert new row or update existing row.

Key Points

  • An upsert inserts when a row is absent and updates when it exists.
  • Check execution plans and database-engine-specific behavior.
  • Test with representative data and concurrent workloads where relevant.

Advanced Questions

Architecture, optimization, and design trade-offs.

Q76Multi-tenancy

How do you design a database for multi-tenancy?

Common options are a shared schema with TenantId, separate schema per tenant, or separate database per tenant. Evaluate isolation, compliance, operational

Answer

Common options are a shared schema with TenantId, separate schema per tenant, or separate database per tenant. Evaluate isolation, compliance, operational overhead, and scale.

Example: Shared tables need tenant-scoped keys, indexes, constraints, and tests against cross-tenant access.

Diagram / flow: Tenant-aware request → tenant context → scoped queries / database routing

Syntax

Tenant-aware request → tenant context → scoped queries / database routing

Example

Tenant-aware request → tenant context → scoped queries / database routing

Code example

Tenant-aware request → tenant context → scoped queries / database routing

Diagram

Diagram / flow:
Tenant-aware request → tenant context → scoped queries / database routing

Key Points

  • Never rely only on a client-supplied TenantId.
Q77Sharding

How do you choose a shard key?

A shard key should distribute data and traffic evenly while supporting common query patterns. Poor choices create hotspots or require scatter-gather querie

Answer

A shard key should distribute data and traffic evenly while supporting common query patterns. Poor choices create hotspots or require scatter-gather queries.

Example: Tenant-based sharding can keep tenant data together but large tenants may become hotspots.

Diagram / flow: Hash(TenantId) → shard; or TenantId range → shard

Syntax

Hash(TenantId) → shard; or TenantId range → shard

Example

Hash(TenantId) → shard; or TenantId range → shard

Code example

Hash(TenantId) → shard; or TenantId range → shard

Diagram

Diagram / flow:
Hash(TenantId) → shard; or TenantId range → shard

Key Points

  • Plan resharding, global uniqueness, and cross-shard operations.
Q78Reliability

How do you design for high availability?

High availability may use replication, failover, health monitoring, backups, tested recovery procedures, and application retry behavior. The design must sp

Answer

High availability may use replication, failover, health monitoring, backups, tested recovery procedures, and application retry behavior. The design must specify acceptable downtime and data loss.

Example: Define RPO and RTO, then test failover and restore procedures.

Diagram / flow: Application → primary/cluster → replica/failover target

Syntax

Application → primary/cluster → replica/failover target

Example

Application → primary/cluster → replica/failover target

Code example

Application → primary/cluster → replica/failover target

Diagram

Diagram / flow:
Application → primary/cluster → replica/failover target

Key Points

  • Replication alone does not protect against accidental deletion or logical corruption.
Q79Reliability

What are RPO and RTO?

Recovery Point Objective is the maximum acceptable data loss measured in time. Recovery Time Objective is the target time to restore service after an incid

Answer

Recovery Point Objective is the maximum acceptable data loss measured in time. Recovery Time Objective is the target time to restore service after an incident.

Example: A 15-minute RPO means recovery should lose no more than roughly 15 minutes of data under the plan.

Diagram / flow: Failure → restore point (RPO) → service restored (RTO)

Syntax

Failure → restore point (RPO) → service restored (RTO)

Example

Failure → restore point (RPO) → service restored (RTO)

Code example

Failure → restore point (RPO) → service restored (RTO)

Diagram

Diagram / flow:
Failure → restore point (RPO) → service restored (RTO)

Key Points

  • Validate targets with real restore and failover exercises.
Q80Distributed transactions

How do you design a reliable outbox table?

The outbox stores pending messages in the same transaction as business changes. A worker publishes them, tracks attempts, and marks completion. Consumers m

Answer

The outbox stores pending messages in the same transaction as business changes. A worker publishes them, tracks attempts, and marks completion. Consumers must be idempotent.

Example: Use a unique message ID, creation time, attempt count, and processing state.

Diagram / flow: BEGIN → update Order + INSERT Outbox → COMMIT Worker → broker → mark published

Syntax

BEGIN → update Order + INSERT Outbox → COMMIT
Worker → broker → mark published

Example

BEGIN → update Order + INSERT Outbox → COMMIT Worker → broker → mark published

Code example

BEGIN → update Order + INSERT Outbox → COMMIT
Worker → broker → mark published

Diagram

Diagram / flow:
BEGIN → update Order + INSERT Outbox → COMMIT
Worker → broker → mark published

Key Points

  • Handle duplicate delivery, poison messages, retention, and parallel worker claiming.
Q81Distributed systems

How do you prevent duplicate processing of events?

Use an idempotent consumer with a durable inbox or processed-message table keyed by message ID. Commit the processed marker with the business update where

Answer

Use an idempotent consumer with a durable inbox or processed-message table keyed by message ID. Commit the processed marker with the business update where possible.

Example: A duplicate message then fails the unique key and can be acknowledged safely after checking state.

Syntax

BEGIN
INSERT ProcessedMessage(MessageId) -- unique
apply business change
COMMIT

Example

BEGIN INSERT ProcessedMessage(MessageId) -- unique apply business change COMMIT

Code example

BEGIN
INSERT ProcessedMessage(MessageId) -- unique
apply business change
COMMIT

Diagram

Distributed systems → database operation → result

Key Points

  • Exactly-once effects usually require careful coordination at the application/data boundary.
Q82Governance and audit

How do you design a schema for auditability and compliance?

Define authoritative records, immutable audit events where required, actor and timestamp semantics, retention, access controls, data minimization, and expo

Answer

Define authoritative records, immutable audit events where required, actor and timestamp semantics, retention, access controls, data minimization, and export/retrieval needs.

Example: Track who changed a sensitive field and the context needed for investigation.

Syntax

Business tables + audit/event table + retention/archival workflow

Example

Business tables + audit/event table + retention/archival workflow

Code example

Business tables + audit/event table + retention/archival workflow

Diagram

Governance and audit → database operation → result

Key Points

  • Do not store secrets or excessive personal data in audit payloads.
Q83Domain modeling

How do you model a payment lifecycle?

Represent payment attempts and state transitions explicitly rather than a single ambiguous boolean. Use unique external references, idempotency keys, amoun

Answer

Represent payment attempts and state transitions explicitly rather than a single ambiguous boolean. Use unique external references, idempotency keys, amounts/currency, timestamps, and reconciliation data.

Example: Keep payment status transitions constrained and reconcile with the provider.

Diagram / flow: Created → Pending → Authorized → Captured ↘ Failed / Cancelled

Syntax

Created → Pending → Authorized → Captured
              ↘ Failed / Cancelled

Example

Created → Pending → Authorized → Captured ↘ Failed / Cancelled

Code example

Created → Pending → Authorized → Captured
              ↘ Failed / Cancelled

Diagram

Diagram / flow:
Created → Pending → Authorized → Captured
              ↘ Failed / Cancelled

Key Points

  • A local database transaction cannot atomically commit a remote payment-provider operation.
Q84Concurrency and transactions

How do you design an inventory reservation schema?

Separate on-hand, reserved, and available quantities or use reservation records with expiry. Enforce nonnegative invariants using atomic updates and transa

Answer

Separate on-hand, reserved, and available quantities or use reservation records with expiry. Enforce nonnegative invariants using atomic updates and transactions.

Example: Use an atomic conditional update or locking strategy to prevent overselling.

Diagram / flow: Available = OnHand - Reserved Order → Reservation → Confirm / Release

Syntax

Available = OnHand - Reserved
Order → Reservation → Confirm / Release

Example

Available = OnHand - Reserved Order → Reservation → Confirm / Release

Code example

Available = OnHand - Reserved
Order → Reservation → Confirm / Release

Diagram

Diagram / flow:
Available = OnHand - Reserved
Order → Reservation → Confirm / Release

Key Points

  • Expiry jobs and payment failure paths must release reservations reliably.
Q85Lifecycle and constraints

How do you model soft delete with unique business keys?

A soft-delete strategy must decide whether deleted rows still reserve unique values. Some engines support filtered/partial unique indexes; other designs us

Answer

A soft-delete strategy must decide whether deleted rows still reserve unique values. Some engines support filtered/partial unique indexes; other designs use active-row keys or separate tables.

Example: This allows a new active account to reuse an email after the old row is soft-deleted, if policy permits.

Syntax

-- SQL Server example
CREATE UNIQUE INDEX UX_User_Email_Active ON dbo.Users(Email) WHERE IsDeleted = 0;

Example

-- SQL Server example CREATE UNIQUE INDEX UX_User_Email_Active ON dbo.Users(Email) WHERE IsDeleted = 0;

Code example

-- SQL Server example
CREATE UNIQUE INDEX UX_User_Email_Active ON dbo.Users(Email) WHERE IsDeleted = 0;

Diagram

Lifecycle and constraints → database operation → result

Key Points

  • Filtered/partial index syntax and NULL behavior vary by engine.
Q86Temporal modeling

How do you model effective-dated records?

Effective-dated records store valid-from and valid-to boundaries to represent when a fact applies. Prevent overlapping intervals when the domain requires a

Answer

Effective-dated records store valid-from and valid-to boundaries to represent when a fact applies. Prevent overlapping intervals when the domain requires a single active fact at any time.

Example: A query selects the row where ValidFrom <= @date and (ValidTo is null or @date < ValidTo).

Syntax

PriceHistory(ProductId, Price, ValidFrom, ValidTo)

Example

PriceHistory(ProductId, Price, ValidFrom, ValidTo)

Code example

PriceHistory(ProductId, Price, ValidFrom, ValidTo)

Diagram

Temporal modeling → database operation → result

Key Points

  • Define inclusive/exclusive boundaries and time-zone semantics clearly.
Q87Temporal modeling

How do you prevent overlapping date ranges?

Use transactions and engine-supported exclusion constraints, locking, or carefully designed validation to prevent overlapping ranges for the same entity. A

Answer

Use transactions and engine-supported exclusion constraints, locking, or carefully designed validation to prevent overlapping ranges for the same entity. Application-only checks can race under concurrency.

Example: A booking should reject a range that overlaps an existing confirmed booking.

Syntax

Conceptual condition: NOT (NewStart < ExistingEnd AND NewEnd > ExistingStart)

Example

Conceptual condition: NOT (NewStart < ExistingEnd AND NewEnd > ExistingStart)

Code example

Conceptual condition: NOT (NewStart < ExistingEnd AND NewEnd > ExistingStart)

Diagram

Temporal modeling → database operation → result

Key Points

  • Exact constraints vary by engine
  • test concurrent inserts.
Q88Concurrency and modeling

How do you design a booking system database?

Model resources, bookings, time ranges, status, and customer references. Prevent double-booking using transactions, suitable locks or exclusion constraints

Answer

Model resources, bookings, time ranges, status, and customer references. Prevent double-booking using transactions, suitable locks or exclusion constraints, and a clear policy for holds and expiry.

Example: A booking is accepted only if no conflicting active booking exists for that resource and interval.

Diagram / flow: Resource 1 ───< Booking Booking(ResourceId, StartAt, EndAt, Status)

Syntax

Resource 1 ───< Booking
Booking(ResourceId, StartAt, EndAt, Status)

Example

Resource 1 ───< Booking Booking(ResourceId, StartAt, EndAt, Status)

Code example

Resource 1 ───< Booking
Booking(ResourceId, StartAt, EndAt, Status)

Diagram

Diagram / flow:
Resource 1 ───< Booking
Booking(ResourceId, StartAt, EndAt, Status)

Key Points

  • Define time zones, buffer periods, cancellation, and race behavior.
Q89Historical consistency

How do you design an order schema that preserves history?

Keep order-line snapshots of item name, unit price, tax/discount, and currency as needed. Product catalog changes should not rewrite what the customer purc

Answer

Keep order-line snapshots of item name, unit price, tax/discount, and currency as needed. Product catalog changes should not rewrite what the customer purchased.

Example: An invoice remains reproducible even after a product is renamed.

Diagram / flow: Order 1 ───< OrderItem >─── 1 Product OrderItem stores PurchasedName and UnitPrice

Syntax

Order 1 ───< OrderItem >─── 1 Product
OrderItem stores PurchasedName and UnitPrice

Example

Order 1 ───< OrderItem >─── 1 Product OrderItem stores PurchasedName and UnitPrice

Code example

Order 1 ───< OrderItem >─── 1 Product
OrderItem stores PurchasedName and UnitPrice

Diagram

Diagram / flow:
Order 1 ───< OrderItem >─── 1 Product
OrderItem stores PurchasedName and UnitPrice

Key Points

  • Specify which values are snapshots and which remain live references.
Q90Lifecycle and scale

How do you design soft-delete and archival together?

Soft delete supports logical removal, while archival moves older data to a lower-cost or separate store. Define how queries, legal holds, restore, and purg

Answer

Soft delete supports logical removal, while archival moves older data to a lower-cost or separate store. Define how queries, legal holds, restore, and purge interact.

Example: Move closed orders older than the retention threshold after validating downstream dependencies.

Diagram / flow: Active tables → archive process → archive store → policy-based purge

Syntax

Active tables → archive process → archive store → policy-based purge

Example

Active tables → archive process → archive store → policy-based purge

Code example

Active tables → archive process → archive store → policy-based purge

Diagram

Diagram / flow:
Active tables → archive process → archive store → policy-based purge

Key Points

  • Archiving is not equivalent to deleting and may affect reporting joins.
Q91Auditability and performance

How do you design a database for audit trails without slowing writes excessively?

Choose which events require synchronous durable auditing, minimize payload size, index only query-critical fields, and consider partitioning or asynchronou

Answer

Choose which events require synchronous durable auditing, minimize payload size, index only query-critical fields, and consider partitioning or asynchronous projections when requirements allow. Critical audit records may need to be committed atomically with the business change.

Example: Partition by time where supported and define retention/archival jobs.

Diagram / flow: Business transaction + required audit row → commit Analytics projection may run asynchronously

Syntax

Business transaction + required audit row → commit
Analytics projection may run asynchronously

Example

Business transaction + required audit row → commit Analytics projection may run asynchronously

Code example

Business transaction + required audit row → commit
Analytics projection may run asynchronously

Diagram

Diagram / flow:
Business transaction + required audit row → commit
Analytics projection may run asynchronously

Key Points

  • Never make legally required audit evidence best-effort without explicit approval.
Q92Performance troubleshooting

How do you investigate a sudden database slowdown?

Compare latency and workload changes, inspect waits, blocking, deadlocks, CPU/I/O, execution plans, statistics, connection saturation, and recent deploymen

Answer

Compare latency and workload changes, inspect waits, blocking, deadlocks, CPU/I/O, execution plans, statistics, connection saturation, and recent deployments. Identify whether the bottleneck is database or application-side.

Example: A missing index, changed plan, parameter sensitivity, or lock contention can all cause regressions.

Diagram / flow: Request trace → query duration → plan/waits → root cause

Syntax

Request trace → query duration → plan/waits → root cause

Example

Request trace → query duration → plan/waits → root cause

Code example

Request trace → query duration → plan/waits → root cause

Diagram

Diagram / flow:
Request trace → query duration → plan/waits → root cause

Key Points

  • Use measurements and baselines
  • avoid speculative index changes.
Q93Query optimization

What is parameter sniffing?

In SQL Server, parameter sniffing is when a cached plan is compiled using parameter values that may not represent later executions. It can cause uneven per

Answer

In SQL Server, parameter sniffing is when a cached plan is compiled using parameter values that may not represent later executions. It can cause uneven performance when data distributions are skewed.

Example: Investigate actual plans and parameter distributions before using recompilation or hints.

Diagram / flow: EXEC dbo.SearchOrders @CustomerId = 123; -- plan may depend on compile-time values

Syntax

EXEC dbo.SearchOrders @CustomerId = 123; -- plan may depend on compile-time values

Example

EXEC dbo.SearchOrders @CustomerId = 123; -- plan may depend on compile-time values

Code example

EXEC dbo.SearchOrders @CustomerId = 123; -- plan may depend on compile-time values

Diagram

Diagram / flow:
EXEC dbo.SearchOrders @CustomerId = 123; -- plan may depend on compile-time values

Key Points

  • Plan caching is useful
  • do not disable it globally without evidence.
Q94Deployment safety

How do you design a database migration rollback plan?

Prefer backward-compatible changes and maintain a tested recovery path. Some data transformations cannot be safely reversed, so a forward fix or restore ma

Answer

Prefer backward-compatible changes and maintain a tested recovery path. Some data transformations cannot be safely reversed, so a forward fix or restore may be needed.

Example: Take verified backups and test migrations against production-like volume.

Diagram / flow: Expand → deploy → backfill → switch → contract

Syntax

Expand → deploy → backfill → switch → contract

Example

Expand → deploy → backfill → switch → contract

Code example

Expand → deploy → backfill → switch → contract

Diagram

Diagram / flow:
Expand → deploy → backfill → switch → contract

Key Points

  • A syntactically reversible schema change may still lose business data.
Q95Modeling trade-offs

How do you choose between JSON columns and normalized tables?

Normalized tables are better for structured relationships, constraints, joins, and querying individual attributes. JSON columns suit flexible or semi-struc

Answer

Normalized tables are better for structured relationships, constraints, joins, and querying individual attributes. JSON columns suit flexible or semi-structured payloads whose internal shape changes, but may weaken constraints and indexing portability.

Example: Use JSON for extensible metadata only when its query and validation needs are understood.

Syntax

Product attributes in typed columns; flexible provider metadata in JSON

Example

Product attributes in typed columns; flexible provider metadata in JSON

Code example

Product attributes in typed columns; flexible provider metadata in JSON

Diagram

Modeling trade-offs → database operation → result

Key Points

  • Hybrid designs are common
  • avoid storing the whole relational model as JSON.
Q96Distributed systems

How do you design a schema for event-driven projections?

A projection/read model stores data shaped for queries and is updated from events. Include event IDs or versions to support idempotency and detect out-of-o

Answer

A projection/read model stores data shaped for queries and is updated from events. Include event IDs or versions to support idempotency and detect out-of-order updates where needed.

Example: A customer summary projection can combine order totals for fast reads.

Diagram / flow: Domain events → consumer → projection tables → query API

Syntax

Domain events → consumer → projection tables → query API

Example

Domain events → consumer → projection tables → query API

Code example

Domain events → consumer → projection tables → query API

Diagram

Diagram / flow:
Domain events → consumer → projection tables → query API

Key Points

  • Define rebuild/replay strategy and eventual-consistency expectations.
Q97Service boundaries

How do you handle schema ownership in microservices?

Each service should own its data contract and migrations. Other services should use APIs or events rather than directly modifying another service's tables.

Answer

Each service should own its data contract and migrations. Other services should use APIs or events rather than directly modifying another service's tables.

Example: This reduces coupling and allows independent deployment.

Diagram / flow: Order Service → Order DB Catalog Service → Catalog DB Events connect services

Syntax

Order Service → Order DB
Catalog Service → Catalog DB
Events connect services

Example

Order Service → Order DB Catalog Service → Catalog DB Events connect services

Code example

Order Service → Order DB
Catalog Service → Catalog DB
Events connect services

Diagram

Diagram / flow:
Order Service → Order DB
Catalog Service → Catalog DB
Events connect services

Key Points

  • Cross-service reporting may need a warehouse or purpose-built projection.
Q98Privacy and governance

How do you design for data privacy deletion requests?

Map where personal data lives, including primary tables, search indexes, caches, exports, logs, and backups. Apply deletion or anonymization under policy w

Answer

Map where personal data lives, including primary tables, search indexes, caches, exports, logs, and backups. Apply deletion or anonymization under policy while preserving legally required records where applicable.

Example: A customer deletion workflow may anonymize old order contact details while retaining legally required transaction records.

Diagram / flow: Data inventory → authorized delete/anonymize workflow → verify downstream copies

Syntax

Data inventory → authorized delete/anonymize workflow → verify downstream copies

Example

Data inventory → authorized delete/anonymize workflow → verify downstream copies

Code example

Data inventory → authorized delete/anonymize workflow → verify downstream copies

Diagram

Diagram / flow:
Data inventory → authorized delete/anonymize workflow → verify downstream copies

Key Points

  • Retention and deletion rules depend on applicable law and business obligations.
Q99Quality engineering

How do you test database constraints and migrations?

Test valid and invalid inserts, FK behavior, unique and check constraints, migration from prior versions, rollback/forward recovery, and performance with r

Answer

Test valid and invalid inserts, FK behavior, unique and check constraints, migration from prior versions, rollback/forward recovery, and performance with realistic data volumes.

Example: Run integration tests against the same database engine/version family used in production.

Diagram / flow: Migration test: old schema + fixture data → migrate → assert schema and data

Syntax

Migration test: old schema + fixture data → migrate → assert schema and data

Example

Migration test: old schema + fixture data → migrate → assert schema and data

Code example

Migration test: old schema + fixture data → migrate → assert schema and data

Diagram

Diagram / flow:
Migration test: old schema + fixture data → migrate → assert schema and data

Key Points

  • Mocks cannot verify actual SQL constraints or engine-specific migration behavior.
Q100Physical design

How do you decide whether to split a large table?

Split or partition only for a concrete need such as retention, workload isolation, or manageability. Vertical splitting separates rarely used or sensitive

Answer

Split or partition only for a concrete need such as retention, workload isolation, or manageability. Vertical splitting separates rarely used or sensitive columns; horizontal partitioning divides rows by a key.

Example: A large text/blob column may be separated if it is rarely accessed and measured benefits justify it.

Syntax

Product core table + ProductDescription table (vertical split)

Example

Product core table + ProductDescription table (vertical split)

Code example

Product core table + ProductDescription table (vertical split)

Diagram

Physical design → database operation → result

Key Points

  • Splitting can add joins and complexity
  • measure first.
Q105CTEs

When would you use a recursive common table expression?

A recursive CTE is useful for hierarchical or graph-like data, such as employee reporting trees or category paths. Include a termination conditio

Answer

A recursive CTE is useful for hierarchical or graph-like data, such as employee reporting trees or category paths. Include a termination condition and guard against cycles where the data model permits them.

Example: WITH Tree AS (anchor UNION ALL recursive_member)

Diagram / flow: Anchor rows → recursive member repeatedly adds descendants → stop when no new rows match.

Syntax

WITH Tree AS (anchor UNION ALL recursive_member)

Example

WITH Tree AS (anchor UNION ALL recursive_member)

Code example

WITH Org AS (
  SELECT EmployeeId, ManagerId, 0 AS Level FROM Employees WHERE ManagerId IS NULL
  UNION ALL
  SELECT e.EmployeeId, e.ManagerId, o.Level + 1
  FROM Employees e JOIN Org o ON e.ManagerId = o.EmployeeId
)
SELECT * FROM Org;

Diagram

Anchor rows → recursive member repeatedly adds descendants → stop when no new rows match.

Key Points

  • A recursive CTE is useful for hierarchical or graph-like data, such as employee reporting trees or category paths.
  • Check execution plans and database-engine-specific behavior.
  • Test with representative data and concurrent workloads where relevant.
Q109Indexing

What is a covering index?

A covering index contains the key and included columns needed by a query, allowing the engine to satisfy it without extra base-table lookups in s

Answer

A covering index contains the key and included columns needed by a query, allowing the engine to satisfy it without extra base-table lookups in suitable plans. Extra columns increase storage and write cost.

Example: CREATE INDEX ... ON Orders(CustomerId) INCLUDE (OrderDate, Total);

Diagram / flow: Query columns → index contains needed values → fewer lookups to base table.

Syntax

CREATE INDEX ... ON Orders(CustomerId) INCLUDE (OrderDate, Total);

Example

CREATE INDEX ... ON Orders(CustomerId) INCLUDE (OrderDate, Total);

Code example

CREATE INDEX IX_Orders_Customer_Cover
ON Orders (CustomerId) INCLUDE (OrderDate, Total);

Diagram

Query columns → index contains needed values → fewer lookups to base table.

Key Points

  • A covering index contains the key and included columns needed by a query, allowing the engine to satisfy it without extra base-table lookups in suitable plans.
  • Check execution plans and database-engine-specific behavior.
  • Test with representative data and concurrent workloads where relevant.
Q110Performance

What makes a predicate SARGable?

A SARGable predicate can use an index search effectively. Applying functions or conversions to indexed columns may prevent a seek; prefer equival

Answer

A SARGable predicate can use an index search effectively. Applying functions or conversions to indexed columns may prevent a seek; prefer equivalent range predicates when correct.

Example: WHERE OrderDate >= @start AND OrderDate < @end

Diagram / flow: Index on OrderDate → bounded range seek → qualifying rows.

Syntax

WHERE OrderDate >= @start AND OrderDate < @end

Example

WHERE OrderDate >= @start AND OrderDate < @end

Code example

DECLARE @day date = '2026-01-15';
SELECT OrderId, OrderDate
FROM Orders
WHERE OrderDate >= @day
  AND OrderDate < DATEADD(day, 1, @day);

Diagram

Index on OrderDate → bounded range seek → qualifying rows.

Key Points

  • A SARGable predicate can use an index search effectively.
  • Check execution plans and database-engine-specific behavior.
  • Test with representative data and concurrent workloads where relevant.
Q112Transactions

What causes a deadlock and how can you reduce it?

A deadlock occurs when transactions wait cyclically on resources held by each other. Access resources in a consistent order, keep transactions sh

Answer

A deadlock occurs when transactions wait cyclically on resources held by each other. Access resources in a consistent order, keep transactions short, index predicates, and implement retry for confirmed deadlock victims where safe.

Example: Transaction A locks row 1 then waits for row 2; B locks row 2 then waits for row 1.

Diagram / flow: T1 holds R1 → waits for R2; T2 holds R2 → waits for R1 → cycle detected.

Syntax

Transaction A locks row 1 then waits for row 2; B locks row 2 then waits for row 1.

Example

Transaction A locks row 1 then waits for row 2; B locks row 2 then waits for row 1.

Code example

BEGIN TRANSACTION;
-- Access tables/rows in a consistent order across code paths.
UPDATE Accounts SET Balance = Balance - 10 WHERE AccountId = 1;
UPDATE Accounts SET Balance = Balance + 10 WHERE AccountId = 2;
COMMIT;

Diagram

T1 holds R1 → waits for R2; T2 holds R2 → waits for R1 → cycle detected.

Key Points

  • A deadlock occurs when transactions wait cyclically on resources held by each other.
  • Check execution plans and database-engine-specific behavior.
  • Test with representative data and concurrent workloads where relevant.
Q118Performance

What is keyset pagination and when is it preferable to OFFSET pagination?

Keyset pagination continues from the last seen sort key and is efficient for deep pages when the ordering is stable and indexed. OFFSET is simple

Answer

Keyset pagination continues from the last seen sort key and is efficient for deep pages when the ordering is stable and indexed. OFFSET is simpler for arbitrary page numbers but may scan/discard many rows and can shift under concurrent writes.

Example: WHERE OrderId > @lastId ORDER BY OrderId LIMIT @pageSize

Diagram / flow: Last seen key → indexed seek after key → fetch next page.

Syntax

WHERE OrderId > @lastId ORDER BY OrderId LIMIT @pageSize

Example

WHERE OrderId > @lastId ORDER BY OrderId LIMIT @pageSize

Code example

SELECT OrderId, OrderDate, Total
FROM Orders
WHERE OrderId > @lastOrderId
ORDER BY OrderId
FETCH FIRST 50 ROWS ONLY; -- syntax varies by engine

Diagram

Last seen key → indexed seek after key → fetch next page.

Key Points

  • Keyset pagination continues from the last seen sort key and is efficient for deep pages when the ordering is stable and indexed.
  • Check execution plans and database-engine-specific behavior.
  • Test with representative data and concurrent workloads where relevant.
Q119Performance

What is table partitioning and what does it not solve?

Partitioning divides a large table into manageable physical/logical segments, often by date or key. It can aid maintenance and partition pruning,

Answer

Partitioning divides a large table into manageable physical/logical segments, often by date or key. It can aid maintenance and partition pruning, but it does not automatically make every query faster; partition keys and query predicates matter.

Example: PARTITION BY RANGE (OrderDate) -- engine-specific DDL

Diagram / flow: Large Orders table → partitions by date → queries with date predicates may prune irrelevant partitions.

Syntax

PARTITION BY RANGE (OrderDate) -- engine-specific DDL

Example

PARTITION BY RANGE (OrderDate) -- engine-specific DDL

Code example

CREATE TABLE OrdersByDate (
  OrderId bigint,
  OrderDate date NOT NULL,
  Total decimal(12,2)
) ;
-- Define engine-specific partitioning after choosing a supported database.

Diagram

Large Orders table → partitions by date → queries with date predicates may prune irrelevant partitions.

Key Points

  • Partitioning divides a large table into manageable physical/logical segments, often by date or key.
  • Check execution plans and database-engine-specific behavior.
  • Test with representative data and concurrent workloads where relevant.
Q120Transactions

How can optimistic concurrency prevent lost updates?

Store a version or rowversion and include the original version in the update predicate. If zero rows are updated, another writer changed the row;

Answer

Store a version or rowversion and include the original version in the update predicate. If zero rows are updated, another writer changed the row; the application should reload, merge, or report a conflict.

Example: UPDATE Products SET Price=@price, Version=Version+1 WHERE Id=@id AND Version=@oldVersion

Diagram / flow: Read version 5 → update where version=5 → success increments version, or zero rows means conflict.

Syntax

UPDATE Products SET Price=@price, Version=Version+1 WHERE Id=@id AND Version=@oldVersion

Example

UPDATE Products SET Price=@price, Version=Version+1 WHERE Id=@id AND Version=@oldVersion

Code example

UPDATE Products
SET Price = @newPrice, Version = Version + 1
WHERE ProductId = @id AND Version = @oldVersion;
-- Check affected row count; zero means a concurrency conflict.

Diagram

Read version 5 → update where version=5 → success increments version, or zero rows means conflict.

Key Points

  • Store a version or rowversion and include the original version in the update predicate.
  • Check execution plans and database-engine-specific behavior.
  • Test with representative data and concurrent workloads where relevant.

Share this question bank

Send this page to someone preparing for an interview.