A candidate finishes a SQL prompt in six minutes. The query runs. The syntax is clean. Everyone in the interview panel feels good until that same person joins the team and struggles the first time a metric breaks because of duplicate rows, late-arriving data, or a vague stakeholder request.
That happens because many SQL interviews test recall more than judgment. Familiar prompts produce familiar answers. Candidates rehearse standard interview questions of SQL, and hiring teams end up measuring preparation as much as actual problem-solving.
A stronger hiring process uses those questions as starting points, not as the full test. The useful signal comes from the layer after the first answer. Ask why they chose that join. Change one business rule and see whether they adjust the logic cleanly. Add missing values, duplicate records, or a scale constraint and listen to how they reason about correctness versus speed.
That is the framework in this guide. Each topic covers four practical dimensions: what to ask, why the question matters, how to score the answer, and who should be held to that bar. An analyst, analytics engineer, data scientist, and backend developer may all write SQL, but they should not all be assessed the same way.
The goal is to help you build interviews that reflect production work. That means checking syntax, but also testing query design, debugging habits, edge-case awareness, and communication under ambiguity. If you want a structured starting point, a SQL assessment test for role-based screening can help standardize the early stage before live interviews.
For broader hiring context around adjacent roles, this set of data analyst interview questions is also useful.
1. SELECT, WHERE, and JOIN Fundamentals
A candidate writes a query that runs, returns rows, and still gets the business answer wrong. That usually happens in this part of the interview.
Start with a prompt that looks ordinary but carries real production risk. Give them two or three tables and ask for a result a stakeholder would request: customers who purchased in a date range, users with an active subscription and a qualifying event, or patients with appointments but no follow-up visit. SELECT, WHERE, and JOIN questions still earn their place because they test whether someone can turn a business request into correct relational logic under mild ambiguity.

A useful starter case is customers, orders, and order_items, with a request like: return customers who placed an order last quarter for a specific product category. That prompt checks more than syntax. It reveals whether the candidate understands join paths, filter placement, and the risk of duplicating rows when item-level tables enter the query. For analyst hiring, this is often the first point where polished rehearsal breaks down. If you are hiring into analytics work, these data analyst SQL interview questions are a good companion set for role-specific follow-ups.
What to listen for
Good answers include reasoning, not just code. The candidate should explain table grain, expected cardinality, and why a given join preserves or excludes certain records. If they choose LEFT JOIN, they should be able to say which table defines the population and what would disappear under INNER JOIN.
That explanation matters. In production, a wrong join rarely throws an error. It quietly overcounts revenue, drops unmatched users, or multiplies records before aggregation.
A practical probe is simple: ask, “What happens if I change this to an INNER JOIN?” Strong candidates answer in terms of row preservation and business impact, not just syntax.
Use a scoring rubric that separates baseline query writing from real SQL judgment:
- Basic pass: Selects the needed columns, applies reasonable filters, and produces a plausible result set.
- Strong pass: Explains join choice, table relationships, and where duplicates could appear.
- Senior signal: Calls out table grain explicitly, discusses selective predicates, and describes how they would validate row counts or inspect the execution plan.
If you want this step standardized before the live interview, a structured SQL assessment test helps establish baseline ability so interviewers can spend live time on reasoning instead of syntax triage.
Variations that expose real ability
The first answer is only the starting point. Change one condition after they finish. Ask them to include customers with no orders, return only the latest order per customer, or handle NULL values in order_date. Ask what changes if one customer has multiple qualifying orders across categories.
Those variations show whether the candidate owns the logic or just recognized a familiar pattern. The strongest candidates adjust the query cleanly, explain the trade-off they made, and check whether the revised output still matches the business request. That is the signal you want from fundamentals. Not memorized joins, but controlled reasoning under changing requirements.
2. Aggregation Functions and GROUP BY Logic
Most hiring teams ask for totals. Fewer ask whether the candidate understands why the totals are wrong.
Aggregation questions are where analysts separate themselves from people who can only retrieve rows. Use business outputs that hiring managers care about: revenue by segment, daily trading volume by asset class, sales by region and category, or headcount by department.

A retail version works well: “Calculate total sales and average margin by category and region for completed orders only.” It looks simple, but it creates room to probe grouping, filter placement, and null handling.
What to listen for
The candidate should know the difference between row-level filtering and post-aggregation filtering. They should be comfortable discussing COUNT(*), COUNT(column), and COUNT(DISTINCT column) without guessing.
Coursera's overview of common SQL screening formats notes that candidates are often asked to write queries from scratch from one or more tables in whiteboard, live coding, or take-home settings, and that common topics include joins, GROUP BY, subqueries, null handling, and window functions in problem-solving contexts rather than pure definitions, as described in its SQL interview guide.
A few useful prompts:
- Order of operations: Ask them to walk through
WHERE,GROUP BY, andHAVINGin plain language. - Null behavior: Ask whether null values affect
AVGorCOUNT(column). - Duplicate defense: Ask what happens if the source table contains repeated transactions.
How to score beyond correctness
A candidate can get the right output and still be shaky. Maybe they group by too many columns. Maybe they write a valid query but can't explain why HAVING belongs there.
For analyst-heavy roles, I like to add one metric trap. Example: “Now exclude refunded orders.” Good candidates revise the logic carefully. Great candidates ask whether refunds are separate records, status changes, or negative line items.
If you're hiring for analytics work, broader data analyst interview question sets are useful alongside SQL because aggregation logic often breaks at the boundary between technical query writing and metric definition.
Cohesyve
See what candidates can do before you interview them
Cohesyve turns a job description into a role-specific assessment with a scoring rubric. Each candidate gets a different version, so questions cannot be shared. Ten candidates free, no card.
3. Window Functions and Ranking
At this stage, the interview questions of SQL start becoming predictive instead of merely familiar.
Ask for ranked products within category, month-over-month change in subscriptions, a running portfolio balance, or the latest event per user. These prompts force candidates to think in partitions and ordered sequences instead of just grouped buckets.
A classic prompt still works: “Find the second highest salary.” But don't stop there. Follow with, “What if there are ties?” Then ask whether they'd use ROW_NUMBER, RANK, or DENSE_RANK, and why.

What strong candidates reveal
They know that window functions preserve row detail while adding analytical context. They can explain why GROUP BY won't help if you still need individual rows in the output. They also understand that ranking logic depends on the business rule, not just the syntax.
A candidate who says “it depends on whether ties should share rank” is usually thinking about the problem correctly.
Advanced SQL practice materials repeatedly highlight analytical patterns such as LAG, LEAD, cumulative sums, and period-over-period growth calculations because they map closely to business analytics and data engineering work. That pattern is summarized in this advanced SQL sales analysis guide.
Better follow-ups than most interviews use
Ask them to rewrite a self-join solution using a window function. Ask what changes if the partition key is missing or incomplete. Ask how null dates or duplicate timestamps affect “latest event” logic.
Good variation prompts include:
- Churn logic: Compare current month activity with the prior month.
- Ranking output: Return top three salaries by department.
- Sequence analysis: Identify a user's next event after signup.
This category matters a lot for analytics engineering, BI, and product analytics roles. If someone struggles here, they may still be useful in a narrower reporting role, but they probably won't handle more analytical SQL without support.
4. Subqueries, CTEs, and Query Optimization
A messy query tells you a lot about how someone thinks.
Give the candidate a nested subquery that technically works but is hard to read. Ask them to rewrite it with a WITH clause. Then ask whether the rewrite is only more readable or if it changes performance expectations in their database.
That one sequence exposes style, clarity, and practical judgment. Some people use CTEs to organize real steps. Others stack them the way some people stack sticky notes on a monitor.
A prompt that feels like the job
Use a multi-step funnel, customer segmentation logic, inventory allocation, or layered financial reporting. For example: identify users who signed up, activated within a time window, and then converted to paid, but exclude internal test accounts and merge duplicate identities.
This isn't about showing off complexity. It's about whether the candidate can break a large problem into stable pieces without losing the thread.
One useful angle is to ask where the bottleneck might be. They don't need to know your exact engine internals. They do need to think about repeated scans, unnecessary nesting, correlated subqueries, and whether an intermediate result should be materialized or simplified.
What works in interviews
I prefer a two-part exercise:
- Part one: Write a working solution however they want.
- Part two: Improve readability and discuss performance trade-offs.
That approach avoids penalizing people who solve quickly in a rough style, while still surfacing whether they can clean up their own work. It also mirrors team reality. Production SQL often starts rough.
A broader set of database interview questions helps here because optimization discussions often cross into schema design, indexing, and engine behavior, not just query syntax.
Don't grade CTE use as automatically senior. Grade whether the person can explain when a subquery is simpler, when a CTE improves reviewability, and when either one hides inefficiency.
5. Data Type Handling and NULL Value Logic
If you want to catch expensive mistakes early, ask null questions.
A surprising number of candidates can write acceptable joins and aggregations but still mishandle NULL, implicit casts, or date and numeric comparisons. In production, that's where quiet bugs live.
Use scenarios people recognize. Customers without phone numbers. Patients with a null discharge date because they're still admitted. Employees with incomplete profiles. Portfolio calculations with missing history.
Small prompts, big signal
Ask what this returns:
WHERE discharge_date = NULLCOUNT(phone_number)price * quantitywhen one field is null
You aren't trying to trick them. You're checking whether they understand SQL's three-valued logic and the difference between unknown, empty, and zero.
A candidate who immediately replaces = NULL with IS NULL is doing the basics right. A better candidate keeps going and tells you where null handling should be explicit in the metric definition, not just patched in the query.
What to probe after the first answer
Give them a query with a hidden type mismatch. Maybe an ID stored as text in one table and integer in another. Ask what could go wrong if the engine coerces values automatically.
Then ask about aggregates. COUNT(*) versus COUNT(column) is one of the simplest SQL questions on paper. In practice, it tells you whether the person has been burned by missing data before.
Some practical scoring points:
- Entry-level strength: Uses
IS NULLcorrectly and understands basic aggregate behavior. - Mid-level strength: Explains null propagation in expressions and filtering.
- Senior strength: Anticipates data quality problems, type inconsistencies, and downstream reporting effects.
This category often matters more than candidates expect. Teams don't usually lose time because someone forgot a semicolon. They lose time because a metric subtly excluded null-bearing rows for weeks.
6. Set Operations and UNION, INTERSECT, EXCEPT
Set operations are underrated in interviews because they look less glamorous than window functions. They're also very good at revealing whether someone sees query logic structurally.
Ask a candidate to combine active users from multiple products, identify articles viewed by subscribers but not free users, or compare acquired employee rosters across systems. These are realistic problems, and they create natural choices between UNION, UNION ALL, joins, and anti-joins.
Good prompts use contrast
One of my favorites is simple: “List all users active in either product A or product B.” Then ask, “Now preserve duplicates because we care about activity records, not unique users.”
That forces the candidate to distinguish between UNION and UNION ALL for both semantics and performance. If they understand that deduplication changes the result and usually costs more work, that's useful judgment.
Another strong prompt: “Find products present in warehouse inventory but missing from the catalog.” Some candidates reach for a join with a null filter. Others use EXCEPT. Both can be fine if they explain the trade-offs clearly.
What to listen for
Strong candidates know that:
UNIONremoves duplicates.UNION ALLpreserves duplicates.INTERSECTfinds overlap.EXCEPTreturns rows in one result and not the other.
The better discussion is whether they know when each choice makes the business logic easier to read. Readability matters. SQL gets reviewed by humans.
Some company-style SQL banks reflect this standardization well, with questions tagged by difficulty and company across employers such as Facebook, Google, Amazon, Uber, LinkedIn, Netflix, and Microsoft, including familiar patterns like second highest salary, top three salaries, rolling averages, and org-style hierarchy questions in the DataLemur SQL question catalog. That consistency is useful for prep, but in interviews it's your cue to add context, edge cases, and explanation requirements.
7. Self-Joins and Hierarchical Data Queries
Hierarchies turn ordinary SQL users into either calm problem solvers or visibly unhappy people.
Ask for manager-employee reporting lines, category trees, cost center rollups, or parent-child content structures. If the role touches organizational data, product catalogs, or nested entities, this category is worth asking directly.
A practical way to frame it
Start small. “Given an employees table with employee_id and manager_id, return each employee and their manager name.” That's a plain self-join.
Then extend it. “Now return the full management chain.” That's where recursive thinking enters. The candidate doesn't have to write perfect recursive SQL immediately, but they should recognize the shape of the problem.
What the question really reveals
This isn't just about recursion syntax. It's about whether the candidate can reason through repeated relationships in the same table and define termination conditions safely.
Ask things like:
- Depth control: How would you stop an accidental infinite loop?
- Practicality: When is a recursive CTE necessary, and when is a single self-join enough?
- Scale: What gets expensive if the hierarchy is large or frequently queried?
If a candidate reaches for recursion when a one-level self-join would do, they may be overengineering. If they avoid recursion entirely when the problem clearly needs it, they may not be comfortable with hierarchical patterns.
A finance example often works well here because cost centers, legal entities, and reporting rollups are naturally hierarchical. A commerce example also works because category trees are familiar and concrete.
8. String Manipulation and Pattern Matching
A lot of real SQL work is ugly. String questions acknowledge that.
You don't need an academic prompt here. Use things people clean up: email validation during imports, SKU parsing, transaction description categorization, URL parameter extraction, or campaign code cleanup.
Prompts that expose practical fluency
Ask the candidate to split a SKU like HOME-CHAIR-BLK-L into meaningful components. Or ask them to identify malformed emails and explain whether they'd use LIKE, a regular expression, or upstream validation instead.
Candidates who have spent time with operational data usually answer differently from candidates who have only practiced textbook SQL. They know text data is inconsistent. They mention empty strings, case sensitivity, trailing spaces, and null values without being prompted too much.
What to evaluate
The syntax matters less than the judgment. Different databases support different string and regex functions. What you want is whether the person knows to ask which engine they're in and whether the transformation belongs in SQL, in ETL, or in application code.
Useful follow-ups:
- Edge cases: What happens with null strings versus empty strings?
- Performance: Would a wildcard prefix search scale well on a large table?
- Portability: Is this regex or function database-specific?
This section is especially relevant for analytics, growth, ops, and migration work. A candidate might never brag about string wrangling, but if they can clean campaign parameters or normalize identifiers safely, they save teams a lot of pain.
9. Date and Time Calculations and Temporal Queries
Time logic makes confident candidates slow down, which is exactly why it's a good interview area.
Use retention by signup week, orders within rolling windows, tenure segmentation, or period-end finance reporting. These questions resemble the job more closely than toy prompts because they force candidates to define windows, boundaries, and business calendars carefully.
Better than “what does DATEADD do”
Ask for a retention query from scratch. Example: “Group users by signup week and calculate how many returned in the following weeks.” Or ask for order frequency in 30, 60, and 90-day windows after first purchase.
These questions test more than date functions. They test event logic, cohort assignment, and whether the candidate notices ambiguities such as timezone alignment or what counts as “returning.”
What strong candidates ask back
Good candidates usually ask clarifying questions before they write much. Does the business use UTC or local time? Are weeks calendar weeks or rolling seven-day periods? Is fiscal reporting standard calendar-based or something like a retail calendar?
Those questions are a feature, not a delay. They show the person understands that date logic is business logic.
One of the clearest weaknesses in many SQL interview collections is that they emphasize syntax definitions more than debugging and execution-order reasoning, while more realistic problems involve cumulative metrics, broken business logic, and messy operational data. That gap is discussed in this Dataquest SQL interview guide.
A candidate who pauses to define the time boundary is usually safer than one who writes quickly and assumes the wrong boundary.
10. Query Performance Analysis and Index Strategy
This is the category teams often skip until they're hiring very senior people. That's often a mistake.
You don't need a database administrator interview to ask performance questions. If the role writes production SQL, even at the analytics layer, basic performance judgment matters. A person who can diagnose a slow dashboard query, understand selective filters, and reason about indexing is far more useful than someone who only writes valid syntax.
Start with a query that works but runs slowly. Ask where they'd investigate first. Then ask what they'd change before they add an index.
A performance discussion is easier with something concrete:
If you want a non-video primer for your hiring team, this guide to faster SQL queries is a helpful framing resource.
What good answers include
Strong candidates talk about row counts, filter selectivity, join order, unnecessary scans, sort operations, and whether the query itself is doing too much. They don't treat indexes as magic.
Ask practical questions:
- Index design: What columns would you consider indexing for a multi-column filter?
- Trade-off: When would you avoid adding an index because of write cost?
- Alternative fix: Would you rewrite the query before changing schema or hardware?
Role-specific scoring
For junior analysts, a pass might be recognizing that SELECT * on a large joined dataset is careless and that indexes help reads. For senior analytics engineers or backend hires, I'd expect fluency with execution plans, composite indexes, and query restructuring.
The point isn't to demand specialist depth from everyone. The point is to see whether the candidate notices that correctness and efficiency are separate concerns. In real systems, they are.
Top 10 SQL Interview Topics Compared
| Topic | Implementation complexity | Resource requirements | Expected outcomes | Ideal use cases | Key advantages | Key limitations |
|---|---|---|---|---|---|---|
| SELECT, WHERE, and JOIN Fundamentals | Low, beginner to intermediate | Basic sample tables; any RDBMS | Demonstrates data retrieval, filtering, and join logic | Joining users/orders, simple relational queries | Quickly confirms baseline SQL competency | Too basic for senior roles; doesn't test optimization |
| Aggregation Functions and GROUP BY Logic | Medium, intermediate | Grouped datasets; knowledge of aggregates | Shows summarization, HAVING use, NULL handling | MRR, sales totals, headcount by dept | Directly applicable to reporting and KPIs | GROUP BY pitfalls and NULLs can confuse candidates |
| Window Functions and Ranking | High, advanced | Larger datasets; DB with window support | Proves advanced analytics: ranking, running totals | Ranking products, running portfolio totals | Efficient analytic patterns; avoids complex self-joins | Complex syntax; not uniformly supported across DBs |
| Subqueries, CTEs (WITH Clauses), and Query Optimization | Medium–High | Complex test data; execution plans helpful | Shows decomposition, readability, and optimization thinking | Multi-step funnel analysis, staged reporting | Improves maintainability and modular queries | Performance varies by engine; overuse can hurt speed |
| Data Type Handling and NULL Value Logic | Low–Medium | Edge-case datasets with NULLs and mixed types | Demonstrates correct NULL semantics and casting | Handling missing contact info, incomplete records | Catches common production bugs early | Behavior can differ slightly by DB; feels pedantic |
| Set Operations and UNION/INTERSECT/EXCEPT | Medium | Multiple result sets; consistent column types | Tests combining result sets, deduplication logic | Combining active users across products, exclusions | Powerful consolidation and deduplication tool | May be slower than joins; UNION implies costly dedupe |
| Self-Joins and Hierarchical Data Queries | High, advanced | Recursive-capable DB; deep hierarchy samples | Shows recursive traversal and hierarchical querying | Org charts, category trees, nested relationships | Solves complex hierarchy problems without denormalizing | Recursive CTEs can be slow; risk of infinite recursion |
| String Manipulation and Pattern Matching | Medium | Text-heavy data; regex support desirable | Demonstrates extraction, validation, and transforms | Email parsing, SKU extraction, URL param parsing | Essential for data cleaning and validation | Functions and regex differ across DBs; can be slow |
| Date/Time Calculations and Temporal Queries | Medium | Timezone-aware timestamps; date indexes | Shows date arithmetic, cohorts, and grouping | Cohort retention, tenure calculations, billing dates | Critical for time-based analytics and cohorts | Timezones and fiscal calendars add complexity |
| Query Performance Analysis and Index Strategy | High, advanced | Large datasets; execution plans; profiling tools | Demonstrates diagnosing slow queries and index strategy | Optimizing dashboards, large reporting queries | Identifies production-ready candidates; prevents scale issues | Requires deep, DB-specific knowledge; contextual tradeoffs |
From Static Questions to Dynamic Skill Verification
A well-built SQL interview loop doesn't need more trivia. It needs better signal.
That usually starts with a mindset shift. Stop treating interview questions of SQL as isolated prompts with one perfect answer. Treat them as layered assessments. The first answer tells you whether the candidate knows the pattern. The follow-up tells you whether they understand the pattern. The edge case tells you whether they can use it in practical applications.
That's the practical framework behind the ten categories above. Start with fundamentals such as joins and filtering. Move into aggregation and windows for analytical reasoning. Add nulls, time logic, and sets to uncover the mistakes that show up in production. For stronger roles, introduce hierarchy problems, optimization, and debugging tasks. By the end, you should know not only whether the candidate can write SQL, but whether they can think through ambiguity, defend trade-offs, and recover from messy data.
That last part matters more now because SQL interviewing has become highly standardized. Practice sets, company-tagged question banks, and common formats such as live coding and take-home assignments have made preparation more structured across the market. That consistency is useful for candidates, but it also means hiring teams need to work harder to avoid false positives. If your process only tests rehearsed prompts, you'll get rehearsed performance.
The fix isn't making interviews harder for the sake of it. It's making them more representative. Ask for a working query, then add a tie condition. Ask for a grouped result, then introduce duplicate records. Ask for a retention metric, then ask how timezone assumptions could break it. Ask why a query is slow, not just whether it returns the right rows. Those small changes reveal judgment, and judgment is what teams hire for.
A simple scoring model helps. Grade each question on four dimensions: correctness, clarity, adaptability, and efficiency awareness. Correctness tells you whether the result is valid. Clarity shows whether the candidate can explain what they're doing. Adaptability appears when the problem changes midstream. Efficiency awareness shows up in discussions about joins, scans, indexes, and whether the candidate notices hidden cost. This gives interviewers a shared language and reduces the usual “I liked them” bias.
Role alignment matters too. A data analyst may not need deep index strategy, but they do need strong grouping, time logic, and null handling. An analytics engineer should be comfortable with window functions, CTEs, optimization trade-offs, and maintainable query structure. A backend engineer who touches transactional systems may need more confidence around joins, set operations, and performance under write-heavy constraints. The same SQL interview shouldn't be copied blindly across all three.
Static question banks still have value. They give teams consistency and speed. But the stronger approach is dynamic skill verification. Instead of serving every candidate the same recycled prompt, generate role-specific tasks from the job requirements. Give each candidate a slightly different scenario. Mix direct query writing with debugging, explanation, and business interpretation. That setup is harder to game, fairer to candidates who think well under realistic conditions, and far closer to the work they'll be doing.
When teams do this well, interviews become more human, not less. The SQL prompt stops being a gatekeeping ritual and becomes a working conversation about data, trade-offs, and judgment. That's a much better way to hire.
Cohesyve helps teams turn static SQL interviews into dynamic, role-specific skill verification. Instead of relying on the same recycled question bank, hiring teams can generate customized assessments from the job description, give every candidate a unique challenge, and rank results based on demonstrated ability. If you want a hiring process that measures practical SQL judgment instead of polished rehearsal, explore Cohesyve.
