SQL interview questions
47 questions, easy to hard. Read one, then answer it out loud: an AI interviewer follows up, hints when you're stuck and grades your answer.
SQL and database interviews cover queries and joins, indexes and performance, transactions and locking, schema design, NoSQL and analytics queries.
SQL Basics
You have a customers table with a name, a country and a sign-up date. Explain, in words, how you'd write a query that lists the names of customers from France who signed up this year, newest first, and what each part of the query does.
What a strong answer covers
- What each clause of a basic query is responsible for, in the order you'd say it aloud.
- How several conditions are joined so that every one of them must hold.
- How to ask for a particular ordering, and in which direction.
- What you can and can't assume about row order when you don't ask for one.
Common mistake: Assuming results come back in insertion order, which happens to work in testing and then breaks unpredictably.
- Count, Sum and Average
- easy
- Pro
An orders table has a customer, an amount and a status. Explain how you'd find the number of orders, the total revenue and the average order value, and how counting all rows differs from counting a column that is sometimes empty.
What a strong answer covers
- How aggregate functions turn a set of rows into a single figure.
- The difference between counting rows and counting values in a column.
- How missing values quietly change totals and averages.
- Deciding which rows should be in scope before you aggregate.
Common mistake: Treating an empty value as zero, then being surprised when the average doesn't match total divided by count.
- Group By Explained
- easy
- Pro
Your manager wants total revenue per country from an orders table. Explain how group by works, what it does to the rows, and why every column you select must either be grouped or aggregated.
What a strong answer covers
- What grouping does to the shape of the result.
- Where each aggregate gets calculated once groups exist.
- Why some columns can't simply be listed alongside an aggregate.
- A clear spoken outline of the query that answers the manager's question.
Common mistake: Adding extra columns to the select list without thinking, then either getting an error or a group per unique combination.
- Where or Having?
- medium
- Pro
You need the customers who placed more than five completed orders. Explain the difference between where and having, which conditions belong in each, and the order in which the database applies them.
What a strong answer covers
- The two different moments at which rows can be filtered.
- Telling apart a condition about one row from a condition about a whole group.
- The logical order in which the database works through a query's clauses.
- Why filtering early is usually the cheaper choice.
Common mistake: Putting every condition in having because it works, which makes the database group rows it could have thrown away first.
- The Trouble with Null
- medium
- Pro
A query for users whose referral code is not equal to a particular value unexpectedly leaves out users with no referral code at all. Explain how null behaves in comparisons and how you'd fix the query.
What a strong answer covers
- What a missing value means in SQL and how comparisons treat it.
- Which comparison outcomes a filter keeps and which it drops.
- The dedicated way to test for missing values, and how to fold it into the condition.
- At least one other place where missing values cause surprising results.
Common mistake: Expecting not equal to behave like ordinary logic, so rows with no value silently vanish from the result.
A colleague wrote a long query with three levels of nested subqueries to find customers whose spending is above the average. Explain what a subquery is, what a common table expression, or with clause, is, and how you'd rewrite the query to be easier to read.
What a strong answer covers
- What a query nested inside another can stand in for.
- How a named, temporary result at the top of a query works.
- Breaking a tangled problem into a few readable, named steps.
- A realistic view of what restructuring does, and doesn't, do for speed.
Common mistake: Claiming that rewriting with a with clause automatically makes the query faster.
- Window Functions
- hard
- Pro
You need each customer's three most recent orders, and a running total of revenue by day. Explain what window functions are, how they differ from group by, and how you'd use them for both tasks.
What a strong answer covers
- How a window calculation differs from collapsing rows into groups.
- How rows are split up and ordered inside a window.
- An approach to keeping only the top few rows per customer.
- How a cumulative total is built up row by row.
- Where a filter on a window result has to go.
Common mistake: Trying to filter on a window function's result in the same where clause that defines it.
Joins
You have a customers table and an orders table, linked by a customer ID on each order. Explain the difference between an inner join and a left join between them, and which you'd use to list every customer with their order count, including those who have never ordered.
What a strong answer covers
- What each join type keeps when a row has no partner.
- What the unmatched side of a result looks like.
- Which join suits a list that must include everyone.
- How the choice of what you count changes the numbers for people with no orders.
Common mistake: Using an inner join for a report that's meant to include everyone, so inactive customers silently disappear.
- Find the Missing Rows
- easy
- Pro
Marketing wants a list of customers who have never placed an order. Explain two ways to find rows in one table that have no matching row in another.
What a strong answer covers
- A join-based way to find rows without a partner.
- An existence-check way to ask the same question.
- Picking the right column to test so the check can't be fooled.
- Why one common way of writing this can misbehave when missing values are around.
Common mistake: Reaching for not in with a subquery and getting an empty result the day a null sneaks into the other table.
- Many-to-Many with a Join Table
- medium
- Pro
Students can enrol on many courses and each course has many students. Explain how you'd model this relationship in tables, and how you'd query for all the courses one student is enrolled on.
What a strong answer covers
- Why neither side's table can hold the relationship on its own.
- What a linking table contains and how it stops duplicates.
- How to walk from one student through to their courses in a query.
- Where facts about the relationship itself naturally belong.
Common mistake: Storing a comma-separated list of course IDs in one column, which is hard to query, index and keep consistent.
- Why Did My Totals Double?
- medium
- Pro
A report joins orders to both their line items and their payments, then sums the order totals, and the revenue comes out far too high. Explain why joining to two one-to-many tables multiplies rows, and how you'd fix the report.
What a strong answer covers
- How a one-to-many join repeats the parent row.
- What happens when two such joins are combined in one query.
- A restructuring that keeps totals correct.
- A habit that catches this problem before a report ships.
Common mistake: Hiding the problem with distinct, which can also drop genuine duplicate amounts and still leaves the query fragile.
- Self Joins
- medium
- Pro
An employees table stores each person's manager as another employee's ID. Explain how you'd list every employee alongside their manager's name, and what changes if you need the whole chain of managers up to the top.
What a strong answer covers
- How one table can appear twice in the same query.
- Keeping the person at the top of the hierarchy in the results.
- Why one join only reaches a single level.
- How a query can repeat itself to climb a chain of unknown length.
Common mistake: Using an inner join, so the most senior person drops off the list because they have no manager.
- How the Database Joins
- hard
- Pro
A query plan shows a hash join for one query and a nested loop join for another. Explain how nested loop, hash and merge joins work, and when a database tends to choose each.
What a strong answer covers
- How each of the three main join strategies works, in plain words.
- The kind of inputs where each strategy shines.
- What information the planner relies on when it chooses.
- Why a good strategy can suddenly turn into a bad one.
Common mistake: Assuming one join method is always best, rather than seeing the choice as depending on input sizes, sort order and indexes.
Indexes and Performance
Explain how a B-tree index on an email column lets the database find one user among ten million rows without reading the whole table, using the analogy of a book's index if it helps.
What a strong answer covers
- What an index actually stores and how it points back to rows.
- How the tree's levels narrow a search down quickly.
- Why only a handful of reads are needed even for millions of rows.
- What else sorted storage makes cheap, beyond exact lookups.
Common mistake: Describing an index as a magic speed-up without explaining why sorted, shallow storage avoids reading the whole table.
- Composite Index Column Order
- medium
- Pro
You add an index on two columns of an orders table: customer ID first, then created date. Explain which queries can use it, which can't, and how you'd decide the column order.
What a strong answer covers
- How a multi-column index is sorted.
- Which kinds of query can take advantage of it.
- Which kinds of query generally can't, and why.
- A sensible rule of thumb for choosing the column order.
Common mistake: Thinking an index on two columns helps any query that mentions either one of them.
- Read a Query Plan
- medium
- Pro
A page is slow and you run explain analyse on its main query. Explain what a query plan shows, what signs you'd look for, and how you'd use it to decide what to change.
What a strong answer covers
- What a query plan represents and the figures it reports.
- The warning signs that point to the slow step.
- Why comparing the planner's guesses with reality matters.
- Turning what the plan shows into a change, and proving it helped.
Common mistake: Adding an index straight away without reading the plan, and never checking whether it was used.
- Why Is My Index Ignored?
- medium
- Pro
There's an index on the email column, yet a query that searches by lower-cased email, and another that searches for emails containing a word, both scan the whole table. Explain why, and how you'd fix each.
What a strong answer covers
- Why transforming a column in a condition can stop an index being used.
- Ways to make a transformed lookup indexable again.
- Why some text searches can't benefit from a sorted index at all.
- Other tools for text search, and why a planner may skip an index on purpose.
Common mistake: Assuming the database is broken, rather than seeing that the query no longer matches how the index is sorted.
- Covering Indexes
- medium
- Pro
A frequently run query looks up orders by customer and only needs the date and total, but it's still slower than you'd like even with an index on customer. Explain what a covering index is and how it could help.
What a strong answer covers
- The extra work a normal index lookup does after finding a match.
- What it means for an index to answer a query entirely by itself.
- How you'd extend the existing index for this query.
- The costs that come with a bigger index.
Common mistake: Adding every column to the index, which bloats it and slows every write for little gain.
- The Cost of Too Many Indexes
- medium
- Pro
A table that receives thousands of inserts a second has fourteen indexes, many added over the years to fix one slow query each. Explain what indexes cost and how you'd decide which to remove.
What a strong answer covers
- What every index costs on each write.
- The less obvious costs beyond write speed.
- How to find indexes that are unused or made redundant by another.
- How to remove indexes cautiously without breaking rare workloads.
Common mistake: Dropping an index that looks unused on the main server when a replica or a monthly job still relies on it.
- Diagnose a Slow Query
- hard
- Pro
A query that used to take ten milliseconds now takes four seconds, and nobody changed the code. Talk through how you'd investigate and what the likely causes are.
What a strong answer covers
- Starting from measurement rather than guesses.
- Changes in the data that can make a once-good plan bad.
- Pressure from outside the query itself.
- Matching the fix to the cause and confirming it worked.
Common mistake: Jumping to add an index before finding out what actually changed.
Transactions and Locking
- The Lost Update
- easy
Two shop assistants each read that a product has ten in stock, each sell one, and each save nine, so the stock ends up at nine instead of eight. Explain why this happened and two ways to prevent it.
What a strong answer covers
- The sequence of events that lets one save overwrite another.
- A way to let the database apply the change itself.
- Ways to detect or block a competing change.
- Why a transaction on its own may not be the whole answer.
Common mistake: Assuming that wrapping the code in a transaction automatically makes it safe.
- Isolation Levels
- medium
- Pro
Your database offers read committed, repeatable read and serialisable isolation. Explain what problems each level allows or prevents, such as dirty reads, non-repeatable reads and phantoms, and why the default is usually not the strictest.
What a strong answer covers
- The anomalies that concurrent transactions can produce, in plain words.
- What each of the three levels protects against and what it still allows.
- What the strictest level costs and what the application must do about it.
- Why databases don't default to the strictest setting.
Common mistake: Treating isolation levels as purely more or less safe, without mentioning the cost in throughput and retries.
- Optimistic Locking
- medium
- Pro
Two editors open the same article in a content system, both make changes, and the second save silently wipes out the first. Explain how optimistic locking with a version number would prevent this and what the user should see.
What a strong answer covers
- What extra information is stored and read alongside each record.
- How the save makes sure nothing changed in the meantime.
- How the application notices a conflict and what the user is told.
- When this approach suits better than holding a lock.
Common mistake: Detecting the conflict but then overwriting anyway, or showing a vague error the user can't act on.
- Lock Rows While You Work
- medium
- Pro
A booking system must never sell the same seat twice, and checking the seat then booking it sometimes double-books under load. Explain how locking the row with select for update works and what to watch out for.
What a strong answer covers
- What explicitly locking a row does to other transactions.
- The order of steps for a safe booking.
- A database-level backstop that makes double-booking impossible.
- How to avoid holding locks for longer than necessary.
Common mistake: Keeping the transaction and its lock open while waiting for a payment or the user, which stalls everyone else.
- Deadlocks
- medium
- Pro
Your logs show occasional deadlock errors when two transfers between the same two bank accounts run at the same time in opposite directions. Explain what a deadlock is, why this causes one, and how you'd prevent it.
What a strong answer covers
- What a deadlock is.
- Why these two transfers can trap each other.
- A simple rule that stops the cycle forming.
- What the database does when it finds one, and how the application should respond.
Common mistake: Treating deadlock errors as a database bug instead of changing lock order and adding a retry.
- Long-Running Transactions
- hard
- Pro
A reporting script opens a transaction, then runs for three hours, and during that time the database slows down and the table grows on disk. Explain why a long-running transaction causes these problems and what you'd do about it.
What a strong answer covers
- How an open transaction can block other work.
- Why the database must hang on to old row versions while it's open.
- Ways to run heavy reports without hurting the main database.
- Guard rails that stop this from happening again.
Common mistake: Only thinking about locks and missing that an idle open transaction also stops cleanup and makes tables grow.
Schema Design
You're designing a users table and a colleague suggests using the email address as the primary key. Explain what a primary key is for, the difference between natural and surrogate keys, and what you'd choose here.
What a strong answer covers
- What a primary key guarantees and who relies on it.
- The difference between keys taken from real data and keys invented by the system.
- What goes wrong when a key's real-world value changes.
- A recommendation that keeps uniqueness without the downsides, and its trade-offs.
Common mistake: Picking a business value as the key because it looks unique, forgetting that people change it.
The application code checks that every order belongs to a real customer and has a positive quantity, but the database still ends up with bad rows. Explain how foreign keys, unique, not null and check constraints help, and why checks in code alone aren't enough.
What a strong answer covers
- How the database can enforce relationships between tables.
- The everyday constraints that guard single values.
- Why checks in one application can't be the only protection.
- How database rules and friendly application messages work together.
Common mistake: Believing that validation in the app is enough because the app is the only writer, until a script or race proves otherwise.
- Store Money and Time
- easy
- Pro
A new payments table stores amounts as floating-point numbers and timestamps without a time zone. Explain what can go wrong with each and which column types you'd use instead.
What a strong answer covers
- Why the usual decimal-looking number type is risky for money.
- Safer ways to store amounts, and what else money needs.
- Why a timestamp with no zone information is ambiguous.
- A consistent approach to storing and displaying times.
Common mistake: Rounding money at display time to hide small errors instead of storing it exactly in the first place.
- Spot Normalisation Problems
- medium
- Pro
An orders table stores the customer's name and address on every order and keeps the product names as a comma-separated list in one column. Walk through the first, second and third normal forms and how you'd restructure this.
What a strong answer covers
- The rule about one value per column, and how it applies here.
- What the later normal forms say about which facts belong in which table.
- Where the customer's details really belong.
- The problems this avoids, and when copying data is deliberate and right.
Common mistake: Normalising everything blindly, so a past order's shipping address changes when the customer moves house.
- Soft Delete or Hard Delete?
- medium
- Pro
Product asks for deleted projects to be recoverable for thirty days. Explain the trade-offs between soft deletes with a deleted-at column and actually deleting rows, and the pitfalls of soft deletes.
What a strong answer covers
- What soft deleting means and why it makes recovery easy.
- The everyday problems it creates for queries and uniqueness.
- Legal and privacy reasons data must sometimes really go.
- Ways to soften the downsides, including cleaning up after the recovery window.
Common mistake: Adding a deleted flag and forgetting it in one query, so deleted projects reappear somewhere in the product.
- Migrations in Version Control
- medium
- Pro
Your team changes the production database by hand and the staging and production schemas have drifted apart. Explain how migration files work, how a team should use them, and what rules keep them safe.
What a strong answer covers
- What a migration file is and how the tool tracks what has run.
- How migrations keep every environment's schema the same.
- The golden rule about changing migrations that have already run.
- Where migrations fit into review and deployment.
Common mistake: Editing an old migration to fix it, so environments that already ran it never get the correction.
- Backfill a Large Table
- hard
- Pro
You've added a new column to a table with two hundred million rows and need to fill it in for every existing row without slowing down the live site. Explain how you'd run the backfill safely.
What a strong answer covers
- Why one enormous update is risky on a live system.
- How to break the work into small, gentle pieces.
- Making the job safe to stop and restart.
- Dealing with rows written while it runs, and what to watch.
Common mistake: Running one giant update in a single transaction and causing long locks, replica lag and bloat.
NoSQL
- Kinds of NoSQL Database
- easy
- Pro
NoSQL covers very different databases. Explain the main kinds, namely key-value, document, wide-column and graph stores, how each stores data and give one good use case for each.
What a strong answer covers
- The four main families and the shape of data each holds.
- A well-known example of each.
- A realistic use case each family suits.
- The idea that the choice follows from how the data is used.
Common mistake: Treating NoSQL as one kind of database, or as a straight replacement for relational ones.
- Embed or Reference?
- medium
- Pro
You're modelling blog posts and their comments in a document database. Explain when you'd embed the comments inside the post document and when you'd store them as separate documents that reference the post.
What a strong answer covers
- What keeping related data inside one document gives you.
- Situations where separate documents are the better choice.
- Letting the app's reads decide how data is grouped.
- Middle-ground designs and the cost of duplicated data.
Common mistake: Embedding everything by default until a popular post hits the document size limit.
- Design for Access Patterns
- medium
- Pro
A team moving to a key-value store like DynamoDB designed the tables exactly as they would in a relational database, and now many screens need several slow lookups. Explain why access-pattern-first design matters for these stores and how you'd approach it.
What a strong answer covers
- What these stores can and can't do when you query them.
- Why you list the questions before you design the keys.
- How keys and secondary indexes are chosen to answer those questions.
- The trade-offs of this style of design.
Common mistake: Copying a relational schema across and then doing joins in application code with many round trips.
- Redis Data Structures
- medium
- Pro
Redis is more than a simple cache. Explain which of its data structures, such as strings, hashes, lists, sets and sorted sets, you'd use for a page view counter, a user profile, a recent activity feed and a top-ten leaderboard, and why.
What a strong answer covers
- Which structure fits each of the four features, and why.
- Why safe concurrent updates matter for counters.
- How to keep a feed from growing forever.
- How ranking is kept cheap, and what living in memory means for durability.
Common mistake: Storing everything as serialised strings, which throws away the atomic operations that make Redis useful.
- When to Add a Search Engine
- medium
- Pro
Users want to search products by keywords, with typos forgiven and the best matches first, and a contains-the-word query on the products table is slow and poor. Explain how a search engine like Elasticsearch works differently and how you'd keep it in sync.
What a strong answer covers
- How a search engine organises text differently from a table.
- How it deals with word forms, typos and ranking.
- Which system stays the source of truth.
- How to keep the two in step, and what lag to expect.
Common mistake: Making the search engine the only copy of the data, so a lost index means lost data.
In a replicated NoSQL store, a user updates their profile and then sees the old version on refresh. Explain eventual consistency, how quorum reads and writes can give stronger guarantees, and how you'd fix this user's experience.
What a strong answer covers
- Why replicas can disagree for a short time.
- How overlapping read and write groups give stronger guarantees.
- What stronger guarantees cost.
- A targeted fix for the user who can't see their own change.
Common mistake: Making every read strongly consistent everywhere, paying the latency cost to solve one user-facing case.
SQL for Analytics
Your product manager asks for a chart of daily active users from an events table. Explain how you'd define the metric precisely and describe in words the query you'd write.
What a strong answer covers
- Pinning down exactly what being active means before writing anything.
- Counting people rather than actions.
- Agreeing where a day begins and ends.
- Making the chart complete and checking it against something you trust.
Common mistake: Counting events instead of distinct users, so one very busy user looks like many.
- Pivot Rows into Columns
- medium
- Pro
Finance wants a report with one row per month and a separate revenue column for each sales channel: web, app and phone. Your data has one row per order with a channel field. Explain how you'd produce this shape in SQL.
What a strong answer covers
- How to bucket orders into months.
- A way to build one column per channel within a single grouped query.
- Showing empty months clearly rather than as blanks.
- The maintenance cost of fixed columns, and alternatives.
Common mistake: Running a separate query per channel and stitching them together, which is slower and easy to get out of step.
- Seven-Day Moving Average
- medium
- Pro
Daily order numbers jump around so much that the trend is hard to see, and your manager asks for a seven-day moving average. Explain how you'd calculate it in SQL and the traps to avoid.
What a strong answer covers
- Getting to one row per day before smoothing.
- How a window over neighbouring days produces the average.
- Why gaps in the dates break the calculation, and how to fill them.
- How to treat the start of the series.
Common mistake: Applying the window directly to raw orders or to days with gaps, so the average no longer covers seven days.
- Compare Week on Week
- medium
- Pro
Your manager wants each week's sign-ups shown next to the previous week's, with the percentage change. Explain how you'd build this in SQL and the edge cases to handle.
What a strong answer covers
- Bucketing sign-ups into weeks with an agreed start day.
- Ways for each week to see the one before it.
- Calculating the change safely when the earlier figure is zero.
- Handling the week that hasn't finished yet.
Common mistake: Comparing a half-finished current week with a full one and reporting an alarming drop.
- Build a Conversion Funnel
- medium
- Pro
Product wants to know how many users view a product, add it to the basket, start checkout and pay, and where they drop off. Explain how you'd build this funnel from an events table.
What a strong answer covers
- Counting people at each step and the conversion between steps.
- Making sure steps are counted in the right order.
- Setting a time limit for completing the journey.
- Breaking results down to find where to act.
Common mistake: Counting each step independently, so users who skipped earlier steps make the funnel look better than it is.
- Median and Percentiles
- medium
- Pro
A dashboard reports the average order value, but a few huge corporate orders make it misleading. Explain why the median or percentiles can be better and how you'd calculate them in SQL.
What a strong answer covers
- Why an average can mislead when a few values are extreme.
- What percentiles add about the spread of values.
- How databases calculate them.
- Why percentiles from separate groups can't simply be combined.
Common mistake: Averaging the medians of each region and calling it the overall median.
- Cohort Retention
- hard
- Pro
Leadership asks whether users who signed up recently stick around better than earlier users. Explain how you'd build a monthly cohort retention table from sign-ups and activity events.
What a strong answer covers
- How users are grouped by when they joined.
- Turning activity dates into time since joining.
- Turning counts into rates and laying out the table.
- Reading the table fairly, especially for recent cohorts.
Common mistake: Comparing raw active-user counts across cohorts of different sizes instead of retention rates.
- Group Events into Sessions
- hard
- Pro
Your events table has no session IDs, but analysts want to know how long people spend per visit. Explain how you'd group each user's events into sessions where a gap of over thirty minutes starts a new one.
What a strong answer covers
- Putting each user's events in time order and comparing neighbours.
- Spotting where a new visit begins.
- Turning those starting points into session numbers.
- Summarising each session, including the odd one-event visit.
Common mistake: Grouping events into fixed clock windows, which splits one visit in two or merges separate visits.
Questions about practising
- How should I prepare for sql interview questions?
- Practise answering them out loud, not just reading them. Explaining an answer under follow-up questions is what interviews test. Work through the 47 questions here from easy to hard, and revisit the ones you struggle with.
- Can I practise sql interview questions with an AI?
- Yes. Open any question and start a voice session: an AI interviewer asks it, follows up on your answer, gives hints when you're stuck and grades your answer with written feedback when the call ends.
- Are these sql interview questions free?
- 6 of the 47 questions are free to practise. Sign in with Google, no card needed. Pro unlocks the rest, plus practice calls to your phone.