Database developer interview questions: live SQL, schema design, procedures and migrations
Database developer interview questions test whether you can design a schema that holds up, write correct set-based SQL under time pressure, build stored procedures and migrations that are safe to run in production, and explain why a slow query is slow. Expect a live SQL task, a schema design exercise from a short business description, and questions on transactions, indexing from the query's point of view, and how you ship database changes without breaking the application.
By Evin JohnPublished 12 min read
What a database developer is hired to do
A database developer owns the data layer of an application or a group of applications. The work is schemas and tables, keys and constraints, views, stored procedures, functions and triggers where the team uses them, the queries behind reports and APIs, and the migration scripts that move a production database from one version to the next. The same title can lean toward an application team (an OLTP database behind a product), toward reporting (read-heavy queries and extracts), or toward a legacy estate full of procedural code in T-SQL or PL/SQL that needs careful changes.
It is not the same job as database administration. A DBA keeps the server healthy: backups, restores, replication, patching, capacity and access. The developer makes sure what runs on that server is correct and efficient. The two overlap on performance and change control, which is why interviewers often ask how you work with the DBA. If the posting is mostly backups and high availability, read the database administrator guide. If it is mostly pipelines and loads into a warehouse, the ETL developer guide fits better, and the SQL question bank covers the query language itself in more depth.
- Correct SQL first: results that stay right with duplicates, NULLs, ties and empty tables.
- Design that protects data: keys, foreign keys, check constraints and types chosen so bad data cannot get in.
- Set-based thinking: one statement that handles a thousand rows instead of a loop that handles one at a time.
- Performance awareness: knowing which index a query needs and what a plan is telling you.
- Safe delivery: scripted, reviewed, versioned changes that can run on a busy production system.
How database developer interviews are usually structured
- Recruiter screenWhich engines you have used and for how long, the size of the databases, whether you wrote procedures or mostly queries, and your salary and notice details.
- Technical screenKnowledge questions on joins, keys, indexes, transactions and isolation, often with one or two short queries written in a shared editor.
- Live SQL or take-home taskSeveral query problems against a small schema, sometimes with a timer. Some teams instead send a take-home with a schema to design and procedures to write.
- Design and tuning roundModel a small business domain on a whiteboard, then reason about a slow query or a plan the interviewer shows you.
- Team and behavioral interviewHow you review changes, handle a production incident caused by a migration, and work with application developers, analysts and the DBA.
Ask the recruiter which engine the live task uses. Window functions and joins are portable, but upserts, date functions, string functions and procedural syntax differ between SQL Server, PostgreSQL, Oracle and MySQL. Saying "in T-SQL I would use MERGE here, in PostgreSQL INSERT with ON CONFLICT" earns credit when you are unsure which one the grader expects.
Schema design and modeling questions
| Question | What it tests | What a strong answer shows |
|---|---|---|
| Design tables for a clinic that books patients with doctors in rooms. | Modeling from a brief | Asks questions first (can a booking span two rooms? are cancellations kept?), names entities and relationships, then keys and the constraint that stops double booking |
| When would you choose a surrogate key over a natural key? | Key design | Natural keys change or get reused (emails, product codes); a surrogate keeps joins stable while a unique constraint still protects the business key |
| Explain third normal form using a table you have worked with. | Normalization | Shows a real redundancy, the update anomaly it caused, and the split that fixed it, instead of reciting definitions |
| When is denormalizing the right call? | Trade-offs | Read-heavy reporting or a hot path where a join is measured as the bottleneck, with a plan to keep the copy consistent |
| How do you store money, and why not a float? | Types | Exact decimal types or integer minor units, because binary floating point cannot represent many decimal amounts and rounding errors add up |
| How would you model a status that changes over time and must be audited? | History | A history table or effective-dated rows with valid-from and valid-to, plus who changed it, rather than overwriting one column |
| A product can have any number of custom attributes. How do you store them? | Flexible data | Weighs a JSON column, an attribute table and extra typed columns against query patterns and validation needs |
| What constraints would you add to an orders table, and where would you not rely on the application? | Integrity | NOT NULL, foreign keys, check constraints on quantity and status, unique business keys; the database is the last line of defence when several apps write to it |
Live SQL questions you should be able to write
Most live tasks use a schema of three to five tables and ask for five to eight results of rising difficulty. Talk while you write: say what the grain of each intermediate result is, and test the edge cases out loud (a customer with no orders, two orders at the same timestamp, a NULL amount).
- Return each customer's most recent order, with ties broken predictably. Number the rows per customer with a window function and keep row one. Mention the tie-breaker column.
- List customers who placed no order in a given month. Use NOT EXISTS, and explain why NOT IN breaks when the subquery can return a NULL.
- Show a running total of spend per customer. A windowed SUM with an explicit frame, ordered by date plus a unique column so equal dates do not jump together.
- Insert new prices and update existing ones in one statement. An upsert: MERGE in SQL Server and Oracle, INSERT ... ON CONFLICT in PostgreSQL and SQLite, INSERT ... ON DUPLICATE KEY UPDATE in MySQL.
- Find gaps in a sequence of invoice numbers. Compare each number with the next one using LEAD, or join to a generated series where the engine has one.
- Delete duplicate rows but keep the oldest of each group. Rank within the duplicate key and delete everything after the first, after checking the count with a SELECT.
- Pivot monthly sales into one column per month. Conditional aggregation with SUM(CASE ...) works everywhere; PIVOT syntax is engine-specific.
- Walk an employee-to-manager hierarchy. A recursive CTE with a depth column and a guard against cycles.
-- Latest order per customer (ties broken by order_id)
SELECT customer_id, order_id, ordered_at, amount
FROM (
SELECT o.*,
ROW_NUMBER() OVER (
PARTITION BY customer_id
ORDER BY ordered_at DESC, order_id DESC
) AS rn
FROM orders AS o
) AS ranked
WHERE rn = 1;
-- Customers with no order in February 2026 (safe with NULLs)
SELECT c.customer_id, c.name
FROM customers AS c
WHERE NOT EXISTS (
SELECT 1
FROM orders AS o
WHERE o.customer_id = c.customer_id
AND o.ordered_at >= '2026-02-01'
AND o.ordered_at < '2026-03-01'
);
-- Upsert that only moves a price forward in time (PostgreSQL / SQLite syntax)
INSERT INTO product_price (sku, price, updated_at)
VALUES ('A-1', 11.00, '2026-03-01')
ON CONFLICT (sku) DO UPDATE
SET price = excluded.price,
updated_at = excluded.updated_at
WHERE excluded.updated_at > product_price.updated_at;The date filter uses a half-open range (from the first of the month up to, but not including, the first of the next) so it works for date and timestamp columns alike and lets an index on the date be used. Wrapping the column in a function such as MONTH(ordered_at) = 2 is also wrong once the table holds more than one year, since it matches every February, and it usually stops the index from being used.
Stored procedures, functions and triggers
| Question | What it tests | What a strong answer shows |
|---|---|---|
| When do you put logic in a stored procedure instead of the application? | Architecture judgment | Data-heavy work close to the data, shared rules several apps must obey, or security through granting execute rights; and the costs: harder testing, vendor lock-in, deployment coupling |
| Rewrite this cursor that updates rows one at a time. | Set-based thinking | Turns the loop into a single UPDATE with a join or a window, and explains the difference in logging and locking |
| How do you handle errors inside a procedure that changes several tables? | Transactions | One transaction, TRY/CATCH or an exception block, rollback on failure, re-raise with context, and no swallowed errors |
| What are the risks of triggers? | Side effects | Hidden logic, surprise performance costs on bulk loads, recursion, and ordering issues; acceptable for auditing or enforcing a rule nothing else can |
| A procedure is fast for one customer and very slow for another. Why? | Plan reuse | A cached plan built for a small parameter value is reused for a huge one; options include recompiling, plan hints or splitting the logic, chosen after looking at both plans |
| How do you avoid SQL injection in dynamic SQL? | Security | Parameters instead of string concatenation, a whitelist for object names, and quoting functions for identifiers |
| How do you unit test a stored procedure? | Quality | Set up known data in a transaction, call the procedure, assert on results and side effects, roll back; frameworks exist for several engines, or plain scripts in CI |
Query tuning from the developer's side
- A report query went from two seconds to two minutes after a data load. Where do you start? Get the actual plan, compare estimated and actual row counts, check whether statistics are stale, and look for a scan where a seek used to be.
- Which index would you build for WHERE customer_id = ? AND status = ? ORDER BY created_at DESC? A composite index on customer_id, status and created_at, in that order, so the filter and the sort are both served. Explain why column order matters.
- What makes a predicate sargable? The column is compared directly, without a function or an implicit type conversion on it, so the engine can seek into an index.
- What is a covering index, and what does it cost? It holds every column the query needs, so the table is never touched; the price is extra storage and slower writes.
- **Why can SELECT * hurt in application code?** It blocks covering indexes, sends unused data over the network, and breaks callers when a column is added or reordered.
- How do you find the queries worth tuning? Rank by total time across all executions, not by the single slowest run, using the engine's query statistics or the application's tracing.
- When would you not add an index? On a write-heavy table where the query is rare, or when an existing index can be widened instead of adding another.
- The ORM generates hundreds of small queries for one page. What is happening? An N+1 pattern; load related rows in one query or a join, and check what the ORM actually sends.
Transactions and concurrency for developers
- Two users book the last seat at the same time. How do you stop overselling? A unique constraint or a conditional UPDATE that checks remaining stock and reports how many rows changed, inside a transaction; do not read, decide in the app, then write.
- What does each isolation level protect against? Dirty reads, non-repeatable reads and phantoms, and what your engine's default is. Mention snapshot or MVCC behavior if your engine uses it.
- What causes a deadlock, and how do you reduce them? Two transactions locking the same resources in opposite order; access tables in a consistent order, keep transactions short, index the lookups, and retry the victim.
- Why should a transaction never wait on user input or a slow API call? It holds locks the whole time and blocks everyone else.
- What is optimistic concurrency? A version or timestamp column checked on update; if another writer changed the row first, zero rows update and the app tells the user.
Migrations and shipping database changes
Senior candidates are judged heavily here, because a bad migration can take an application down or lose data. Expect questions about the tools you used (migration frameworks, database projects, or plain numbered scripts) and, more importantly, the rules you follow.
- How do you rename a column on a table the live application reads? In steps: add the new column, write to both, backfill in batches, switch reads, then drop the old column in a later release.
- How do you add a NOT NULL column to a very large table? Add it as nullable or with a default the engine can apply without rewriting every row, backfill in batches, then add the constraint. Check how your engine version handles defaults.
- Where do database scripts live? In version control next to the application code, reviewed in pull requests, applied by the pipeline, never typed by hand into production.
- What is your rollback plan for a migration? A tested down script where possible; for destructive changes, a backup or a copy of the affected data and a decision about rolling forward instead.
- How do you keep development, test and production schemas from drifting? Every change goes through migrations, and a check in CI compares the schema the scripts produce with what is deployed.
Fictional example
- Interviewer
- Tell me about a database change that went wrong in production.
- Candidate
- At a logistics company I added an index to the shipments table to speed up a tracking screen. In test it took seconds. In production the table was about forty times bigger, the index build locked writes, and label printing in two warehouses stalled for several minutes.
- Candidate
- I cancelled the build with the DBA, confirmed writes recovered, and posted an update in the incident channel. The next night we built it with the engine's online option during the quiet window, and it finished without blocking.
- Candidate
- The fix that mattered was the process. I added a step to our migration checklist: check the row count in production, and flag any index or column change on large tables for an online build or a maintenance window. Our test environment also got a nightly copy of production volumes with personal data masked.
Behavioral and collaboration questions
- An application developer wants to drop a foreign key because inserts are failing. What do you say? Find out why inserts fail (often ordering or bad data), fix that, and keep the constraint that protects integrity.
- Tell me about a time you pushed back on a schema an architect proposed. Show the concern with evidence, the alternative, and how the decision was reached.
- How do you review another developer's SQL? Correctness with edge cases first, then the plan on realistic data, then naming and readability.
- How do you explain a data issue to a business user? What is wrong, which reports are affected, since when, and when it will be fixed, in plain words.
- Describe working with a DBA during an outage. Clear roles, shared facts, and no blame while the system is down.
Questions to ask the team
- Which engines and versions are in production, and is any migration between them planned?
- How much business logic lives in procedures versus application code?
- How are schema changes reviewed and deployed today?
- Who is on call for database incidents, and how are developers involved?
A ten-day preparation plan
- Days 1 to 3: live SQLWrite two problems a day by hand against a small schema you create: windows, anti-joins, upserts, gaps, duplicates, pivots and a recursive CTE. Run each on a free local engine.
- Days 4 and 5: designModel three small domains from a one-paragraph brief, with keys and constraints, and say out loud why each table exists.
- Day 6: proceduresRewrite a cursor as a set-based statement, add error handling and a transaction, and write a test for it.
- Day 7: tuningRead real execution plans in your main engine, add an index, and compare. Practice explaining sargability and column order.
- Day 8: migrationsWrite the steps for a zero-downtime column rename and a large backfill. Prepare one incident story.
- Days 9 and 10: mock roundsOne timed live SQL session and one design discussion with a friend or mentor, followed by a review of what you said.
For the live SQL round, practice talking and typing at the same time. Natively, an AI interview assistant for Mac and Windows, can sit in on a mock session: it transcribes the conversation on your computer, can read a query problem from a screenshot and suggest an approach, and keeps the transcript so you can check afterward whether you named the grain, the tie-breaker and the NULL case before running anything. With Pro or the free trial it can also take your résumé and the job description into account.
Questions people ask
What questions are asked in a database developer interview?
Expect a live SQL task (window functions, anti-joins, upserts, duplicates, recursive queries), a schema design exercise, questions on stored procedures and error handling, query tuning and indexes, transactions and isolation, and how you ship schema changes safely.
What is the difference between a database developer and a DBA interview?
A database developer interview tests schema design, SQL and procedural code, query tuning and migrations. A DBA interview focuses on backups, restores, high availability, security and server health, with tuning as the shared ground.
How do I prepare for a live SQL test as a database developer?
Practice writing queries by hand against a small schema you build yourself, say the grain and edge cases out loud, and learn the upsert and date syntax of the engine the employer uses.
What do interviewers look for in a senior database developer?
Designs that protect data integrity, set-based SQL instead of row-by-row loops, the ability to read a plan and choose an index, and a disciplined, reversible way of deploying database changes.
Where to go next
Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.
Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.
