SQL Interview Questions and Answers

30 questions, ranked by frequency
Updated November 2026

SQL is the most common technical screen for data analyst, data scientist, data engineer and business analyst roles. Most rounds give you one or two tables and ask for a query that answers a business question, then probe how you handle duplicates, NULLs and ties.

The questions below come from the Dataford question bank, ranked by how often they show up across our interview guides. Each one opens in a live SQL editor so you can run your query against real tables.

Practice SQL interviews with a coach

1:1 mock interviews, with written feedback after

See coaches

What interviewers test

Joins

INNER vs LEFT joins, anti-joins, and what happens to row counts when keys repeat.

Aggregation

GROUP BY with HAVING, conditional aggregation with CASE WHEN, and counting distinct values correctly.

Window functions

ROW_NUMBER, RANK and DENSE_RANK, running totals, LAG and LEAD, and rolling averages.

Dates and data cleaning

Truncating dates to weeks or months, handling NULLs and duplicates, and validating results before you report them.

Easy SQL questions

Warm-up questions that check the fundamentals. Interviewers use these early to see whether you can get to a correct answer quickly and explain it.

  1. 1.

    Explain how INNER JOIN and LEFT JOIN differ, and when to use each for matched-only versus all-left-row analysis.

    Show example answer

    Approach

    Interview Tips
    • Start by describing the rows returned by each join type before discussing syntax.
    • Use a simple customers-and-orders example to show how unmatched rows behave.
    • Mention that filtering right-table columns in the WHERE clause after a LEFT JOIN can unintentionally turn it into an INNER JOIN.
    Related Concepts
    • FULL OUTER JOIN
    • RIGHT JOIN
    • NULL handling
    • Join filter placement

    Solution

    LEFT JOIN vs INNER JOIN
    What the concept is

    INNER JOIN and LEFT JOIN are two fundamental SQL join types used to combine rows from two tables based on a matching condition.

    An INNER JOIN returns only the rows where the join condition matches in both tables. If a customer has no order, or an order references no matching customer, that unmatched row does not appear in the result.

    A LEFT JOIN returns every row from the left table, whether or not a match exists in the right table. When there is no match, SQL still returns the left-table row, but the right-table columns are filled with NULL.

    This distinction matters because joins do not just combine columns; they define which records survive into the final result set.

    Why it matters

    In analytics and reporting, the wrong join type can produce misleading results.

    For example:

    • If you want a list of customers who placed at least one order, INNER JOIN is appropriate.
    • If you want a list of all customers, including those who never ordered, LEFT JOIN is required.

    The difference is especially important in business questions involving missing activity, coverage, eligibility, or exceptions. Many real analyses depend on identifying what did not happen, such as users with no purchases, products with no sales, or employees with no submitted timesheets. Those cases usually require a LEFT JOIN.

    Basic behavior example

    Assume these tables:

    customers

    • 1, Alice
    • 2, Bob
    • 3, Carla

    orders

    • 101, customer_id 1
    • 102, customer_id 1
    • 103, customer_id 2

    If you run:

    SELECT c.customer_name, o.order_id
    FROM customers c
    INNER JOIN orders o
      ON c.customer_id = o.customer_id;
    

    You get rows for Alice and Bob only, because Carla has no matching order.

    If you run:

    SELECT c.customer_name, o.order_id
    FROM customers c
    LEFT JOIN orders o
      ON c.customer_id = o.customer_id;
    

    You get Alice, Bob, and Carla. Carla appears with NULL in order_id.

    When to use INNER JOIN

    Use INNER JOIN when unmatched rows are irrelevant to the question.

    Typical use cases:

    • Orders with customer details
    • Employees assigned to a department, when only assigned employees matter
    • Transactions linked to valid accounts
    • Reporting on completed relationships only

    Example:

    SELECT o.order_id, c.customer_name
    FROM orders o
    INNER JOIN customers c
      ON o.customer_id = c.customer_id;
    

    This is useful when you only want orders that belong to a known customer.

    When to use LEFT JOIN

    Use LEFT JOIN when all rows from the left table must be preserved, even if there is no related row on the right.

    Typical use cases:

    • All customers, including those with no orders
    • All products, including those never purchased
    • All employees, including those without managers or submitted reports
    • Audits for missing relationships

    Example:

    SELECT c.customer_id, c.customer_name, o.order_id
    FROM customers c
    LEFT JOIN orders o
      ON c.customer_id = o.customer_id;
    

    This is useful when the absence of an order is meaningful.

    Common misconception: LEFT JOIN plus WHERE filter

    One of the most common interview traps is this pattern:

    SELECT c.customer_id, o.order_id
    FROM customers c
    LEFT JOIN orders o
      ON c.customer_id = o.customer_id
    WHERE o.order_status = 'completed';
    

    Although the query uses LEFT JOIN, the WHERE clause removes rows where o.order_status is NULL. That means customers without matching orders are filtered out, making the result behave like an INNER JOIN.

    If the goal is to keep all customers and only attach completed orders when present, write:

    SELECT c.customer_id, o.order_id
    FROM customers c
    LEFT JOIN orders o
      ON c.customer_id = o.customer_id
     AND o.order_status = 'completed';
    

    This preserves unmatched customers while limiting the joined orders.

    Practical implications

    In real systems, join choice affects:

    • Row counts
    • Aggregations
    • Missing data interpretation
    • Downstream dashboards and KPIs

    For example, counting customers after an INNER JOIN to orders will exclude non-buyers. That may be correct for a purchaser metric, but wrong for a total customer base metric. Similarly, using LEFT JOIN when calculating conversion funnels helps identify users who dropped off before a later event.

    How to explain this in an interview

    A strong answer should say:

    • INNER JOIN returns matched rows only
    • LEFT JOIN returns all left-table rows plus matches from the right
    • Unmatched right-side values become NULL in a LEFT JOIN
    • Use INNER JOIN for existing relationships only
    • Use LEFT JOIN when missing related data should still be visible
    • Be careful with WHERE filters on right-table columns after a LEFT JOIN

    That combination shows both conceptual understanding and practical SQL judgment.

    Key Concepts
    INNER JOIN

    INNER JOIN returns only rows where the join condition matches in both tables. If a row from either side has no match, it is excluded from the result.

    SELECT c.customer_id, c.customer_name, o.order_id
    FROM customers c
    INNER JOIN orders o
      ON c.customer_id = o.customer_id;
    
    LEFT JOIN

    LEFT JOIN returns all rows from the left table and matching rows from the right table. If there is no match on the right side, the right-table columns are returned as NULL.

    SELECT c.customer_id, c.customer_name, o.order_id
    FROM customers c
    LEFT JOIN orders o
      ON c.customer_id = o.customer_id;
    
    Unmatched Rows and NULLs

    The main behavioral difference is how unmatched rows are treated. INNER JOIN drops them, while LEFT JOIN preserves left-table rows and fills right-table columns with NULL.

    SELECT c.customer_name, o.order_id
    FROM customers c
    LEFT JOIN orders o
      ON c.customer_id = o.customer_id
    WHERE o.order_id IS NULL;
    
    Choosing the Correct Join

    Use INNER JOIN when you only care about records with valid relationships in both tables. Use LEFT JOIN when the absence of related data is meaningful and should still appear in the output.

    Filtering After a LEFT JOIN

    A common mistake is putting a filter on the right table in the WHERE clause after a LEFT JOIN, which can effectively turn it into an INNER JOIN. If you want to preserve unmatched left rows, place the filter in the ON clause when appropriate.

    SELECT c.customer_id, o.order_id
    FROM customers c
    LEFT JOIN orders o
      ON c.customer_id = o.customer_id
     AND o.order_status = 'completed';
    
    Comparison
    AspectINNER JOINLEFT JOIN
    Rows returnedOnly rows with matches in both tablesAll rows from the left table, plus matching right-table rows
    Unmatched left rowsExcludedIncluded
    Unmatched right columnsNot returnedReturned as NULL
    Best use caseNeed only related recordsNeed complete left-side coverage, including missing matches
    Common exampleCustomers who placed ordersAll customers, including those with no orders
    Filtering riskLess likely to cause confusionWHERE filters on right-table columns can remove unmatched rows
    Practice this question
  2. 2.

    Explain INNER, LEFT, RIGHT, FULL OUTER, CROSS, and SELF JOINs with examples and when to use each.

    Solve and see the answer
  3. 3.

    Explain how SQL fits with data analysis and visualization tools, and when to use each in an analytics workflow.

    Solve and see the answer
  4. 4.

    Find the second highest distinct salary from a single table using basic PostgreSQL ordering and limiting.

    Solve and see the answer
  5. 5.

    Replace missing sales fields with defined defaults and return a consistently ordered dataset.

    Solve and see the answer
  6. 6.

    Calculate the monthly spending trends for customers using window functions and joins.

    Solve and see the answer
  7. 7.

    Explain the differences between WHERE and HAVING clauses in SQL and when to use each.

    Solve and see the answer
  8. 8.

    Explain how to assess and clean incomplete or inconsistent data before analysis.

    Solve and see the answer
  9. 9.

    Explain how CTEs make complex PostgreSQL queries easier to read, debug, and maintain in reporting workflows.

    Solve and see the answer
  10. 10.

    Use GROUP BY and SUM to rank the top 10 customers by total revenue from a single sales table.

    Solve and see the answer

Medium SQL questions

The core of most technical rounds. Expect to combine several ideas, state your assumptions and handle edge cases.

  1. 11.

    Explain how to profile, clean, and standardize missing or dirty data before analysis.

    Show example answer

    Approach

    Interview Tips
    • Start by explaining how you would profile the data before cleaning it.
    • Mention that you would not blindly impute missing values without business context.
    • Call out the importance of keeping raw and cleaned layers separate for auditability.
    Related Concepts
    • data quality
    • staging tables
    • deduplication
    • null semantics

    Solution

    Data Cleaning Strategy in SQL

    When a dataset contains significant missing or dirty data, the first goal is not to “fix everything” immediately. The first goal is to understand the shape of the problem well enough to avoid introducing bias. In SQL, that means starting with profiling: count NULLs, inspect distinct values, check min/max ranges, and look for patterns that suggest malformed records. For example, if a date column contains text-like placeholders, or a numeric column contains negative values that should never occur, those rows need to be isolated before they affect reporting.

    A good workflow usually follows this order:

    1. Profile the data to quantify missingness and anomalies.
    2. Classify issues into fixable, ignorable, and invalid rows.
    3. Apply cleaning rules consistently in SQL.
    4. Validate the result by comparing row counts, distributions, and aggregates before and after cleaning.
    Handling missing values

    NULLs are not always bad data. Sometimes they mean “unknown,” “not collected,” or “not applicable.” The right treatment depends on the business question. If you are calculating revenue, a missing amount is usually not safe to impute and should often be excluded or flagged. If you are grouping by a dimension such as channel or region, you might map NULL to a labeled bucket like 'unknown' so the record remains visible in analysis.

    Use COALESCE when a default value is analytically acceptable, but be careful: replacing NULL with zero can distort averages, ratios, and totals if the missingness is not truly equivalent to zero. A common interview point is that imputation should be domain-driven, not automatic.

    Handling dirty categorical values

    Dirty labels are common in operational systems: 'Web', 'web ', 'Website', and 'WEB' may all refer to the same channel. SQL is well suited for standardizing these values with TRIM, LOWER, and CASE WHEN. This is especially important before GROUP BY, because inconsistent labels create fragmented groups and misleading counts.

    A practical pattern is to create a cleaned staging query or CTE that normalizes values before downstream reporting. That keeps the logic auditable and reusable.

    Handling invalid dates and numbers

    Invalid dates, impossible timestamps, and out-of-range numeric values should be treated as data quality failures, not just missing values. In PostgreSQL, you can use CASE WHEN to flag suspicious rows and filter them out of final metrics. For example, negative order amounts, future dates in historical tables, or dates outside a valid reporting window should usually be excluded or investigated.

    This matters because bad values often have a larger impact than missing values. A single extreme outlier can skew averages, and a malformed date can break time-series grouping.

    Handling duplicates

    Duplicates are one of the most dangerous quality issues because they often look valid. They can inflate counts, revenue, and conversion metrics without being obvious. The right approach depends on whether duplicates are exact copies or multiple versions of the same business entity. If you have a natural key and a timestamp, a window function like ROW_NUMBER() is often the cleanest way to keep the newest or most complete record.

    If duplicates are exact row copies, you may remove them with DISTINCT, but that is only safe when every duplicate is truly redundant. If duplicates represent multiple events, then deduplication would be wrong.

    Practical trade-offs

    The central trade-off is between completeness and correctness. Excluding too much data can bias the sample, while imputing too aggressively can create false precision. In interviews, a strong answer usually mentions that you would:

    • quantify the issue first,
    • preserve raw data in a staging layer,
    • apply cleaning rules in a reproducible SQL transformation,
    • and document assumptions so downstream consumers know what was changed.

    For an Operations Manager context, this is especially important because reporting often drives staffing, service levels, and exception handling. If the data is dirty, the process should make that visible rather than hiding it behind a polished-looking metric.

    A concise SQL mindset

    A strong SQL approach is to build a clean intermediate dataset with explicit rules instead of editing source data in place. That usually means using CASE WHEN, COALESCE, filters, and sometimes window functions for deduplication. The best answer shows that you understand not just how to clean data, but how to do it in a way that is repeatable, auditable, and safe for business reporting.

    Key Concepts
    Data profiling

    Start by measuring the scope of missingness, invalid values, duplicates, and unexpected distributions. In SQL, this usually means counting NULLs, checking distinct values, and looking for impossible ranges before deciding on a cleanup strategy.

    SELECT
      COUNT(*) AS total_rows,
      COUNT(*) FILTER (WHERE amount IS NULL) AS missing_amounts
    FROM transactions;
    
    NULL handling

    NULLs should be treated intentionally, not automatically replaced. Depending on the use case, you may exclude them, impute them with a rule, or keep them as unknowns so the analysis remains honest.

    SELECT COALESCE(status, 'unknown') AS status_clean
    FROM orders;
    
    Standardization

    Dirty categorical values often come from casing, whitespace, abbreviations, or inconsistent labels. Standardizing them with trimming, casing, and CASE expressions makes grouping and joins reliable.

    SELECT CASE
      WHEN LOWER(TRIM(channel)) IN ('web', 'website') THEN 'web'
      ELSE 'other'
    END AS channel_clean
    FROM events;
    
    Deduplication

    Duplicate rows can inflate counts and sums, especially in operational datasets. You usually identify a natural key or use window functions to keep the most recent or most complete record.

    SELECT *
    FROM (
      SELECT *, ROW_NUMBER() OVER (PARTITION BY order_id ORDER BY updated_at DESC) AS rn
      FROM orders
    ) t
    WHERE rn = 1;
    
    Practice this question
  2. 12.

    Explain how to validate SQL data before reporting, including null checks, duplicates, outliers, and aggregation reconciliation.

    Solve and see the answer
  3. 13.

    Explain SQL window functions and when to use ROW_NUMBER() versus DENSE_RANK() for ranked ticket analysis.

    Solve and see the answer
  4. 14.

    Explain how SQL and NoSQL differ in schema, consistency, scaling, and customer analytics use cases.

    Solve and see the answer
  5. 15.

    Compute daily active users and a 7-day rolling average using a CTE, distinct counts, and window functions.

    Solve and see the answer
  6. 16.

    Explain how clustered and non-clustered indexes differ in storage, lookup behavior, and query performance.

    Solve and see the answer
  7. 17.

    Compare star and snowflake schemas for warehouse design, including trade-offs in normalization, query simplicity, and analytics performance.

    Solve and see the answer
  8. 18.

    Standardize missing observation fields with fallback values, missingness flags, and ordered output.

    Solve and see the answer
  9. 19.

    Explain SQL vs NoSQL trade-offs, including schema design, consistency, scaling, and query flexibility.

    Solve and see the answer
  10. 20.

    Explain how to ensure data accuracy in SQL workflows using validation checks, reconciliation, and careful query design.

    Solve and see the answer

Hard SQL questions

Questions that separate strong candidates. They reward a clear plan before you write anything and a short check of your result.

  1. 21.

    Find the second highest salary in each department without using aggregate functions.

    Show example answer

    Approach

    We first remove duplicate salaries within each department, then rank the remaining salaries from highest to lowest. The second rank is the second highest distinct salary, which avoids using MAX() or COUNT().

    WITH ranked_salaries AS (
      SELECT
        department_name,
        salary,
        DENSE_RANK() OVER (
          PARTITION BY department_name
          ORDER BY salary DESC
        ) AS salary_rank
      FROM (
        SELECT DISTINCT
          department_name,
          salary
        FROM employees
        WHERE salary IS NOT NULL
      ) distinct_salaries
    )
    SELECT
      department_name,
      salary AS second_highest_salary
    FROM ranked_salaries
    WHERE salary_rank = 2
    ORDER BY department_name;
    
    How it works
    1. SELECT DISTINCT department_name, salary removes duplicate salary values inside each department, so repeated salaries do not affect the ranking.
    2. DENSE_RANK() OVER (PARTITION BY department_name ORDER BY salary DESC) assigns rank 1 to the highest salary, rank 2 to the next distinct salary, and so on.
    3. WHERE salary_rank = 2 filters to only the second highest distinct salary per department.
    4. ORDER BY department_name makes the output deterministic and easy to read.

    This approach is PostgreSQL-friendly and avoids aggregate functions entirely.

    Solution

    WITH ranked_salaries AS (
      SELECT
        department_name,
        salary,
        DENSE_RANK() OVER (
          PARTITION BY department_name
          ORDER BY salary DESC
        ) AS salary_rank
      FROM (
        SELECT DISTINCT
          department_name,
          salary
        FROM employees
        WHERE salary IS NOT NULL
      ) distinct_salaries
    )
    SELECT
      department_name,
      salary AS second_highest_salary
    FROM ranked_salaries
    WHERE salary_rank = 2
    ORDER BY department_name;
    
    Practice this question
  2. 22.

    Rewrite a slow PostgreSQL loan payment query to reduce scanned rows while preserving the required aggregated results.

    Solve and see the answer
  3. 23.

    Explain how to diagnose and optimize a slow PostgreSQL query on large customer datasets.

    Solve and see the answer
  4. 24.

    Explain how to tune a slow PostgreSQL query that joins several large transaction tables using indexes, join strategy, and partitioning.

    Solve and see the answer
  5. 25.

    Optimize a PostgreSQL reporting query by reducing intermediate rows, using appropriate joins, and calculating monthly performance efficiently.

    Solve and see the answer
  6. 26.

    Use CTEs, joins, and date filtering to calculate 30-day retention by signup cohort from login and feature usage data.

    Solve and see the answer
  7. 27.

    Explain how to diagnose and optimize a slow analytical query on a multi-terabyte event table using SQL-aware tuning strategies.

    Solve and see the answer
  8. 28.

    Tests advanced SQL tuning and ability to improve performance while preserving results.

    Solve and see the answer
  9. 29.

    Calculate weekly retention by signup cohort using CTEs, joins, date truncation, and distinct user counts.

    Solve and see the answer
  10. 30.

    Optimize a PostgreSQL reporting query by reducing scanned rows, preserving unmatched records, and selecting the latest related review efficiently.

    Solve and see the answer

Frequently asked questions

What SQL topics come up most in interviews?

Joins, GROUP BY with aggregates, window functions (ranking, running totals, LAG and LEAD) and date handling cover most SQL rounds. Questions about duplicates and NULLs are the most common follow-ups.

Which SQL dialect should I use in an interview?

Use the dialect the company names, otherwise standard PostgreSQL-style SQL is safe. Interviewers care more about correct logic than dialect details, so say out loud when you rely on a dialect-specific function.

How should I practice for a SQL interview?

Solve questions against real tables instead of reading answers. Time yourself, talk through your plan before writing the query, and check the result for duplicates and edge cases before you call it done.

Are window functions really asked in SQL interviews?

Yes. Top-N per group, running totals and comparing a row to the previous one are standard medium questions, and they are hard to solve cleanly without window functions.

Keep preparing