Country or region and language

    Choose your country or region and your language.

    Suggested for you

      All countries and regions

        Choose your character

        It shows in the top bar and on your profile. Change it any time.

        SQL query questions for interviews

        Practice SQL query questions for interviews with runnable PostgreSQL examples, worked answers, and checks for ties, repeated amounts, and missing values.

        A person practicing on a laptop in a quiet workspace

        SQL query questions for interviews test how you turn a requirement into a result you can check. Practice counting rows, finding repeated values and returning a second-highest distinct amount. Before coding, define what each output row represents, how missing values behave and how ties count. Search volumes can help you choose revision topics; they don't measure how often interviewers ask a question.

        Common questions and useful answers

        Useful SQL interview answers connect a clear explanation to a result you can check. SQL, short for Structured Query Language, lets you retrieve and change data in relational databases, which organize data into related tables.

        Use an answer contract before writing a query: a short statement of the result's meaning and rules. The contract prevents a technically valid query from answering the wrong question.

        Clarify these points before choosing syntax:

        • Output row meaning: Does each row represent an order, a customer, an amount, or a summary?
        • Missing values: Should NULL, SQL's marker for missing or unknown information, be excluded, counted separately, or preserved?
        • Ties: Do equal amounts share a position, and should every qualifying order appear?
        • Empty results: What should happen when no record meets the rule?

        For example, “second-highest order amount” could mean the second row after sorting or the second distinct amount. Distinct means different values, so repeated maximum amounts occupy only one distinct position.

        Search demand and revision priorities

        Search demand suggests combining query-writing practice with explanations of joins, then extending your revision to window functions. Window functions calculate across related rows without collapsing those rows into a single summary.

        Source for every figure: DataForSEO, Google Ads average monthly searches, India market (IN), measured November 2026.
        Search queryAverage monthly searchesRevision use
        sql query questions for interview40,500Write executable answers rather than memorizing definitions alone.
        joins in sql27,100Explain matching rules and check whether joins multiply rows.
        sql window functions18,100Extend into ranking after you understand grouping and ties.

        These figures measure search activity, not interview frequency, difficulty, or hiring outcomes. Related searches can overlap, so don't add the volumes together to estimate unique learners. The figures support a revision sequence, not a ranked list of interview questions.

        Foundational answers

        Foundational answers should state the concept and its practical consequence. In the model answers below, notice how each definition explains what happens to rows.

        1. Interviewer: "What is SQL, and what do you use it for?"
        
        Model answer: "SQL stands for Structured Query Language. You use it to retrieve and change data in relational databases, where tables store rows and columns. A query describes the result you want; the database chooses an execution strategy."
        
        Listening for: A clear purpose, an understanding of tables, and a distinction between SQL and a database product such as PostgreSQL.
        2. Interviewer: "What is the difference between an inner join and a left join?"
        
        Model answer: "An inner join returns matching row combinations. A left join also preserves rows from the left table that have no match, filling the right-side columns with NULL. Either join can return several rows for one left-side record when several right-side records match."
        
        Listening for: Matching rules, preservation of unmatched rows, and awareness that a join can multiply rows.

        If an order has several line items, joining orders to line items changes the row meaning from one order to one matching order-item combination. State that change before calculating totals, or an order-level amount can be counted repeatedly.

        3. Interviewer: "What is the difference between WHERE and HAVING?"
        
        Model answer: "WHERE filters input rows before grouping. HAVING filters groups after aggregation, which combines rows into summaries. For example, exclude canceled orders before calculating customer totals, then filter customer groups by their total."
        
        Listening for: Row-level versus group-level filtering and a correct reason for choosing each clause.

        Try explaining those distinctions without reading the model answers, then use Interview questions: basics for another practice step.

        Counts and repeated amounts

        Counts and repeated amounts test whether you understand what a query measures. Run each fictional exercise independently in PostgreSQL; each block defines its data and requires no existing table.

        The opening WITH clause defines a common table expression, a named result available within that statement. Here, VALUES supplies the fictional rows. The integer cast on NULL gives the missing amount an explicit data type.

        -- 4. Interviewer: "How many orders are present, and how many
        -- have a recorded amount?"
        --
        -- Fictional specification:
        -- Amounts are in rupees; NULL means an unrecorded amount.
        -- Return one summary row, counting all orders and recorded amounts.
        -- Starting rows (order_id, amount):
        -- (1, 900), (2, 900), (3, 600), (4, NULL).
        -- No starting-data changes are required.
        -- Calculation: four rows; three non-NULL amounts.
        --
        -- Model answer: "COUNT(*) counts rows. COUNT(amount) counts
        -- rows whose amount isn't NULL."
        
        WITH orders(order_id, amount) AS (
          VALUES (1, 900), (2, 900), (3, 600), (4, NULL::integer)
        )
        SELECT COUNT(*) AS order_count,
               COUNT(amount) AS recorded_amount_count
        FROM orders;
        
        -- Expected output:
        -- order_count | recorded_amount_count
        -- 4           | 3
        --
        -- Listening for: Counting rows versus counting non-NULL values.
        -- 5. Interviewer: "Which recorded order amounts occur
        -- more than once?"
        --
        -- Fictional specification:
        -- Amounts are in rupees; NULL means an unrecorded amount.
        -- Return one row per repeated non-NULL amount.
        -- Repeated means a count greater than one.
        -- Starting rows (order_id, amount):
        -- (1, 900), (2, 900), (3, 600), (4, NULL).
        -- No starting-data changes are required.
        -- Calculation: 900 occurs twice; 600 occurs once; exclude NULL.
        --
        -- Model answer: "Exclude missing amounts, group by amount,
        -- and keep groups with more than one row. Repeated amounts
        -- don't prove that the orders themselves are duplicates."
        
        WITH orders(order_id, amount) AS (
          VALUES (1, 900), (2, 900), (3, 600), (4, NULL::integer)
        )
        SELECT amount, COUNT(*) AS occurrences
        FROM orders
        WHERE amount IS NOT NULL
        GROUP BY amount
        HAVING COUNT(*) > 1
        ORDER BY amount;
        
        -- Expected output:
        -- amount | occurrences
        -- 900    | 2
        --
        -- Listening for: Correct grouping, a defined repetition rule,
        -- and a distinction between repeated values and duplicate records.

        The repeated-amount query applies both filtering stages: WHERE removes missing amounts, while HAVING removes groups that aren't repeated. To investigate duplicate orders instead, first ask which fields identify the same business transaction. Matching amounts alone aren't enough.

        Second-highest values and ties

        A second-highest query needs a tie rule before it needs syntax. Ask whether the interviewer wants one amount or every order at that amount, then define what happens when a second distinct amount doesn't exist.

        -- 6. Interviewer: "Return every order with the second-highest
        -- distinct recorded amount. How will you handle ties and
        -- missing values?"
        --
        -- Fictional specification:
        -- Amounts are in rupees; NULL means an unrecorded amount.
        -- Rank distinct recorded amounts from highest to lowest.
        -- Return every order at the second distinct amount,
        -- ordered by order_id.
        -- With fewer than two distinct recorded amounts, return no rows.
        -- Starting rows (order_id, amount):
        -- (1, 900), (2, 900), (3, 600), (4, NULL).
        -- No starting-data changes are required.
        -- Calculation: distinct amounts are 900 and 600; second is 600.
        --
        -- Model answer: "Find the highest amount below the maximum,
        -- then return all orders with that amount. Repeated maximums
        -- don't occupy another distinct position. Missing amounts
        -- don't participate in the comparisons."
        
        WITH orders(order_id, amount) AS (
          VALUES (1, 900), (2, 900), (3, 600), (4, NULL::integer)
        )
        SELECT order_id, amount
        FROM orders
        WHERE amount = (
          SELECT MAX(amount)
          FROM orders
          WHERE amount < (SELECT MAX(amount) FROM orders)
        )
        ORDER BY order_id;
        
        -- Expected output:
        -- order_id | amount
        -- 3        | 600
        --
        -- Listening for: Distinct values versus ordered rows,
        -- preservation of qualifying ties, and a defined empty result.

        MAX returns the largest non-NULL value. The nested queries each return a single value, making them scalar subqueries. The inner maximum establishes the upper boundary; the next maximum finds the largest amount below that boundary. The outer query preserves every matching order.

        Use the repeated maximum as your diagnostic check. Skipping the first row after sorting by amount can return another maximum instead of the second distinct amount. If no lower amount exists, the inner calculation returns NULL, and the outer comparison selects no rows.

        Once you can predict the second-highest result before running the query, move to Interview questions: intermediate for independent practice.

        Rehearsal and practical limits

        Rehearse by stating your answer contract, predicting the output, and then running the query. Compare the returned columns, row meaning, missing-value behavior, and ordering with the expected result before changing your answer.

        Use SQL interview practice when you're ready to answer independently. The Work Gym checks exercises automatically with a hint naming the mistake; its Interview Hub supports typed and spoken practice interviews with a written report.

        These exercises build entry-level query reasoning, not proof of production performance or complete interview readiness. Small fictional tables don't show performance on large datasets, and search demand can't identify a particular employer's questions. Your next useful step is to explain why each query returns its result, not simply reproduce its syntax.

        Common questions

        Can search volume show which SQL interview questions are asked most often? No. Search volume measures search activity, not questions asked during interviews. Use the figures to choose revision topics, not to rank interviewer behavior.

        What's the difference between COUNT(*) and COUNT(column)? COUNT(*) counts every input row, while COUNT(column) counts only rows where that column isn't NULL. A recorded zero is included in COUNT(column), because zero isn't missing.

        Do repeated values mean that records are duplicates? No. Separate orders can legitimately have the same amount. Define the fields that identify the same transaction before classifying records as duplicates.

        Practice what this post teaches

        How should I handle ties in a second-highest SQL query? Clarify whether second-highest means the second distinct value or the second ordered row. If the requirement is every order at the second distinct amount, preserve all matching orders and define an empty result when no second amount exists.

        Practice what this post teaches

        Your Work Gym account

        Save your progress and pick up on another device. Your browser's progress comes with you.

        New accounts get 12 hours of full access: every course, unit, project and exam. The clock starts when you open your first lesson.

        Plan your practice from a job ad or syllabus

        Have a referral code?

        or

        You can keep practicing without an account.

        Help and feedback

        Ask a question, tell us what is not working, or share an idea. We reply by email.

        What is it about?

        We use it only to reply to you.