1. Home
  2. Blog
  3. Databases & SQL

Databases & SQL

SQL Interview Questions for Testers With Answers and Practice Queries

Twenty-two SQL interview questions for testers, grouped by topic, with short answers, runnable queries and the data-validation scenarios interviewers actually ask about.

12 min read
SQL interview questions for testers with answers and practice queries

Key takeaways

  • Testers use SQL to verify what the application stored, not to build databases.
  • Expect questions on SELECT, WHERE, JOIN, GROUP BY, duplicates, NULLs and subqueries.
  • Practise on one small schema until you can write each query from memory.
  • Explain how you would use each query to find a bug; that is what interviewers want to hear.

Many testing interviews include a short SQL round. The interviewer slides a laptop over and asks you to find duplicate emails or the second-highest salary. These SQL interview questions for testers are the ones that come up again and again, with answers short enough to say out loud.

The goal is not to turn you into a database administrator. Testers read data, compare it with what the screen or API said, and prove or disprove a bug. If you can do that quickly, you pass most SQL rounds.

Basics first? Work through our SQL tutorial for beginners, then use this page as your revision sheet. For a wider list of testing questions, read how to write test cases too, because interviewers often mix topics.

Why interviewers ask SQL interview questions for testers

Three everyday jobs depend on SQL: checking that a form submission was saved correctly, preparing or cleaning test data, and investigating a defect in the data layer. An interviewer wants proof that you can do those without waiting for a developer.

The practice schema

All examples use two tables. Run this once in SQLite, MySQL or PostgreSQL (adjust types if your tool complains) and you can try every answer below.

CREATE TABLE employees (
  id INTEGER PRIMARY KEY,
  name VARCHAR(50) NOT NULL,
  dept VARCHAR(30),
  salary INTEGER,
  manager_id INTEGER
);

CREATE TABLE orders (
  order_id INTEGER PRIMARY KEY,
  emp_id INTEGER,
  amount DECIMAL(10,2),
  status VARCHAR(20),
  created_on DATE
);

INSERT INTO employees VALUES
 (1,'Asha','QA',70000,NULL),(2,'Ben','QA',65000,1),(3,'Chen','Dev',90000,1),
 (4,'Dina','Dev',90000,3),(5,'Eli',NULL,50000,3);
INSERT INTO orders VALUES
 (1,1,120.50,'PAID','2026-10-01'),(2,1,80.00,'PAID','2026-10-02'),
 (3,2,45.00,'FAILED','2026-10-02'),(4,3,300.00,'PAID','2026-10-03');

Basic SQL interview questions for testers

1. What is SQL and why do testers need it?

SQL (Structured Query Language) reads and changes data in relational databases. Testers use it to verify saved data, create test data and trace defects back to the database.

2. What is the difference between DELETE, TRUNCATE and DROP?

DELETE removes rows you choose with WHERE and can usually be rolled back. TRUNCATE empties the whole table quickly. DROP removes the table itself. Behaviour around rollback differs by database, so mention that you would check the one in use.

3. What is the order of a SELECT statement?

You write SELECT, FROM, WHERE, GROUP BY, HAVING, ORDER BY. The database logically processes FROM and WHERE first, then grouping, HAVING, SELECT and finally ORDER BY. The PostgreSQL SELECT reference documents the full syntax.

4. How do you handle NULL values?

NULL means unknown, so = NULL never matches. Use IS NULL or IS NOT NULL.

SELECT name FROM employees WHERE dept IS NULL;      -- Eli
SELECT name, COALESCE(dept, 'Unassigned') FROM employees;

5. What is the difference between WHERE and HAVING?

WHERE filters rows before grouping. HAVING filters groups after aggregation. Details and examples are in our GROUP BY and HAVING guide.

6. What is the difference between CHAR and VARCHAR?

CHAR(n) is fixed length and may pad with spaces. VARCHAR(n) stores only the characters used up to a limit. Testers care because padding can break equality checks in some databases.

7. How do you find rows that match a pattern?

SELECT name FROM employees WHERE name LIKE 'A%';    -- starts with A
SELECT name FROM employees WHERE name LIKE '_en';   -- Ben

% matches any number of characters and _ matches exactly one.

Join questions in SQL interview questions for testers

8. What are the types of joins?

INNER returns matching rows only. LEFT keeps all rows from the left table. RIGHT keeps all from the right. FULL keeps both sides. CROSS pairs every row with every row. See SQL joins explained for pictures and examples.

9. Find employees who have no orders.

SELECT e.name
FROM employees e
LEFT JOIN orders o ON o.emp_id = e.id
WHERE o.order_id IS NULL;      -- Dina, Eli

Tester angle: orphan or missing records are classic defects.

10. How do you list each employee with their manager’s name?

SELECT e.name AS employee, m.name AS manager
FROM employees e
LEFT JOIN employees m ON m.id = e.manager_id;

This is a self join: the same table under two aliases.

11. What is the difference between a primary key and a foreign key?

A primary key uniquely identifies a row and cannot be NULL. A foreign key points to a key in another table and enforces referential integrity. Read primary key vs foreign key for the full comparison.

Grouping and aggregate questions

Counting and grouping appear in almost every set of SQL interview questions for testers.

12. Count the employees in each department.

SELECT dept, COUNT(*) AS total
FROM employees
GROUP BY dept;

13. Which departments have more than one employee?

SELECT dept, COUNT(*) AS total
FROM employees
WHERE dept IS NOT NULL
GROUP BY dept
HAVING COUNT(*) > 1;

14. What is the difference between COUNT(*) and COUNT(column)?

COUNT(*) counts rows. COUNT(dept) counts only rows where dept is not NULL. In our data the first returns 5 and the second 4. Mixing them up is a favourite trap.

15. Find the highest salary and the second-highest salary.

SELECT MAX(salary) FROM employees;                         -- 90000
SELECT MAX(salary) FROM employees
WHERE salary < (SELECT MAX(salary) FROM employees);        -- 70000

An alternative is DISTINCT salary ORDER BY salary DESC LIMIT 1 OFFSET 1 (MySQL, PostgreSQL, SQLite) or DENSE_RANK() in databases that support window functions.

Subqueries, duplicates and sets

16. How do you find duplicate values?

SELECT salary, COUNT(*) AS times
FROM employees
GROUP BY salary
HAVING COUNT(*) > 1;     -- 90000 appears twice

On a real project run this on an email or order-number column that should be unique.

17. What is a subquery?

A query inside another query. Example: employees earning above the average.

SELECT name FROM employees
WHERE salary > (SELECT AVG(salary) FROM employees);

18. What is the difference between UNION and UNION ALL?

UNION removes duplicate rows from the combined result. UNION ALL keeps them and is faster because it skips the duplicate check.

19. What is the difference between IN and EXISTS?

Both test membership. IN compares against a list of values. EXISTS asks whether a correlated subquery returns any row. For large tables EXISTS often reads better, though modern optimizers handle both well. Be careful with NOT IN when the list contains NULL: it can return no rows at all.

Data validation scenarios

Many SQL interview questions for testers are really scenarios. Here are three that sound like daily work.

20. A user placed an order but it does not show on the screen. How do you check the database?

SELECT * FROM orders
WHERE emp_id = 2
ORDER BY created_on DESC;

Say what you would compare: the row’s existence, its status and amount, and the timestamp, against the UI and the API response. Our API testing with Postman guide covers the API half.

21. How do you check that migrated data matches the source?

-- row counts
SELECT COUNT(*) FROM old_orders;
SELECT COUNT(*) FROM new_orders;

-- rows present in old but missing in new
SELECT o.order_id FROM old_orders o
LEFT JOIN new_orders n ON n.order_id = o.order_id
WHERE n.order_id IS NULL;

Also compare totals such as SUM(amount) and sample a few rows field by field.

22. How do you make sure your test did not leave junk data?

Create records with a recognisable marker, for example an email ending in @test.example, and delete them afterwards with a narrow WHERE. Always run the matching SELECT first, and never run an update or delete without a WHERE clause on shared data.

Advanced SQL interview questions for testers

Senior roles add a few extras. Be ready to explain these in one or two sentences:

  • Index: a structure that speeds up lookups at the cost of slower writes and extra storage.
  • Transaction and ACID: a group of statements that succeed or fail together; atomicity, consistency, isolation, durability.
  • View: a saved query that behaves like a table.
  • Window functions: ROW_NUMBER(), RANK() and DENSE_RANK() number or rank rows without collapsing them.
  • Execution plan: the database’s description of how it will run a query, useful when a screen is slow. In PostgreSQL and MySQL use EXPLAIN.

The SQLite language reference is a handy free place to check syntax for any of these.

How to answer SQL interview questions for testers well

  • Clarify first. Ask which database and whether names can be duplicated.
  • Write simple SQL. A readable query beats a clever one.
  • Say how you would verify it. Mention running it on a small sample and comparing with the UI.
  • Admit what you do not know. Say which function you would look up rather than guessing.
  • Practise by typing. Reading answers is not the same as writing them under pressure.

Final thoughts

You do not need hundreds of questions. Master the twenty-two above on one small schema, practise explaining what each query would prove, and these SQL interview questions for testers will feel routine. Then try your own variations: another table, another join, another trap.

Frequently asked questions

Which SQL topics matter most for a tester interview?

SELECT with WHERE, joins, GROUP BY with HAVING, NULL handling, duplicates, subqueries and basic data validation queries cover most testing interviews.

How much SQL does a manual tester need for interviews?

Enough to read and verify data: filter, sort, join two tables, count, group and find duplicates. Writing stored procedures is rarely expected.

How do I practise SQL interview questions for testers at home?

Install SQLite or any free database, load a small schema like the one above and write each query yourself before checking the answer.

How do I find the second-highest salary?

Select the maximum salary that is lower than the overall maximum, or use ORDER BY with LIMIT and OFFSET, or DENSE_RANK in a window function.

Should testers learn window functions?

They are a bonus for junior roles and common in SDET interviews, so learn ROW_NUMBER, RANK and DENSE_RANK after the basics.

Keep learning

Work with Stack Quora

Need help with testing, WordPress or SEO?

We help teams ship better software and grow their sites. Tell us what you are working on and we will suggest a clear next step.

Keep reading

More guides on testing, AI & modern development

Enjoyed this article? Pick a topic and jump straight into our newest tutorials.

Artificial Intelligence

LLM Structured Output Explained: Getting Reliable JSON From AI Models

LLM structured output explained with validation we ran in Pydantic: JSON mode and schemas, constrained decoding, the ways model output…

Read article →
DevOps

SSH Keys Explained: How They Work, ssh-keygen, Ed25519 and Safe Habits

SSH keys explained with keys we generated: public vs private keys, ssh-keygen, Ed25519 vs RSA, fingerprints, passphrases, ssh-agent, authorized_keys, config…

Read article →
DevOps

HTTP Caching Explained: Cache-Control, ETag and 304 Responses, With a Live Test

HTTP caching explained with a small server we ran: Cache-Control directives, max-age, no-cache vs no-store, ETag revalidation and 304 responses,…

Read article →
Test Automation

API Contract Testing Explained: Catch Breaking Changes Before They Ship

API contract testing explained with a schema check we ran: what a contract is, consumer-driven contracts, Pact, OpenAPI, which changes…

Read article →
Software Testing

Risk-Based Testing Explained: Score Risks, Build a Matrix and Test What Matters

Risk-based testing explained step by step: identifying risks, scoring likelihood and impact, building a risk matrix, mapping risk to test…

Read article →
Databases & SQL

SQL Constraints Explained: NOT NULL, UNIQUE, CHECK and FOREIGN KEY, Tested

SQL constraints explained with tests we ran: NOT NULL, UNIQUE, CHECK, DEFAULT, PRIMARY and FOREIGN KEY, the NULL loopholes, SQLite's…

Read article →
Databases & SQL

SQL Date Functions Explained: Adding, Comparing and Grouping Dates Without Bugs

SQL date functions explained with queries we ran: adding intervals, month-end surprises, date differences, the BETWEEN trap, grouping by day,…

Read article →
Software Development

Python asyncio Explained: async, await, gather and TaskGroup With Real Timings

Python asyncio explained with code we timed: coroutines, await, gather, TaskGroup, error handling, timeouts, limiting concurrency and the blocking-call mistake…

Read article →
Software Development

Debounce vs Throttle in JavaScript: How They Work, When to Use Each, Tested

Debounce vs throttle in JavaScript explained with timings we measured in Node.js: how each works, simple implementations, leading and trailing…

Read article →
Software Development

Python Context Managers Explained: The with Statement, contextlib and Real Uses

Python context managers explained with code we ran: how with works, __enter__ and __exit__, contextlib.contextmanager, suppress, ExitStack, database transactions and…

Read article →
Artificial Intelligence

LLM Temperature and Top-p Explained: How AI Models Choose Their Next Word

LLM temperature and top-p explained with a simulation we ran: how probabilities are reshaped, what top-p keeps, recommended settings by…

Read article →
DevOps

YAML Explained: Syntax, the Norway Problem and Other Traps We Tested

YAML explained with a parser test: basic syntax, lists and maps, the Norway problem, versions turning into floats, octal zip…

Read article →
DevOps

Cron Jobs Explained: Syntax, Real Schedules and the Mistakes That Break Them

Cron jobs explained with schedules we verified: the five fields, operators, real examples, the day-of-month OR day-of-week trap, environment problems,…

Read article →
Software Testing

Bug Life Cycle in Software Testing: Every Status, Who Owns It and Common Mistakes

The bug life cycle explained: every defect status from New to Closed, who owns each step, rejected, deferred and reopened…

Read article →
Test Automation

Property-Based Testing in Python: Hypothesis Finds the Bugs Your Examples Miss

Property-based testing explained with Hypothesis tests we ran: properties vs examples, strategies, shrinking, the real bugs it found in our…

Read article →
Databases & SQL

SQL Pagination Explained: OFFSET vs Keyset, With a Million-Row Test

SQL pagination explained with a million-row test we ran: LIMIT and OFFSET, why deep pages get slow, keyset (cursor) pagination,…

Read article →
Databases & SQL

SQL EXISTS vs IN: Differences, the NOT IN NULL Trap and Performance

SQL EXISTS vs IN explained with queries we ran: how each works, why NOT IN returns no rows when a…

Read article →
Software Development

Python Logging Explained: Levels, Handlers, Formatters and Mistakes to Avoid

Python logging explained with code we ran: levels, basicConfig quirks, named loggers, handlers and formatters, logger.exception, lazy formatting, duplicate logs…

Read article →
Software Development

JavaScript Map vs Object: Key Differences, Pitfalls and a Benchmark

JavaScript Map vs Object explained with code we ran in Node.js: key types, ordering, the prototype trap, JSON, size, WeakMap…

Read article →
Software Development

Python Type Hints Explained: Annotations, mypy and the Errors It Catches

Python type hints explained with a real mypy run: basic annotations, Optional and unions, TypedDict, Literal, Protocol, generics, Callable, strict…

Read article →
Artificial Intelligence

LLM Tokens Explained: How AI Models Read Text, Count Costs and Fill Context Windows

LLM tokens explained with a tokenizer we ran: how text is split, why counts differ by language and tokenizer, context…

Read article →
DevOps

Semantic Versioning Explained: MAJOR.MINOR.PATCH, Ranges and Release Rules

Semantic versioning explained with code we ran: MAJOR.MINOR.PATCH rules, pre-releases, correct version sorting, caret and tilde ranges, 0.x versions, lockfiles…

Read article →
DevOps

Git Reset vs Revert: How to Undo Commits Safely, With a Tested Example

Git reset vs revert explained with a repository we built: soft, mixed and hard reset, revert commits, reverting merges, recovering…

Read article →
Software Testing

The Test Pyramid Explained: Layers, Ratios and When to Break the Shape

The test pyramid explained: unit, integration and end-to-end layers, sensible ratios, the ice cream cone anti-pattern, the testing trophy and…

Read article →
Test Automation

pytest Fixtures Explained: Scope, yield Teardown, conftest.py and Factories

pytest fixtures explained with a suite we ran: how fixtures work, scopes, yield teardown, conftest.py, factory fixtures, parametrized fixtures, built-ins…

Read article →
Databases & SQL

SQL Upsert Explained: INSERT ON CONFLICT, MERGE and the REPLACE Trap

SQL upsert explained with queries we ran: INSERT ON CONFLICT DO UPDATE and DO NOTHING, the excluded row, conditional updates,…

Read article →
Databases & SQL

SQL LIKE Operator Explained: Wildcards, Case Sensitivity and Performance

The SQL LIKE operator explained with queries we ran: % and _ wildcards, escaping, NOT LIKE and NULL, case sensitivity…

Read article →
Artificial Intelligence

AI Hallucinations Explained: Why Language Models Make Things Up and How to Reduce It

AI hallucinations explained: what they are, why language models produce them, common types, how to reduce them with grounding and…

Read article →
Test Automation

Mocking in Python: unittest.mock, patch and the Mistakes That Make Tests Lie

Mocking in Python with unittest.mock, tested: Mock and return_value, side_effect, patching where a name is used, spec and autospec, mocking…

Read article →
Software Testing

Code Coverage Explained: Line vs Branch Coverage and What 100% Really Means

Code coverage explained with a real coverage.py run: line, branch and condition coverage, reading a report, why 100% coverage can…

Read article →
Artificial Intelligence

What Are AI Agents? How They Work, With a Simple Agent Loop You Can Run

What are AI agents? A plain guide to the agent loop, tools, memory and guardrails, with a small Python loop…

Read article →
Test Automation

TDD vs BDD: Key Differences, One Feature Built Both Ways and When to Use Each

TDD vs BDD explained with one discount feature built both ways: red-green-refactor with code we ran, Given-When-Then scenarios, tools, trade-offs…

Read article →
Software Testing

User Acceptance Testing (UAT): Process, Checklist and Real Examples

User acceptance testing explained: who runs it, how it differs from QA, a seven-step process, a UAT test case template,…

Read article →
Artificial Intelligence

What Are Embeddings? Vectors and Cosine Similarity Explained Simply

What are embeddings? A plain-language guide to vectors, cosine similarity and semantic search, with a small example we ran, common…

Read article →
Test Automation

Flaky Tests: What Causes Them and How to Fix Them for Good

Flaky tests explained with demos we ran: the main causes, how to confirm and diagnose one, proper fixes for timing,…

Read article →
Software Testing

Load Testing vs Stress Testing: Differences, Metrics and k6 Examples

Load testing vs stress testing explained: what each proves, spike and soak tests, the metrics that matter, why averages mislead,…

Read article →