Relational database concepts
How a relational database behaves whatever product runs it: the relational model and schema design on top, and constraints, transactions and concurrency, indexes, query planning, server-side objects, storage internals, replication, partitioning and access control underneath. Interviewers lean on this layer at every level because it is the part that transfers when a candidate changes engines — it separates people who can predict what the database will do from people who have memorised one vendor's manual. No product is named here; the eleven engine subtrees sit beside this one under db-relational.
on this pageshowhide
guide
overview
~1 minRelational database concepts are the part of a database interview that survives a change of engine. Interviewers use them to separate candidates who can predict what the database will do with a statement from candidates who have learned one product's commands: what two concurrent sessions will see, whether an index will actually be used, why a commit survives a crash, what a replica can and cannot promise. Questions run from a junior defining a key or explaining a missing value to a principal arguing about isolation guarantees, failover data loss or where business rules should live. The subject splits into two layers and an outer ring. The logical layer is the [relational model](/topics/db-relational-model) itself (relations, keys, algebra, three-valued logic), [schema design and normalization](/topics/db-relational-schema-design), and the [integrity constraints](/topics/db-relational-constraints) that let the engine enforce rules declaratively. The engine layer honours those promises: [transactions and concurrency control](/topics/db-relational-transactions), [indexes and access paths](/topics/db-relational-indexing), [query processing and optimization](/topics/db-relational-query-processing), [server-side objects](/topics/db-relational-views-server-logic) such as views, procedures and triggers, and [storage internals](/topics/db-relational-storage-architecture) from pages to the write-ahead log. The outer ring is operational: [replication, backup and high availability](/topics/db-relational-replication-ha), [partitioning and scaling](/topics/db-relational-partitioning-scaling), and [access control and data protection](/topics/db-relational-security-access). Start with the model and its keys, because every later section borrows that vocabulary, then schema design and constraints, which interviewers probe more than anything else here. Indexes and transactions come next: between them they explain most "why is this slow" and "why is this wrong" questions. Query processing and storage internals read better once those are familiar, and replication, partitioning and security build on all of it. Nothing on this page is tied to a product; the engine-specific sections sit beside it under [relational databases](/topics/db-relational), and this is what they have in common.
primer
A few ideas carry most of the subject. Once they are solid, the questions below read as consequences rather than facts to memorise. - **The model is a contract; the engine is an implementation.** A relation is an unordered collection of distinct tuples under a declared heading, and the engine may store, order and reach those tuples however it likes as long as the answer is the same. That separation is why an index can be added without touching a query, and why a query with no explicit ordering carries no order guarantee. Many questions test whether you know which side of that line a behaviour lives on. - **Declared rules beat checked rules.** Keys, foreign keys, uniqueness, `NOT NULL` and `CHECK` predicates are enforced by the engine on every write, inside the writing transaction. An application that reads first and writes second leaves a window in which another session can act; a constraint leaves none. Interviewers probe this because it shows whether you trust the database with invariants. - **A missing value makes logic three-valued.** Comparisons against a missing value yield unknown, and that quietly changes filters, joins, aggregates, uniqueness and negated subqueries. Few ideas generate more trick questions per sentence. - **Normalization is about anomalies, not tidiness.** Each normal form removes one way for the same fact to be stored twice and then disagree. Denormalizing is a legitimate choice when reads dominate, but it has to be argued as a trade, with a plan for keeping the copies consistent. - **Isolation is a menu of permitted anomalies.** Full isolation is expensive, which is why engines let you relax it, and each level is best understood by what it still lets happen. Knowing which anomaly a piece of code is exposed to, and which mechanism (a snapshot, a lock, a retry) removes it, is the heart of the transactions section. - **Access cost is counted in pages and rows.** Whether the planner scans a table, walks an index or joins by hashing, the decision rests on estimated row counts and page reads drawn from statistics. An index is not free speed: it is a sorted copy of some columns that every write must maintain, and the planner uses it only when its estimate says it is cheaper. - **Durability comes from the log, not the data files.** A commit is made durable by forcing a sequential log record to stable storage; changed pages are written later, and recovery replays the log. The same log feeds replication and point-in-time restore, which is why so many operational questions lead back to it. - **Every copy trades freshness for something.** Replicas, materialized views, caches and backups all hold data that may lag the source. The recurring question is how far behind each copy is allowed to be, and what its readers must tolerate.
- Relation
- A set of tuples sharing one heading of named, typed attributes; the formal object a table approximates. As a set, it has no row order and no duplicates.
- Candidate key
- A minimal set of attributes that identifies each tuple uniquely. One is chosen as the primary key; the others stay available as alternate keys.
- Functional dependency
- A rule that the values of one attribute set determine the values of another. Normal forms are defined by which dependencies a table may contain.
- Referential integrity
- The guarantee that every foreign key value points at an existing parent row, kept by checks on child writes and on parent deletes or key changes.
- Three-valued logic
- The logic an engine applies once values can be missing: a predicate is true, false or unknown, and a filter keeps only the rows where it is true.
- Isolation level
- A setting that bounds which concurrency anomalies a transaction may observe; weaker levels allow more of them in exchange for less blocking and fewer aborts.
- Serializability
- The property that concurrent transactions produce the same outcome as some one-at-a-time ordering of them; the strongest isolation the standard defines.
- Multi-version concurrency control
- A scheme in which writers create new row versions and readers see a consistent snapshot of older ones, so reads and writes rarely wait for each other.
- Two-phase locking
- A discipline in which a transaction acquires locks in one phase and releases them in another, never acquiring after its first release; the classic route to serializability.
- B+tree
- A balanced, page-based search tree with every key held in linked leaf pages; the default index structure for equality, range and ordered access.
- Selectivity
- The fraction of rows a predicate matches. Small fractions favour index access; large ones favour reading the whole table.
- Cardinality estimate
- The optimizer's prediction of how many rows an operator will produce, derived from statistics; a large share of bad plans trace back to a wrong one.
- Execution plan
- The tree of physical operators (scans, joins, sorts, aggregations) the engine chooses to run a query, annotated with estimated and optionally actual row counts.
- Buffer pool
- The engine's own in-memory cache of fixed-size data pages, through which reads and writes of table and index data pass.
- Write-ahead log
- A sequential record of changes that must reach stable storage before the pages it describes; the basis of durability, crash recovery and most replication.
- Replication lag
- How far a replica trails its primary, measured as log volume not yet applied or as the age of the newest applied change.
- RPO and RTO
- Recovery point objective, the data loss a system can tolerate, and recovery time objective, the downtime it can tolerate; together they shape backup and failover design.
- Partition pruning
- Skipping partitions whose declared bounds cannot contain matching rows; it needs a predicate on the partition key.
The sections are not separate chapters. They lean on each other, and a single interview question often crosses three of them. **The model sets the rules the engine must honour.** Relational theory defines what a correct answer is; schema design applies it to a domain; constraints turn the design's rules into checks the engine runs. Keys connect all three: a candidate key from the theory becomes a primary or unique constraint in the schema, and that constraint is almost always backed by an index. **Indexes serve two purposes at once.** The structure that enforces uniqueness and makes foreign key checks cheap is also what the planner weighs when it picks an access path. That is why index questions appear in the constraint, query and write-performance sections alike, and why an unindexed referencing column is a recurring scenario. **The optimizer connects the query to storage.** Query processing turns declarative text into a plan by estimating how many rows each step produces and how many pages each access path touches. The estimates come from statistics about the stored data; the costs come from how pages, the buffer pool and the memory for sorts and hashes behave. A slow-query question usually needs all three sections. **Transactions sit on the storage machinery.** Atomicity and durability are delivered by the write-ahead log and crash recovery; isolation is delivered by locks, row versions or both. Row versioning leaves dead versions that background cleanup must reclaim, which links concurrency to bloat, long-running transactions and table maintenance. **Server-side objects reuse everything above.** Views are stored queries the optimizer can merge into the caller's query; materialized views are stored results with a refresh cost; triggers and procedures run inside the caller's transaction and inherit its isolation and locks. Arguing where business logic should live is largely arguing about those inherited properties. **Operations extend the single server outward.** Replication ships the same log that provides durability; point-in-time recovery replays it over a base backup; partitioning splits one table so pruning and retention become cheap; sharding splits the whole database and gives up cheap cross-shard joins and constraints. Access control and encryption wrap every layer, from who may connect to what a stolen disk or backup reveals.
- Relational Model & Theory →
Relations, keys and three-valued logic are the vocabulary every other section uses, and the source of many short questions about missing values and duplicates.
- Schema Design & Normalization →
The most heavily probed area: normal forms, relationship mapping and the design trade-offs you will be asked to defend.
- Keys & Integrity Constraints →
Turns a design's rules into engine-enforced guarantees and shows why checks done in application code race under concurrency.
- Indexes & Access Paths →
How the engine reaches rows, what an index costs on every write, and why a valid index is sometimes left unused.
- Transactions & Concurrency Control →
Isolation levels, anomalies and row versioning: the section that tests whether you can predict what concurrent sessions do to each other.
- Query Processing & Optimization →
Ties indexes and statistics into plans, so you can explain a slow query from the engine's side instead of guessing.
Treating a missing value as an ordinary one: testing it with equality, forgetting how it empties a negated subquery, or assuming every engine counts several of them against a unique constraint the same way.
Checking for a row from the application and then inserting it, instead of declaring a unique constraint and handling the violation; the gap between the two statements is a race.
Naming an isolation level without the anomalies it still permits, or assuming a level behaves identically everywhere; the standard only says what each level may allow, and engines may allow less.
Adding an index for each slow query without counting its cost on writes, or expecting a composite index to serve a filter that skips its leading column.
Declaring a foreign key but leaving the referencing column unindexed in an engine that does not index it for you, so parent deletes and key updates scan the child table.
Trusting a predicted plan's row estimates; compare them with actual counts from a real run before blaming the index or rewriting the query.
Assuming a committed write is visible on an asynchronous replica at once; reads of your own writes need the primary or a lag check.
Holding a transaction open across user think time or remote calls, which keeps locks, pins old row versions and stalls cleanup of dead ones.
Calling a replica a backup: a destructive statement replicates too, so recovery needs independent backups and a restore that has actually been rehearsed.
Letting the application connect as a superuser or as the owner of its tables, which turns any injection or leaked credential into control of the whole schema.
Most design discussions here come down to one of a few recurring choices, and naming the one in play is often what the interviewer is waiting for. - **Normalized versus denormalized.** Normalization stores each fact once and keeps writes safe; denormalization copies facts to save joins at read time. The deciding questions are the read-to-write ratio and who keeps the copies in step. - **Stronger versus weaker isolation.** Stronger levels remove anomalies at the price of blocking, aborts and retries; weaker ones leave the application to guard specific read-modify-write paths with explicit locks or conditional updates. - **Read speed versus write cost.** Every index, materialized view and trigger makes some reads cheaper and every affected write more expensive. Count both sides before adding one. - **Database versus application enforcement.** Constraints and server-side logic sit next to the data and hold whichever service writes; application logic is easier to test, version and deploy. An invariant that must survive every writer usually belongs in the database. - **Durability versus commit latency.** Waiting for the log flush, and for a synchronous standby, protects acknowledged commits; relaxing either lowers latency and raises the data a failure can lose. - **Scale up versus scale out.** A bigger server keeps one consistent database and simple queries; replicas and shards add capacity at the cost of stale reads, cross-shard queries and constraints that no longer span all the data.
Several shapes recur across the sections under different names. Recognising them is the quickest way to place an unfamiliar question. - **Check, then act, with no guard.** Duplicate sign-ups, lost updates, overselling stock and double-applied payments are one race: a decision based on a read that another session invalidates. The fixes are shared too: a constraint, an atomic conditional write, a lock, or a stronger isolation level with retries. - **Estimate, then choose.** Index versus scan, join algorithm, join order and partition pruning are all planner decisions driven by row estimates. When one goes wrong, look at statistics before rewriting the query. - **Write to the log once, reuse it everywhere.** Durability, crash recovery, replication, point-in-time restore and change capture are different consumers of the same change stream. - **Keep old versions, clean up later.** Row versioning and undo information buy non-blocking reads and pay for them with background cleanup, and long transactions are what make that work pile up. - **Precompute and pay on write.** Indexes, materialized views, generated columns and summary tables move work from reads to writes or to a refresh schedule. - **Split by a key.** Partitioning, sharding and tenant layouts each pick a key that decides where a row lives, and that choice decides which queries stay local and which fan out.
explore
- Relational Model & Theory49 questions
- Relations, Tuples & Attributes4 questions
- Schema vs Instance3 questions
- Set vs Bag Semantics4 questions
- Key Taxonomy3 questions
- Relational Algebra19 questions
- Relational Calculus4 questions
- Three-Valued Logic & NULL3 questions
- Codd's Rules5 questions
- Logical & Physical Data Independence4 questions
- Schema Design & Normalization94 questions
- Normalization Theory35 questions
- ER Modeling & Relational Mapping21 questions
- Practical Patterns & Anti-Patterns28 questions
- Schema Evolution & Migrations10 questions
- Keys & Integrity Constraints48 questions
- Primary Keys in Practice4 questions
- Foreign Key Enforcement4 questions
- Referential Actions4 questions
- Unique Constraints & NULLs4 questions
- CHECK Constraints5 questions
- NOT NULL & DEFAULT3 questions
- Deferrable & Deferred Checking5 questions
- Unique Index vs Unique Constraint5 questions
- Adding Constraints to Live Tables5 questions
- Database vs Application Enforcement4 questions
- Constraint Costs on Writes5 questions
- Transactions & Concurrency Control108 questions
- ACID Guarantees20 questions
- Concurrency Anomalies22 questions
- Isolation Levels21 questions
- MVCC Mechanics16 questions
- Locking & Two-Phase Locking16 questions
- Transactions in Practice13 questions
- Indexes & Access Paths67 questions
- B+Tree Structure & Fanout5 questions
- B+Tree Inserts, Page Splits & Range Scans5 questions
- Hash Indexes4 questions
- Composite Indexes & Leftmost-Prefix Rule5 questions
- Covering Indexes & Index-Only Scans4 questions
- Selectivity & Cardinality5 questions
- Partial & Expression Indexes5 questions
- Clustered Index vs Heap Storage5 questions
- Secondary Indexes & Row Lookups4 questions
- Index Write & Maintenance Cost5 questions
- Index Bloat & Fragmentation5 questions
- Bitmap Indexes5 questions
- Access Paths: Full Scan vs Index Scan4 questions
- When the Planner Ignores an Index6 questions
- Query Processing & Optimization72 questions
- Pipeline: Parse & Rewrite12 questions
- Cost-Based Optimization22 questions
- Execution Engine27 questions
- Plans in Practice11 questions
- Views, Procedures & Server-Side Logic46 questions
- Views & Their Use Cases5 questions
- Updatable Views5 questions
- Materialized Views & Refresh Strategies4 questions
- Stored Procedures & Functions6 questions
- Business Logic in the Database: Trade-Offs4 questions
- Trigger Mechanics5 questions
- Trigger Pitfalls5 questions
- Generated & Computed Columns4 questions
- Sequences & Identity Columns4 questions
- Temporary Tables4 questions
- Engine Architecture & Storage Internals54 questions
- Client/Server Model & Connection Handling4 questions
- Connection Pooling4 questions
- Background Workers4 questions
- Pages, Heap Files & Row Layout6 questions
- Buffer Pool & Eviction5 questions
- Write-Ahead Logging (Redo/Undo)5 questions
- Checkpoints5 questions
- Crash Recovery (ARIES Concept)5 questions
- Dead Version Cleanup (Vacuum/Purge)5 questions
- Row Store vs Column Store3 questions
- Memory Areas & Spill-to-Disk3 questions
- System Catalogs5 questions
- Replication, Backup & High Availability54 questions
- Replication & Read Scaling20 questions
- Failover & Availability15 questions
- Backup & Recovery19 questions
- Partitioning & Scaling46 questions
- Table partitioning: range, list, hash5 questions
- Partition pruning and partition-aware plans4 questions
- Partition maintenance and retention4 questions
- Sharding a relational database: shard keys5 questions
- Cross-shard queries and resharding6 questions
- Multi-tenancy schemes6 questions
- Vertical vs horizontal scaling of an RDBMS5 questions
- Scaling reads vs scaling writes6 questions
- Access Control & Data Protection45 questions
- Database Authentication vs Authorization6 questions
- Roles & Privilege Model6 questions
- GRANT/REVOKE Semantics5 questions
- Least-Privilege Application Accounts5 questions
- Row-Level Security5 questions
- Column Masking & Restricted Projections4 questions
- Encryption at Rest4 questions
- Encryption in Transit5 questions
- Database Auditing5 questions
- AI & Data Scientistroleanchors this topic
- AI Engineerroleanchors this topic
- Backend Developerroleanchors this topic
- Computer Scienceskillanchors this topic
- Cyber Security Expertroleanchors this topic
- Data Analystroleanchors this topic
- Data Engineerroleanchors this topic
- Full Stack Developerroleanchors this topic
- Java Backend Developerroleanchors this topic
- Kotlin Backend Developerroleanchors this topic
- MLOps Engineerroleanchors this topic
- Machine Learning Engineerroleanchors this topic
- Software Architectroleanchors this topic
- BI Analystrole
- BigQueryskill
- DevOps / SRE Engineerrole
- DevSecOps Engineerrole
- Forward Deployed Engineerrole
- Java SDETrole
- MongoDBskill
- PostgreSQL DBArole
- QA Engineerrole
- SQLskill
- Server-Side Game Developerrole
- Snowflakeskill
questions
683 · 11 sectionsWhat is the Cartesian product of two relations, and how are the theta-join and equi-join defined in terms of it?
basics
~20 sThe Cartesian product pairs every tuple of one relation with every tuple of the other, producing a relation with the combined attributes and a cardinality equal to the product of the inputs. A theta-join is that product filtered by a predicate; an equi-join is a theta-join whose predicate uses only equality comparisons.
In relational algebra, what does the selection operator σ (sigma) do to a relation, and how does a conjunctive predicate σ over "p AND q" relate to applying two selections one after the other?
basics
~10 sSelection σ_p(R) keeps exactly the tuples of relation R that satisfy predicate p. The schema is unchanged — it filters rows, never columns. Conjunctions cascade: σ_{p∧q}(R) = σ_p(σ_q(R)) = σ_q(σ_p(R)).
Before you can take the union or the difference of two relations in relational algebra, what must be true of them? Explain what "union compatibility" means and what breaks without it.
basics
~20 sThe two relations must be union-compatible: same number of attributes, in corresponding positions, with compatible types. Without that, the result would have no well-defined heading, so the expression is simply invalid — not merely wrong at runtime.
In the relational model, what is the difference between a superkey, a candidate key, and a primary key?
basics
~20 sA superkey is any set of attributes whose values are unique across all rows. A candidate key is a minimal superkey: drop any attribute and uniqueness breaks. The primary key is the one candidate key chosen as the official row identifier; the rest are alternate keys.
In the relational model, what exactly is a relation, and how do the SQL words table, row and column map onto relation, tuple and attribute?
basics
~20 sA relation is a heading plus a body. The heading is a set of named attributes, each with a domain (type); the body is a set of tuples, each mapping every attribute name to a value. Informally: table = relation, row = tuple, column = attribute.
In a conceptual data model, how do you decide whether something like a customer's address should be modeled as an entity in its own right or as an attribute of the customer?
basics
~20 sAn entity is a thing with its own identity, its own describing facts and its own lifecycle. An attribute is one fact about a single entity instance. If addresses repeat, need describing, or are referenced on their own, model an entity.
A model says a student may enrol in many courses and a course may hold many students. How is that many-to-many association represented in relational tables, what is the extra table's key, and why can it not be done with a column on either side?
basics
~20 sIt becomes a third table holding one row per pair — student key and course key — with a foreign key to each parent and a primary key over the pair. Neither parent can hold the link because each side has many partners, and a column stores only one value.
An entity in your model has an attribute that can hold several values at once, such as a customer's phone numbers. How is that mapped to relational tables, and why not use repeated columns or one comma-separated string?
basics
~20 sIt becomes a child table holding the owner's key plus one value per row, with a foreign key to the owner and a key over (owner key, value). Repeated columns cap the count and scatter one fact; a delimited string loses typing, constraints and lookups.
How do you store a tree structure (for example an organizational chart or a category tree) in a relational table using a self-referencing foreign key, and how do you retrieve a whole subtree from it?
basics
~20 sGive the table a parent_id column that is a foreign key back to its own primary key. Roots have NULL parent_id. One row per node stores one edge. To read a whole subtree you walk the parent_id chain repeatedly, which in standard SQL means a recursive query.
How do you implement a many-to-many relationship between two tables in a relational database, and why can't a single foreign key column express it?
basics
~20 sUse a third table holding one foreign key to each side, keyed on the pair of them. A single foreign key column stores one value per row, so it cannot record many links from the same row.
What does a CHECK constraint do in a relational table, and at what point does the database engine evaluate it?
basics
~20 sA CHECK constraint is a boolean condition attached to a table. The engine tests it for every row a statement inserts or updates; if the condition comes out false, the statement fails with a constraint-violation error and the row is not stored.
If the application already validates every field before saving, why still declare constraints such as NOT NULL, unique keys and foreign keys in the database schema?
basics
~20 sBecause the application is not the only writer, and its checks are not atomic with the write. Scripts, migrations, other services and future bugs all reach the same tables. Database constraints are the last line of defense that no code path can bypass; app validation exists for fast, friendly feedback.
A column in one table references the key of another table under a foreign key constraint. What exactly does that constraint guarantee about the stored data, and what happens if the referencing column holds NULL?
basics
~20 sIt guarantees every non-NULL value in the referencing (child) column exists in the referenced (parent) key, so there are no orphan rows. A NULL referencing value points at nothing, so the check is skipped and the row is accepted.
A table column is declared NOT NULL with a DEFAULT value. Explain the difference between an INSERT that omits that column entirely and one that explicitly supplies NULL for it.
basics
~20 sOmitting the column makes the engine apply the DEFAULT, so the insert succeeds. Explicitly writing NULL is a real value being supplied — the DEFAULT is not consulted, and the NOT NULL constraint rejects the row.
What does declaring a primary key on a table actually guarantee, and how does a relational engine enforce that guarantee?
basics
~20 sA primary key guarantees every row has a value in those columns (no NULLs) and no two rows share the same combination. The engine enforces it by marking the columns NOT NULL and maintaining a unique index it probes on every insert and key update.
Atomicity is one of the four ACID properties of a database transaction. What does it guarantee, and what happens to the work a transaction has already done if it fails halfway through?
basics
~20 sAtomicity means a transaction is all-or-nothing: either every change it made becomes visible together, or none does. If it fails partway, the engine reverses the work already done, leaving the database as if the transaction never ran.
In the ACID acronym for database transactions, what does the C (consistency) actually guarantee, and who decides what 'consistent' means?
basics
~20 sC means a transaction moves the database from one valid state to another: every declared integrity rule (primary key, unique, not null, check, foreign key) holds at commit. The engine enforces the declared rules; the developer decides which rules to declare.
When a database returns success for a COMMIT, what exactly has it promised the client, and what has it not promised?
basics
~20 sIt promises the committed changes survive a crash or power loss of that node: the data reached stable storage, not just memory. It does not promise the data survives losing that machine or its disk, nor that any replica already has it.
What does the isolation property of ACID promise about transactions that run at the same time, and why do real database engines let you weaken that promise?
basics
~20 sIsolation means concurrent transactions must not see each other's unfinished work: the outcome should match some order where they ran one at a time. Enforcing that fully costs locking, blocking and aborts, so engines offer weaker levels that trade specific anomalies for throughput.
What is a dirty read in a relational database, and what can go wrong for the transaction that performed one if the writing transaction later rolls back?
basics
~20 sA dirty read is reading a row version written by a transaction that has not committed. If that writer rolls back, the value you read never existed in any committed state, so any decision, calculation or write you based on it is derived from data the database itself disowned.
A relational database can read the rows a query needs either by reading the whole table or by going through an index. Describe what physical work each of those two access paths performs, step by step.
basics
~20 sA full scan reads every page of the table in order and discards rows that do not match. An index scan descends the index to the matching keys, then follows each key's pointer to fetch that row's table page. Fewer rows touched, but scattered reads.
A table's live row count has been flat for months, yet queries served by one of its B+tree indexes keep getting slower. What can happen inside an index over time that explains this, even with no growth in live data?
basics
~20 sDeletes and updates leave dead entries and half-empty pages behind. The same live keys end up spread over more pages, so scans read more pages and each cached page carries less useful data. That is index bloat.
Why can a B+tree index efficiently return every row whose key falls within a range, and produce rows already in key order for an ORDER BY without a separate sort step? What property of the structure makes that possible?
basics
~20 sAll entries live in leaf pages, sorted by key, and the leaves are chained to their neighbours in key order. So the engine descends once to the first matching key and then walks the chain until the range ends, reading entries already in order.
Describe how a B+tree index is laid out in storage: what does an internal (branch) node contain versus a leaf node, and how does a key lookup use each of them?
basics
~20 sA B+tree is a balanced tree of page-sized nodes. Internal nodes store only separator keys and child pointers used to route a search downward. Leaf nodes store every indexed key in sorted order with a pointer to the row. A lookup descends root to leaf.
Explain the difference between a table whose rows are stored in a clustered (index-organized) structure and a table stored as a heap, and how each locates a row.
basics
~20 sIn clustered storage the table IS the index: rows live in the leaves of a B+tree ordered by the clustering key. In a heap, rows sit in unordered pages and are addressed by a physical row id, with every index a separate structure pointing at those ids.
The same amount of data is scanned by two queries, yet one starts returning rows almost immediately while the other returns nothing for several seconds and then delivers everything at once. What in the execution plan explains the difference?
basics
~20 sA fully pipelined plan passes each row up to the client as it is produced, so the first row arrives early. If the plan contains a blocking operator — a sort, a hash build, a grouping step — nothing can be emitted until that operator has read all its input, so results appear only at the end.
Describe how a naive nested loop join produces its result, and what its cost is in terms of the sizes of the two inputs.
basics
~20 sFor each row of the outer input, scan the entire inner input and emit the pairs that satisfy the join predicate. Comparisons are O(n*m), and the naive form re-reads the inner input once per outer row, so I/O is the real problem.
When a database sorts or groups a large result set, the plan may report that the operator "spilled to disk". What does spilling mean, what triggers it, and how does it show up in query performance?
basics
~20 sEach sort or grouping operator gets a limited memory budget. If the rows it must hold exceed that budget, the engine writes partial results into temporary files and reads them back later. Spilling replaces memory work with disk I/O, so latency jumps sharply.
Relational database optimizers are commonly described as either rule-based or cost-based. Explain the difference, and why essentially every modern relational engine chose the cost-based design.
basics
~20 sA rule-based optimizer applies a fixed priority list of heuristics regardless of the data. A cost-based optimizer enumerates alternative plans, estimates the cost of each from statistics about the data, and picks the cheapest. Cost-based wins because the right plan depends on data distribution, which rules cannot see.
What are optimizer statistics in a relational database, and what goes wrong when they are missing or out of date?
basics
~20 sThey are summaries of the data — row counts, distinct values per column, null fractions, common values, value distributions — that the query planner reads to guess how many rows each step will produce. Missing or stale statistics make those guesses wrong, so the planner picks a bad access path or join method and the query runs far slower.
What is a generated (computed) column in a relational table, and what is the practical difference between declaring it STORED and declaring it VIRTUAL?
basics
~20 sA column the engine derives from other columns of the same row via a fixed expression; you never write to it. STORED materializes the value on disk at write time (uses space, free to read, indexable). VIRTUAL stores nothing and recomputes it on every read.
What is a materialized view, how does it differ from an ordinary non-materialized view, and when would you introduce one?
basics
~20 sA materialized view stores the actual result rows of its query on disk, like a table. An ordinary view stores only the query text and recomputes it on every read. You trade freshness and storage for cheap reads of expensive queries.
What is a database sequence object, and how do IDENTITY columns and auto-increment/serial columns relate to it?
basics
~20 sA sequence is a standalone database object that hands out unique increasing numbers on request, independent of any table. An IDENTITY or serial column is a column wired to such a generator so inserts get a value automatically. Same machinery, different packaging.
In a relational database, what is the difference between a stored procedure and a stored function, and when would you reach for each?
basics
~20 sA function returns a value and is called inside an expression or query. A procedure is invoked by a CALL statement, returns data through output parameters or result sets, and in most engines may commit or roll back. Functions compute values; procedures perform units of work.
What is a temporary table in a relational database, and how do its visibility and lifetime differ from an ordinary table?
basics
~20 sA temporary table holds intermediate rows for one session (or one transaction). Its data is private to the creating session, it lives in a special temporary namespace, it is dropped automatically at session or transaction end, and it is typically unlogged and never crash-recovered.
What is a database engine's buffer pool, and why does the engine maintain its own in-memory page cache instead of simply reading and writing files through the operating system?
basics
~20 sA shared region of RAM holding fixed-size disk pages. All reads and writes go through it, so hot pages never touch disk. The engine caches itself because it knows access patterns and must control when a modified page may be written.
What is a checkpoint in a database storage engine, and what two problems would a system have if it never took one?
basics
~20 sA checkpoint flushes modified in-memory pages to disk and records a position in the transaction log. Without it, crash recovery would have to replay the log from the beginning, and the log could never be truncated, so it would grow forever.
Walk through what a relational database server does from the moment a client opens a TCP connection until that client can run its first SQL statement.
basics
~20 sTCP connect, a protocol handshake naming the database and user, an optional TLS upgrade, then authentication. The server allocates a session (a backend process or thread with its own memory), loads role metadata, and signals it is ready for queries.
Why do applications keep a pool of open database connections instead of opening a new connection for each request, and what does a pool actually do when code asks for one?
basics
~20 sOpening a connection costs a network handshake, authentication, and server-side setup - milliseconds plus memory - and the server can only hold a limited number. A pool keeps a bounded set of authenticated connections open, lends one to each unit of work, takes it back afterwards, and makes callers wait when all are busy.
After an unexpected server crash, a relational database keeps the effects of some transactions and throws others away. How does it decide which is which, and what does that mean for an application that already received a successful commit acknowledgement?
basics
~20 sThe transaction log decides. A transaction whose commit record reached durable storage before the crash is kept, and reapplied if needed. Every transaction without a durable commit record is rolled back completely. So an acknowledged commit survives; in-flight work disappears atomically, never half-applied.
A nightly database backup job has reported success every night for six months. What does that success signal actually prove, and what would you do before trusting those backups in a real outage?
basics
~20 sIt proves the job ran and wrote bytes somewhere. It does not prove the backup is complete, readable, or restorable. The only proof is restoring it onto a separate instance, starting the database, and querying the data.
Define Recovery Point Objective (RPO) and Recovery Time Objective (RTO) for a database, and give a concrete example of a system where the two numbers are very different.
basics
~20 sRPO is how much recent data you can afford to lose, measured in time before the failure. RTO is how long the system may stay unavailable before it is serving again. RPO is about data loss; RTO is about downtime.
Explain the difference between full, incremental, and differential backups of a relational database, and how each choice affects the backup window, storage cost, and restore time.
basics
~20 sA full backup copies everything. An incremental copies only what changed since the previous backup of any type. A differential copies everything changed since the last full. Incrementals are smallest to take but slowest to restore, because the whole chain must be replayed.
In a replicated database cluster with one primary and several standbys, what is split-brain, how does it arise during a failover, and what damage does it do to the data?
basics
~20 sSplit-brain is two nodes both believing they are primary and accepting writes, usually after a network partition hid a still-running primary. Their histories diverge, and reconciling them means discarding writes the application already saw committed.
What is the difference between a planned switchover and an unplanned failover in a primary/replica relational database setup, and how does each affect the risk of losing committed data?
basics
~20 sA switchover is a controlled role swap: writes are stopped, the replica catches up fully, then roles change with no data loss and the old primary can rejoin as a replica. A failover is reactive after a crash, so unreplicated commits can be lost.
A SaaS application stores data for many customer organizations in one relational database, and every table carries a tenant_id column naming the owning organization. Explain how that discriminator column is meant to work: what must be true of every query, of primary keys and indexes, and of unique and foreign-key constraints for the design to be correct?
basics
~20 stenant_id tags each row with its owning customer. Every read and write must filter on it, it should lead composite primary keys and indexes so a scan touches one tenant, unique constraints must include it, and foreign keys must stay inside one tenant.
When you create an index on a partitioned table, what is physically created, and how does that differ from indexing an ordinary non-partitioned table?
basics
~20 sOn a non-partitioned table you get one physical index over all rows. On a partitioned table, most engines build one physical index per partition, each covering only that partition's rows; the index you declared on the parent is just metadata tying them together.
What is partition pruning in a partitioned table, what does a query have to contain for the database to do it, and how is it different from using an index?
basics
~20 sPruning is the database eliminating partitions that cannot contain matching rows, using each partition's declared bounds. It needs a predicate on the partition key. An index narrows the search inside a table; pruning removes whole tables from the plan before any scan happens.
What does adding read replicas to a relational database actually scale, and what does it not scale?
basics
~20 sReplicas add read capacity: full copies of the data that can serve queries. They do not add write capacity — every replica must apply the same write stream as the primary — and with asynchronous replication their data is slightly behind, so reads can be stale.
A relational engine lets you declare one logical table as a set of physical child tables using RANGE, LIST or HASH. Explain what table partitioning is and what each of the three strategies is for.
basics
~20 sPartitioning splits one logical table into physical pieces inside the same database, chosen by a partition key. RANGE assigns contiguous intervals (usually dates), LIST assigns explicit value sets (region, status), HASH spreads rows evenly by a hash of the key.
What should a database audit trail record, and why is logging inside the application not considered sufficient for auditing database access?
basics
~20 sRecord who, what, which object, when, from where, and the outcome: logins and failed logins, DDL, privilege changes, and DML or reads on sensitive tables. App logs miss DBAs, tools and jobs that connect directly, and can be bypassed.
In a relational database, what is the difference between authentication and authorization, and at what point in a session is each one performed?
basics
~20 sAuthentication proves who is connecting. It happens once, during the connection handshake, using a password, an OS identity, a Kerberos ticket, or a client certificate. Authorization decides what that identity may do, and the server re-checks it on every statement afterwards.
What is dynamic data masking in a relational database — where the engine rewrites column values as they are read — and how does it differ from storing the data already redacted or tokenised?
basics
~20 sDynamic masking keeps the true value stored and applies a masking function at query time based on who is asking, so privileged roles still see the original. Write-time redaction or tokenisation changes what is stored, so the original cannot leak from that table at all.
At which layers can a relational database's data be encrypted at rest — storage volume or filesystem, database engine, and application or column level — and what fundamentally differs between them?
basics
~20 sVolume or filesystem encryption protects whole disks and is invisible to the database. Engine-level Transparent Data Encryption encrypts the database's own files and backups. Application or column encryption encrypts values before storage, so even the database never sees plaintext — but indexing and range queries break.
When a client application connects to a relational database over TLS, what exactly is protected, and which threats does that encryption not address?
basics
~20 sTLS protects the wire: credentials, SQL text, parameters and result rows cannot be read or silently altered by anyone on the network path, and the client can verify it reached the real server. It does nothing for data on disk, backups, in-database authorization, or a compromised host.