Tag: Interview Questions

  • Top SQL Server Interview Questions and Answers, by Topic

    Top SQL Server Interview Questions and Answers, by Topic

    Not new material — every answer below traces back to a specific earlier lesson in this course, cited so you can go re-derive the full reasoning if a follow-up question digs deeper than the one-liner. A reference bank organized the way it actually gets asked in an interview room.

    Interview Q → A, by topic(the reasoning behind the one-liner)Q: DELETE vs TRUNCATEvs DROP?(the classic opener)flip →A: logged row deletes,page deallocation,or structure gone entirely —each fires (or skips) triggers differentlyevery card is tagged back to its chapter:FundamentalsJoins & SetsFunctions & ProcsPerformanceTransactions & Securityevery answer traces back toa chapter — go re-derive itsay WHY, not just WHAT —interviewers probe pastthe one-line definition 📌

    Fundamentals

    Q: What’s the difference between DELETE, TRUNCATE, and DROP?
    A: DELETE removes rows (optionally filtered with WHERE), is logged row-by-row, fires DELETE triggers, and can be rolled back mid-transaction. TRUNCATE removes all rows, deallocates pages directly, resets IDENTITY, doesn’t fire triggers, and can’t be filtered. DROP removes the entire table structure and data permanently. (Fundamentals Ch.2)
    Q: What’s the difference between WHERE and HAVING?
    A: WHERE filters rows before grouping; HAVING filters groups after GROUP BY — HAVING can reference aggregates, WHERE cannot, because at the point WHERE runs, no aggregate has been computed yet. (Fundamentals Ch.4)
    Q: Why does WHERE column = NULL always return zero rows?
    A: SQL uses three-valued logic — NULL means “unknown,” and unknown = unknown evaluates to unknown, not true. Use IS NULL instead. (Fundamentals Ch.3)

    Joins & Sets

    Q: When does a LEFT JOIN silently behave like an INNER JOIN?
    A: When a filter on the right table’s column sits in WHERE instead of ON — NULL fails most WHERE comparisons, discarding the unmatched left rows LEFT JOIN was meant to preserve. (Fundamentals Ch.5)
    Q: What’s the difference between UNION and UNION ALL?
    A: UNION removes duplicate rows across the combined result (a real cost); UNION ALL keeps every row including duplicates and is faster since it skips the dedup pass. (Fundamentals Ch.5)

    Functions & Procedures

    Q: When would you choose a stored procedure over a function?
    A: When you need to modify data, manage explicit transactions, use TRY/CATCH, or return multiple result sets — none of which a function can do, by design (attempting DML inside a function throws “invalid use of a side-effecting operator”). (Ch.2, Ch.4)
    Q: What’s the difference between a temp table and a table variable?
    A: The behavioral difference that actually matters: a table variable’s contents survive a transaction ROLLBACK; a temp table’s contents are rolled back with the transaction. Table variables also historically carry weaker optimizer statistics. (Ch.3)

    Performance

    Q: What’s the difference between a clustered and nonclustered index?
    A: A clustered index’s leaf level IS the actual data, physically ordered by the key — at most one per table. A nonclustered index’s leaf holds the key plus a pointer back to the clustered index, requiring a key lookup for any additional columns not covered. (Ch.8)
    Q: How would you diagnose a slow query in production?
    A: Check sys.dm_exec_query_stats for cost, capture the actual execution plan, look for Table Scans/Key Lookups and Estimated-vs-Actual gaps, confirm with STATISTICS IO, then design a targeted (ideally covering) index and re-measure. (Ch.8)
    Q: What is parameter sniffing?
    A: A stored procedure’s execution plan is compiled once and cached based on the first parameter value seen; that plan gets reused for every later call regardless of whether the shape of the data matches, sometimes producing a fast plan for one caller and a terrible one for another. (Ch.4)

    Transactions & Security

    Q: What causes a deadlock, and how do you prevent one?
    A: Two transactions each holding a lock the other needs, in a circular wait. Prevent by always acquiring locks on shared resources in the same order across the entire application — a code-level fix, not a database configuration one. (Ch.9)
    Q: What’s the difference between TDE and Always Encrypted?
    A: TDE protects data at rest (stolen files/backups) — an authorized query still sees plaintext. Always Encrypted keeps the server from ever seeing plaintext at all; decryption happens client-side, protecting the data even from a DBA with full query access. (Ch.10)
    Q: Why shouldn’t an application’s service account be db_owner?
    A: Least privilege — a compromised connection with db_owner can drop every table and read every row; the same compromise with a narrowly-scoped role can only do what that role explicitly permits. (Ch.10)

    Enjoyed this?

    Subscribe to get every new SQL Server lesson as soon as it’s published, and share it with a developer who’d find it useful.

    📡 Subscribe via RSS  | 
    Share on X  | 
    Share on LinkedIn  | 
    Share on Facebook

    Want the full structured course with quizzes, projects, and 10+ exercises per chapter? Check out SQL Server for Developers & DBAs, coming soon on this site.

  • SQL Server Scenario-Based Interview Questions: Find the 2nd Highest Salary, and More

    SQL Server Scenario-Based Interview Questions: Find the 2nd Highest Salary, and More

    Modern interviews increasingly favor “solve this problem” over “define this term.” Here’s how to actually handle the classics — not just the working query, but the reasoning an interviewer is actually listening for.

    The 2nd-highest-salary trap(same data, two different answers)Alex 100kSam 100kJordan 95kPriya 90knaive MAX-WHERE says THIS ✗DENSE_RANK correctly says THIS ✓the same tie-handling matters for dedupe:rn=1 — Sam, Eng — KEEPrn=2 — Sam, Eng — DELETErn=3 — Sam, Eng — DELETEties are the whole test —ROW_NUMBER breaks them, DENSE_RANK doesn’tadd a 4th row and re-run — that’s how youactually prove which version is right 📌

    Find the Second-Highest Salary (Correctly, With Ties)

    -- Robust version using DENSE_RANK, correctly handles ties at the top
    WITH Ranked AS (
        SELECT *, DENSE_RANK() OVER (ORDER BY salary DESC) AS rnk FROM dbo.Salary
    )
    SELECT * FROM Ranked WHERE rnk = 2;

    The common wrong answer (MAX(salary) WHERE salary < MAX(salary)) often works by luck, but most candidates can’t explain why it breaks down when the top salary is tied across multiple people — in that case, the “wrong” version silently returns the third-highest distinct salary, not the second, because two people share first place. DENSE_RANK (Ch.6) makes the tie-handling explicit and correct by definition, not by accident.

    -- Prove the difference yourself: with a tie at the top, these give different answers
    INSERT INTO dbo.Salary (name, salary) VALUES ('Alex', 100000), ('Sam', 100000), ('Priya', 90000);
    SELECT MAX(salary) FROM dbo.Salary WHERE salary < (SELECT MAX(salary) FROM dbo.Salary); -- 90000, correct here by luck
    -- Add a 4th row: ('Jordan', 95000) and re-run — now compare against the DENSE_RANK version

    Find Duplicate Rows

    SELECT name, department, COUNT(*) AS occurrences
    FROM dbo.Salary
    GROUP BY name, department
    HAVING COUNT(*) > 1;

    This is Fundamentals Ch.4's GROUP BY + HAVING pattern applied directly — "duplicates" is really just "groups with more than one member," the same shape as every other GROUP BY/HAVING question, just with a different threshold.

    Delete Duplicates, Keeping One Copy

    WITH Deduped AS (
        SELECT *, ROW_NUMBER() OVER (PARTITION BY name, department ORDER BY employee_id) AS rn
        FROM dbo.Salary
    )
    DELETE FROM Deduped WHERE rn > 1;

    A genuinely common follow-up to the duplicate-finding question above, and a real test of whether you understand ROW_NUMBER's uniqueness-guarantee well enough to use it for a DELETE, not just a SELECT — note this is deleting through the CTE, a pattern worth having ready.

    "How Would You Diagnose a Slow Query?" — The Strong Answer Structure

    Confirm where time goes Capture execution plan Check DMVs for waits Test a hypothesis

    Interviewers evaluate the process, not just the final answer — narrate your reasoning out loud, in this order (which is precisely the Chapter 8 DMV lesson's toolkit, applied as a live workflow), rather than jumping straight to "add an index." A candidate who says "I'd add an index" with no diagnostic step first reads as guessing; one who walks through sys.dm_exec_query_stats → execution plan → sys.dm_os_wait_stats → a specific, testable fix reads as someone who's actually done this under pressure before.

    Practice tip: Pick any two questions from this lesson and Lesson 1 combined, and answer them out loud, to another person or recorded, within 90 seconds each — the real interview constraint isn't knowing the answer, it's producing a clear, well-structured explanation of it under mild time pressure. That's a different skill from recognizing the right answer on a page, and it's worth practicing separately.

    Enjoyed this?

    Subscribe to get every new SQL Server lesson as soon as it's published, and share it with a developer who'd find it useful.

    📡 Subscribe via RSS  | 
    Share on X  | 
    Share on LinkedIn  | 
    Share on Facebook

    Want the full structured course with quizzes, projects, and 10+ exercises per chapter? Check out SQL Server for Developers & DBAs, coming soon on this site.