33.7. Database Interview Questions
Table of Contents
Types of Database Interview Questions
Database interview questions usually fall into a few categories:
- Fundamental concepts
- SQL and querying
- Schema design and relationships
- Performance and indexing
- Transactions and consistency
- Applied / scenario questions
You will rarely get only one type. Most backend interviews mix them to see how you think about data and trade-offs.
In this chapter we will not re-teach databases or SQL. Instead we will focus on what you might be asked and how to answer with clarity and confidence, plus example answers.
Fundamental Concept Questions
Relational vs NoSQL
Typical questions:
- What is the difference between relational and NoSQL databases?
- When would you choose one over the other?
Example answer structure:
- Explain the core idea
- Relational: tables, rows, columns, fixed schema, SQL.
- NoSQL: document, key–value, wide-column, graph, flexible schema.
- Highlight strengths and weaknesses
- Give simple use cases
Example concise answer:
A relational database stores data in tables with a fixed schema and supports SQL and ACID transactions. It is ideal when data is structured and relationships are important, for example orders, users, payments.
NoSQL is a group of databases with more flexible schemas, for example document stores like MongoDB, key value stores like Redis, column stores, and graph databases. They trade some relational features for flexibility or scalability. They work well for large, semi-structured data, caching, or when the schema evolves quickly.
Primary key and foreign key
Typical questions:
- What is a primary key?
- What is a foreign key?
- Why are they important?
Example answer:
A primary key uniquely identifies each row in a table. It must be unique and not null.
A foreign key is a column, or set of columns, in one table that refers to the primary key of another table. The database can enforce referential integrity with foreign key constraints, so you cannot have child rows pointing to non-existent parent rows.
Normalization
Typical questions:
- What is normalization?
- Why normalize a database?
- What is denormalization and when is it useful?
You do not need to recite formal definitions of every normal form. Focus on the goal and trade-offs.
Example answer:
Normalization is the process of structuring tables so that each fact is stored only once, which reduces redundancy and update anomalies.
For example, instead of storing a customer address in every order row, you store customer data in a Customers table, and orders reference the customer with a foreign key.
Denormalization is the opposite, where you intentionally duplicate some data, for example storing the customer name in the Orders table, to speed up reads or simplify queries. It is useful in analytics or high-read workloads, but it makes writes and updates more complex.
ACID properties
Typical question:
- What are ACID properties in databases?
ACID properties:
- Atomicity: each transaction is all or nothing
- Consistency: a transaction brings the database from one valid state to another
- Isolation: concurrently running transactions do not interfere in a way that breaks correctness
- Durability: once a transaction is committed, its data is persisted even after crashes
You can give a short example about transferring money between accounts to illustrate atomicity, isolation, and consistency.
SQL and Query Questions
Almost every backend interview includes at least one SQL problem. They test if you can think in sets and joins.
Basic CRUD SQL
Typical questions:
- Write a query to select users who signed up last week.
- Insert a new row into the Orders table.
- Update a user email.
- Delete inactive users.
You should be comfortable writing simple and readable SQL quickly.
Example schema:
users(id, email, created_at, status)
orders(id, user_id, amount, created_at)Example answers:
Select users from last 7 days:
SELECT id, email
FROM users
WHERE created_at >= NOW() - INTERVAL '7 days';Insert:
INSERT INTO users (email, created_at, status)
VALUES ('alice@example.com', NOW(), 'active');Update:
UPDATE users
SET email = 'new@example.com'
WHERE id = 123;Delete:
DELETE FROM users
WHERE status = 'inactive';You will not always have these exact columns, but the pattern is the same.
JOIN questions
Very common questions:
- What types of JOINs do you know?
- Write a query to list all users and their total order amount.
- Difference between INNER JOIN and LEFT JOIN?
Table of basic join types:
| Join type | Returns |
|---|---|
| INNER JOIN | Rows where join condition matches in both |
| LEFT JOIN | All rows from left table, plus matching right |
| RIGHT JOIN | All rows from right table, plus matching left |
| FULL OUTER JOIN | All rows from both, with nulls where missing |
| CROSS JOIN | Cartesian product of two tables |
Example question:
Givenusers(id, email)andorders(id, user_id, amount), write a query to get each user with their total order amount, including users who have no orders.
Answer:
SELECT
u.id,
u.email,
COALESCE(SUM(o.amount), 0) AS total_amount
FROM users u
LEFT JOIN orders o ON o.user_id = u.id
GROUP BY u.id, u.email;Key points to mention:
- Use
LEFT JOINto include users who have no orders. - Use
GROUP BYto aggregate. - Use
COALESCEto treatNULLas 0.
Aggregation and GROUP BY
Typical questions:
- Count orders per user.
- Average order value by day.
- Top N users by spend.
Example queries:
Orders per user:
SELECT user_id, COUNT(*) AS order_count
FROM orders
GROUP BY user_id;Average order amount by day:
SELECT
DATE(created_at) AS day,
AVG(amount) AS avg_amount
FROM orders
GROUP BY DATE(created_at)
ORDER BY day;Top 5 users by total spend:
SELECT
user_id,
SUM(amount) AS total_amount
FROM orders
GROUP BY user_id
ORDER BY total_amount DESC
LIMIT 5;Common filter patterns
You may be asked things like:
- Get users who have never placed an order.
- Get users who placed at least one order in the last 30 days.
Users with no orders:
SELECT u.*
FROM users u
LEFT JOIN orders o ON o.user_id = u.id
WHERE o.id IS NULL;Users with recent orders:
SELECT DISTINCT u.*
FROM users u
JOIN orders o ON o.user_id = u.id
WHERE o.created_at >= NOW() - INTERVAL '30 days';Be prepared to use:
JOIN,LEFT JOINGROUP BYandHAVINGDISTINCT- Date filters like
NOW() - INTERVAL '30 days'
Schema Design and Relationships
Here you are tested on how you model data.
One-to-many and many-to-many
Typical questions:
- How do you model one-to-many in a relational database?
- How do you model many-to-many?
Example explanation:
- One-to-many: a foreign key on the “many” side.
- One user, many orders:
orders.user_idreferencesusers.id. - Many-to-many: a junction table (also called join table or association table).
- Many products in many orders.
Schema example:
users(id, email, ...)
products(id, name, ...)
orders(id, user_id, created_at, ...)
order_items(
order_id REFERENCES orders(id),
product_id REFERENCES products(id),
quantity,
PRIMARY KEY (order_id, product_id)
)
You can mention that the primary key can be (order_id, product_id) if each product appears at most once per order. If not, use a separate id.
Example design question: blog system
Question:
Design the database tables for a simple blog with users, posts, and comments.
Good minimal design:
users(
id SERIAL PRIMARY KEY,
email TEXT UNIQUE NOT NULL,
name TEXT NOT NULL
)
posts(
id SERIAL PRIMARY KEY,
author_id INTEGER NOT NULL REFERENCES users(id),
title TEXT NOT NULL,
content TEXT NOT NULL,
created_at TIMESTAMP NOT NULL DEFAULT NOW()
)
comments(
id SERIAL PRIMARY KEY,
post_id INTEGER NOT NULL REFERENCES posts(id),
author_id INTEGER NOT NULL REFERENCES users(id),
content TEXT NOT NULL,
created_at TIMESTAMP NOT NULL DEFAULT NOW()
)Explain:
- One-to-many: user to posts, user to comments, post to comments.
- Foreign keys enforce relationships.
- Add indexes on
posts.author_id,comments.post_id,comments.author_idfor performance.
Example design question: e-commerce cart
Question:
How would you design the schema for a shopping cart?
Simple design:
users(
id SERIAL PRIMARY KEY,
...
)
products(
id SERIAL PRIMARY KEY,
name TEXT NOT NULL,
price NUMERIC(10,2) NOT NULL
)
carts(
id SERIAL PRIMARY KEY,
user_id INTEGER NOT NULL REFERENCES users(id),
status TEXT NOT NULL -- 'active', 'converted', etc.
)
cart_items(
id SERIAL PRIMARY KEY,
cart_id INTEGER NOT NULL REFERENCES carts(id),
product_id INTEGER NOT NULL REFERENCES products(id),
quantity INTEGER NOT NULL CHECK (quantity > 0),
UNIQUE(cart_id, product_id)
)Here you can mention:
- Why
UNIQUE(cart_id, product_id)is helpful, so each product appears at most once per cart. CHECKconstraint ensuresquantity > 0.
Indexing and Performance Questions
You will often get high level or practical questions about indexes, query performance, and trade-offs.
What is an index?
Typical question:
- What is a database index and why is it used?
Example answer:
An index is a data structure that a database uses to speed up queries on certain columns. You can think of it like the index in a book. Instead of scanning every row, the database looks up the index to quickly find matching rows.
Indexes makeWHERE,JOIN, andORDER BYoperations faster on the indexed columns, but they add overhead on writes, since the index must be updated when data changes.
You can mention that a B-tree index is the default in many relational databases, and that there are other types, for example hash, GIN, GiST in PostgreSQL.
When to add an index
Typical question:
- Given this query, what index would you add?
- How can you make this query faster?
Example query:
SELECT *
FROM orders
WHERE user_id = 123
AND created_at >= '2024-01-01'
ORDER BY created_at DESC
LIMIT 20;Good index:
CREATE INDEX idx_orders_user_created_at
ON orders(user_id, created_at DESC);Reasoning you can explain:
- The query filters on
user_idand date, and orders bycreated_at. - A composite index on
(user_id, created_at)lets the database efficiently find and sort rows for that user, most recent first. - The index order matches the
ORDER BY.
Index trade-offs
Typical questions:
- What are the downsides of too many indexes?
- Why not index every column?
Points you can mention:
- Each index needs storage.
- Inserts, updates, deletes become slower, because each index must be updated.
- More indexes can make the optimizer choose suboptimal plans or increase maintenance time.
A good line to use:
Index read-heavy columns that appear often inWHERE,JOIN, orORDER BYclauses, but be careful not to index everything, because each index slows down writes.
Transactions, Isolation, and Concurrency
Backend roles often involve concurrent access to the database. Interviewers may ask about race conditions and how to avoid them.
Basic transaction concept
Typical question:
- What is a transaction?
- Why use transactions?
Example answer:
A transaction is a group of database operations that are treated as a single unit. Either all of them succeed and are committed, or if something fails they are rolled back so that none of them take effect. This helps keep data consistent, for example when transferring money between accounts.
Isolation levels
You may be asked:
- What problems can happen when many transactions run concurrently?
- What is an isolation level?
At a junior to mid level, you should know:
- Read phenomena: dirty read, non-repeatable read, phantom read.
- Standard isolation levels:
- Read uncommitted
- Read committed
- Repeatable read
- Serializable
You do not need a deep internal explanation. Focus on practical understanding.
Example answer:
Isolation levels control how much concurrent transactions can see each other intermediate changes.
At read committed, which is a common default, each query sees only committed data, so there are no dirty reads, but repeated reads in the same transaction can return different results.
At repeatable read, once you read a row, you keep seeing the same version within the transaction, which prevents non-repeatable reads.
At serializable, the database behaves as if transactions ran one after another, which is the safest but can cause more conflicts and rollbacks.
You can add a one sentence example of a race condition, for example two users trying to update the same inventory count at the same time.
Handling race conditions
Typical scenario question:
You have a table products(id, stock). How do you safely decrement stock when a user makes a purchase, so that you never oversell?
Possible answers:
- Use a transaction and row-level lock:
BEGIN;
SELECT stock
FROM products
WHERE id = 42
FOR UPDATE;
-- Check stock in application code. If enough:
UPDATE products
SET stock = stock - 1
WHERE id = 42;
COMMIT;- Use a single atomic update:
UPDATE products
SET stock = stock - 1
WHERE id = 42
AND stock > 0;Then check the affected rows count in the application:
- If 1 row updated, purchase is successful.
- If 0 rows updated, no stock.
Explain why this is safe:
- The condition
stock > 0is checked by the database in one atomic step, so two concurrent requests cannot both reduce stock below zero.
Applied and Scenario Questions
These questions test if you can use concepts to solve real problems.
Example: logging and analytics
Question:
You collect user events (page views, clicks) at very high volume for analytics. Would you use a relational database or something else?
A reasonable junior to mid answer:
For very high volume event logging, a traditional relational database can become expensive and hard to scale, especially for write-heavy workloads and large historical data.
A more common approach is to use a log or columnar / analytics store, for example Kafka plus a data warehouse or a time series / columnar database.
For a small system or MVP, it might still be acceptable to use PostgreSQL with partitioned tables, then later move to a more specialized solution as volume grows.
The exact tool is less important than the reasoning: separation between OLTP (transactional) and OLAP (analytics) workloads.
Example: soft delete vs hard delete
Question:
How would you implement soft deletes? When would you use them?
Answer outline:
- Hard delete: row removed from table.
- Soft delete: row kept with a flag, for example
deleted_attimestamp oris_deletedboolean. - Add default filters
WHERE deleted_at IS NULLin queries. - Good for audit, restore, and compliance.
- But it can complicate queries and indexing.
Example schema:
users(
id SERIAL PRIMARY KEY,
email TEXT UNIQUE NOT NULL,
deleted_at TIMESTAMP NULL
)Default query pattern:
SELECT *
FROM users
WHERE deleted_at IS NULL;Example: handling large tables
Question:
What would you do if a table becomes very large and queries slow down?
Things you can mention:
- Add or improve appropriate indexes.
- Use query optimization, for example only select needed columns.
- Use pagination (
LIMIT/OFFSETor keyset pagination). - Partition the table by date or tenant if the database supports it.
- Archive old data to cheaper storage.
- Analyze query plans (for example
EXPLAIN ANALYZEin PostgreSQL).
You are not expected to be a performance expert, but you should show that you know where to start.
How to Approach Database Questions in Interviews
Beyond knowing content, you should practice how to think aloud. Here are practical strategies.
Clarify requirements
When given a schema or design question, ask:
- Read vs write heavy?
- Expected scale? Thousands vs millions of rows?
- Do we need history or audit of changes?
- Are strong relationships important, or is flexibility more important?
This shows that you care about trade-offs.
Example clarification:
For this e-commerce database, roughly how many orders per day do we expect? Are we focusing more on operational queries or analytics?
Think from queries back to schema
A helpful mindset:
“Design the schema so that the most common queries are simple and fast.”
So ask yourself:
- Which queries must be fast and simple?
- How often do they run?
- Which filters and joins appear often?
Then choose:
- Table structure.
- Indexes.
- Possible denormalization.
Use simple and consistent naming
When you write SQL or schemas during the interview:
- Keep table names plural or singular, but be consistent.
- Use clear column names, for example
user_id,created_at,updated_at. - Avoid overly clever names.
Clear code is easier for the interviewer to follow.
Validate your SQL
Even in an interview, quickly check:
- Do I have the correct
JOINtype? - Did I add required
GROUP BYcolumns? - Are there cases where the result might be
NULLand should useCOALESCE? - Does the query return duplicates? Do I need
DISTINCT?
Say your checks aloud:
I am doing aLEFT JOINbecause I still want users without orders. I will group byu.id, u.email. To ensure users with no orders get 0 instead of null, I will useCOALESCE(SUM(o.amount), 0).
This reassures the interviewer that you understand the result shape.
Practice Ideas Before Interviews
To feel comfortable with database questions, you can practice in a focused way.
Practice SQL
Pick any SQL-friendly environment, for example:
- PostgreSQL in Docker
- An online SQL playground
- A local database with sample tables
Then:
- Create 3–4 tables, for example
users,orders,order_items,products. - Write queries for:
- Users with no orders
- Top N spending users
- Average order size per month
- Products that were never ordered
- Last order per user
- Try to solve each in more than one way, for example with:
JOIN+GROUP BY- Subqueries
NOT EXISTS
Practice schema design
Pick small domains:
- Blog / comments
- To-do app
- E-commerce
- School / students / courses
- Social network (users, friendships, posts, likes)
For each:
- List the main entities and relationships.
- Identify one-to-many and many-to-many.
- Draw tables with primary and foreign keys.
- List 3–5 most important queries.
- Decide which columns to index.
Practice explaining trade-offs
Pick questions like:
- Why relational database vs NoSQL for this system?
- Why normalize vs denormalize?
- Why soft delete vs hard delete?
Practice answering in 3 parts:
- Define both options.
- Compare advantages and disadvantages.
- Give a simple example decision.
For example:
For an inventory system where consistency is critical and data is structured, I would pick a relational database like PostgreSQL. It gives strong ACID guarantees, transactions, and joins.
For a logging system with very high write throughput and less strict schemas, I might use a NoSQL or analytics store to handle volume and schema evolution more easily.
By focusing on these patterns and practicing both content and communication, you will be ready for most database-related questions in backend interviews.
Views: 7
KAHIBARO