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.