SQL Interview Questions and Answers with Examples
A SQL interview usually covers a core set of concepts, though the questions depend on the role. Interviewers want to know whether you can be trusted with the data behind a product, so they ask about tables, joins, nulls, indexes, and transactions.
That predictability is good news for anyone preparing, because it means the basics are worth knowing properly rather than approximately. A small example shows how well you understand the answer.
Knowing what a foreign key does is one thing. Saying what happens to the child rows when the parent is deleted shows that you understand the consequences.
The questions below are grouped by level. Start at the beginner section for a first developer or analyst role, and read the later sections for roles where you own schema, performance, or data integrity.
SQL examples use PostgreSQL syntax unless noted. The snippets assume the tables and columns they name already exist; they are separate examples, not one complete setup script.
How Should You Answer a SQL Interview Question?
Answer a SQL interview question by stating the concept or intended result first. Explain what each result row represents, then show the query and any important assumptions about the database.
A practical answer usually has four parts:
- State the concept in plain language.
- Show a small query or table definition.
- Explain the failure mode.
- Name how you would verify the answer.
An index answer should mention the query pattern and EXPLAIN. A transaction answer should name the rollback boundary. A join answer should predict row multiplication. Those details show why the query works.
Beginner Questions
Beginner SQL questions cover tables, keys, joins, and filtering. Give the definition, then explain what it changes in a real query.
1. What Is SQL, and What Is It Used for?
SQL is a language for defining, reading, and changing data in relational databases. You can use it to query tables, enforce constraints, and group related changes into transactions.
A strong answer covers SQL's role in reading, changing, relating, and protecting stored facts. Tables keep different facts separate, while queries and constraints connect them without forcing everything into one record.
2. What Is the Difference Between a Table, a Row, and a Column?
A table describes one kind of fact. A row is one instance of that fact. A column is one attribute of that fact.
CREATE TABLE users (
id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
email TEXT NOT NULL UNIQUE,
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
); Here users is the table, each user is a row, and email is a column. The important interview detail is table meaning. If a table tries to describe two different facts at once, queries become harder and constraints become weaker.
3. What Is the Difference Between SQL and NoSQL?
Relational SQL databases use tables and relationships; NoSQL databases use models such as documents, key-value pairs, and graphs. A relational SQL database stores data in tables with defined columns. Primary keys identify rows, foreign keys connect tables, constraints reject invalid values, and transactions protect related changes.
NoSQL is an umbrella label rather than one product. It covers document databases, key-value stores, graph databases, wide-column stores, and search engines, each with a different API and different guarantees, so a claim about one family does not automatically apply to another.
The answer an interviewer wants is a workload answer, not a winner. Relational SQL suits stable entities whose relationships must stay valid, such as customers and orders. A specific NoSQL model suits a clear access pattern, such as reading one nested document or fetching a value by key. The SQL vs NoSQL comparison works through the criteria in full.
4. What Is the Difference Between MySQL, MariaDB, PostgreSQL, and SQLite?
MySQL and MariaDB are related client/server databases; PostgreSQL is a separate client/server engine with extensive types and extensions; SQLite runs inside the application without a database server. All four support SQL.
- MySQL is a client/server database, the long-time default for web applications, and widely hosted and documented.
- MariaDB is an open-source database in the MySQL family. It speaks the MySQL client protocol, while keeping its own releases, features, storage engines, and compatibility rules, so compatibility is something you test rather than assume.
- PostgreSQL is an object-relational database that combines SQL with a broad set of types, constraints, indexes, and extensions.
- SQLite is an embedded engine. The application reads and writes a database file directly, without a separate database server.
Name the shape first, server or file, then say which engine the role actually uses and where its syntax differs from the others. The database engines guide covers each one on its own page.
5. What Is a SQL Primary Key?
A primary key uniquely identifies each row and cannot be null in PostgreSQL, the engine used here. Choose a key whose value will remain stable. In most application tables, a generated integer or UUID primary key is a practical choice.
Business identifiers can still be unique without becoming the relationship key:
CREATE TABLE products (
id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
sku TEXT NOT NULL UNIQUE,
name TEXT NOT NULL
); The id is the stable relationship key, while the unique sku remains a business identifier that can follow its own change rules.
6. What Is a SQL Foreign Key?
An enforced SQL foreign key requires non-null references to match a primary or unique key in the same or another table.
CREATE TABLE orders (
id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
user_id BIGINT NOT NULL REFERENCES users (id),
total_cents INTEGER NOT NULL
); Now an order cannot point at a missing user. That is the database doing useful work instead of leaving the rule as a comment in application code.
A complete answer also names the delete rule: restrict the parent delete, cascade it to dependent children, or set an optional reference to null according to the relationship's meaning.
7. What Does NULL Mean in SQL?
NULL means the value is unknown, missing, or not applicable. It does not mean an empty string, zero, or false.
That distinction matters because comparisons with NULL use different syntax:
SELECT id, email
FROM users
WHERE deleted_at IS NULL; This is not the same as deleted_at = NULL. A strong answer also notes that nulls affect aggregates, left joins, and engine-specific uniqueness behavior.
8. What Is the Difference Between an Inner Join and a Left Join?
An inner join returns only rows where the relationship matches. A left join returns every row from the left table and fills unmatched right-side columns with NULL.
SELECT users.email, orders.id
FROM users
JOIN orders ON orders.user_id = users.id; That query excludes users with no orders because there is no matching order row.
SELECT users.email, orders.id
FROM users
LEFT JOIN orders ON orders.user_id = users.id; That query keeps users with no orders, and the order columns are NULL for those rows.
Use an inner join when the match must exist and a left join when missing relationships belong in the result. The SQL joins guide covers the reporting mistakes around that choice.
9. What Is the Difference Between WHERE and HAVING?
The WHERE clause filters rows before grouping, while HAVING filters grouped results after aggregation.
SELECT user_id, COUNT(*) AS order_count
FROM orders
WHERE status = 'paid'
GROUP BY user_id
HAVING COUNT(*) >= 3; The WHERE clause limits the input rows to paid orders. The HAVING clause then keeps only users with at least three paid orders.
Use WHERE for an input-row condition and HAVING for a condition on the grouped result.
10. What Is the Difference Between DELETE, TRUNCATE, and DROP?
DELETE removes rows from a table, usually with a WHERE clause. TRUNCATE removes all rows quickly in engines that support it. A DROP statement removes the table object itself.
Interview-relevant details are engine-dependent: TRUNCATE typically bypasses per-row DELETE triggers, and in most engines it resets auto-increment counters, although some engines require an option or behave differently.
A strong answer includes caution. Check the target rows first (the interval literal below is PostgreSQL syntax; MySQL writes it as INTERVAL 90 DAY):
SELECT id, email
FROM users
WHERE deleted_at < CURRENT_DATE - INTERVAL '90 days'; Then apply the same condition to the destructive statement inside the appropriate operational safeguards.
Intermediate Questions
From here the interviewer stops asking what things are and starts asking what happens. The answers that land are the ones that predict a result before writing the query.
11. What Is the Difference Between COUNT(*) and COUNT(Column)?
A COUNT(*) expression counts rows, while COUNT(column) counts non-null values in that column.
SELECT
COUNT(*) AS total_rows,
COUNT(deleted_at) AS deleted_rows
FROM users; If deleted_at is null for active users, COUNT(deleted_at) counts only deleted rows. A strong answer states that null behavior.
12. Why Can a SQL Join Inflate a Count?
A SQL count can become inflated when a join produces several rows for one item before the aggregate runs.
SELECT users.id, COUNT(*) AS row_count
FROM users
JOIN orders ON orders.user_id = users.id
JOIN order_items ON order_items.order_id = orders.id
GROUP BY users.id; If one order has five items, the joined result has five rows for that order. Counting rows at that point counts items, not orders.
A small row count makes that multiplication visible:
| Stage | Rows |
|---|---|
| Orders before join | 3 |
| Rows after item join | 5 |
Fix it by counting the thing you mean:
SELECT users.id, COUNT(DISTINCT orders.id) AS order_count
FROM users
JOIN orders ON orders.user_id = users.id
JOIN order_items ON order_items.order_id = orders.id
GROUP BY users.id; Name the meaning of each result row before choosing the aggregate: one row per user, order, or item.
13. What Is Database Normalization?
Normalization is the discipline of separating facts so each table records one kind of thing, and repeated facts do not need to be updated in several places.
A normalized order model separates users, orders, products, and order items, then connects them with keys. Denormalize deliberately for a measured report, cache, or historical snapshot with a defined refresh rule. The schema design guide shows the full process.
14. What Is a Many-to-Many Database Relationship?
A many-to-many relationship means each row on one side can relate to many rows on the other side, and the reverse is also true. The reliable implementation is a join table.
CREATE TABLE post_tags (
post_id BIGINT NOT NULL REFERENCES posts (id),
tag_id BIGINT NOT NULL REFERENCES tags (id),
PRIMARY KEY (post_id, tag_id)
); A comma-separated list cannot receive ordinary foreign keys or support clean joins and indexes. The join table makes each relationship a row.
15. What Does a SQL Index Do?
An index gives the database a faster path to matching rows for a query pattern. It can help filters, joins, ordering, uniqueness, and some covering reads.
A strong answer covers both sides: an index can speed specific reads, but it consumes storage, adds write work, and should match a real query pattern.
16. How Should You Index a SQL Query That Filters and Sorts?
For a SQL query that filters orders by user and sorts by date, start by evaluating an index on (user_id, created_at). Check the execution plan before assuming it helps.
SELECT id, total_cents, created_at
FROM orders
WHERE user_id = 42
ORDER BY created_at DESC
LIMIT 20; A reasonable first index starts with the filter and then supports the sort:
CREATE INDEX orders_user_created_idx
ON orders (user_id, created_at); The equality filter leads the index, followed by the ordering column. Verify the choice with EXPLAIN and representative data. The indexes and query optimization guide covers composite and covering indexes.
17. What Is a SQL Transaction?
A transaction groups database steps into one all-or-nothing operation.
<?php
$debit = $pdo->prepare(
"UPDATE accounts
SET balance_cents = balance_cents - :debit_amount
WHERE id = :account_id
AND balance_cents >= :minimum_balance"
);
$credit = $pdo->prepare(
"UPDATE accounts
SET balance_cents = balance_cents + :amount
WHERE id = :account_id"
);
$pdo->beginTransaction();
try {
$debit->execute(["debit_amount" => 5000, "account_id" => 1, "minimum_balance" => 5000]);
if ($debit->rowCount() !== 1) {
throw new RuntimeException("Debit account was not updated.");
}
$credit->execute(["amount" => 5000, "account_id" => 2]);
if ($credit->rowCount() !== 1) {
throw new RuntimeException("Credit account was not updated.");
}
$pdo->commit();
} catch (Throwable $error) {
if ($pdo->inTransaction()) {
$pdo->rollBack();
}
throw $error;
} Check both affected-row counts and roll back explicitly because InnoDB can leave earlier successful statements active after a later statement error, while a zero-row update is not an SQL error.
ACID names atomicity, consistency, isolation, and durability. The transactions and ACID guide covers isolation and deadlocks in detail.
18. What Is SQL Injection?
SQL injection happens when untrusted input becomes part of SQL syntax instead of a value bound to a parameter.
This is the unsafe pattern most PHP code reviews should reject:
$sql = "SELECT * FROM users WHERE email = '$email'"; The safer version uses a prepared statement:
$stmt = $pdo->prepare('SELECT id, email FROM users WHERE email = ?');
$stmt->execute([$email]); Prepared statements keep values out of SQL grammar. The PHP PDO guide shows the complete application boundary.
19. What Is the Difference Between UNION and UNION ALL?
UNION combines compatible result sets and removes duplicates. UNION ALL combines compatible result sets and keeps duplicates.
SELECT email FROM newsletter_signups
UNION ALL
SELECT email FROM account_users; Use UNION ALL when duplicates are meaningful or impossible by design. Use UNION when duplicate removal is required. The UNION guide shows the result sets and column-shape rules.
Advanced Questions
These appear when the role owns performance, concurrency, or the review of somebody else's SQL. The interviewer is no longer checking knowledge; they are checking judgment under a trade-off.
20. What Is a Covering SQL Index?
A covering index is an index that contains everything the query needs, so the database can answer the query from the index without reading the table row in the ordinary way.
SELECT user_id, created_at
FROM orders
WHERE user_id = 42
ORDER BY created_at DESC; An index on (user_id, created_at) may cover that query. If the query also selects total_cents, the database may need either the table row or an index design that includes that value.
Covering indexes can help read-heavy paths, but they make the index larger and writes more expensive.
21. What Does EXPLAIN Show?
EXPLAIN shows the plan the database expects to use for a query. It helps you see scan types, join order, index usage, estimated rows, sorts, and other planning choices.
Read the plan with these questions in mind:
- Is the database reading far more rows than expected?
- Is it using the index you thought would help?
- Is a sort happening after the filter?
- Did a join multiply the work?
- Are row estimates wildly wrong?
A strong answer names both EXPLAIN and the evidence to inspect after running it.
22. What Is a Database Deadlock?
A deadlock happens when transactions wait on each other in a cycle, so none of them can proceed. The database breaks the cycle by aborting one transaction.
Deadlocks can happen in a correct busy system. These habits keep them smaller and easier to retry:
- Keep transactions short.
- Touch rows in a consistent order.
- Retry the failed transaction when the operation is safe to retry.
- Avoid doing network calls or slow application work while a transaction is open.
A strong answer treats the aborted transaction as an expected retry case when the operation is safe to repeat.
23. How Do You Find the Second-Highest Salary in SQL?
To find the second-highest distinct salary in SQL, sort distinct non-null salaries in descending order and skip the first. Use DENSE_RANK() when you also need every employee tied at that salary.
If the question asks for the second distinct salary:
SELECT DISTINCT salary
FROM employees
WHERE salary IS NOT NULL
ORDER BY salary DESC
LIMIT 1
OFFSET 1; If the question asks for the employee row with the second-ranked salary, a window function is usually clearer:
SELECT id, name, salary
FROM (
SELECT
employees.*,
DENSE_RANK() OVER (ORDER BY salary DESC) AS salary_rank
FROM employees
WHERE salary IS NOT NULL
) ranked
WHERE salary_rank = 2; DENSE_RANK() keeps tied salaries at the same rank.
24. What Is a SQL Window Function?
A window function computes a value across related rows without collapsing them into one grouped row.
SELECT
user_id,
created_at,
total_cents,
SUM(total_cents) OVER (
PARTITION BY user_id
ORDER BY created_at, id
ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
) AS running_total_cents
FROM orders; The query keeps one row per order and adds a running total per user. A normal GROUP BY would collapse those rows.
SQL Window Functions works through ranking, running totals, LAG, and frames with runnable examples.
25. How Do You Review SQL Generated by an ORM or AI Assistant?
Review ORM- or AI-generated SQL by checking its parameters, joins, selected columns, query plan, and transaction handling. Read the generated query rather than relying on the application method name.
A practical review checks these points:
- Does it use parameters instead of string concatenation?
- Does the join match the actual relationship?
- Does it accidentally select every column?
- Does pagination happen in SQL rather than in memory?
- Does the filter match an index?
- Does it run one query or one query per row?
- Does a write sequence need a transaction?
Check that the query returns the intended rows and that failed writes can be rolled back safely.
Mistakes Candidates Make
Three common mistakes are ignoring duplicate rows, assuming all databases behave alike, and claiming a query is faster without checking it.
Reciting Syntax Without Naming the Meaning of Each Result Row
A familiar query can give the wrong answer when the data contains duplicates or ties. Before writing SQL, state whether you need one row per user, order, value, or group.
Treating One Engine's Behavior as Portable SQL
Identifier quoting, date arithmetic, generated IDs, and LIMIT behavior differ between databases. Name the engine, explain the general concept, and identify any syntax that would change elsewhere.
Claiming Performance Without Reading a Plan
An index or query rewrite is not automatically faster. Explain why you expect it to help, inspect EXPLAIN on representative data, and compare rows read, sorts, and execution time where the engine supports it.
What to Focus on the Night Before
With one evening left, revise the core topics most relevant to the role rather than the whole page: joins, NULL behavior, primary and foreign keys, what an index actually does, and the difference between DELETE, TRUNCATE, and DROP.
For each one, practice the habit this whole page rests on. Say what happens as well as what the thing is. Explain what each result row represents, what could go wrong, and how you would check the result. Then pick three questions from above and answer them out loud tonight.
Frequently Asked Questions
Should a SQL interview answer begin with code or plain language?
Begin a SQL interview answer with a short explanation of the concept or intended result. Add a query when it helps, then explain what each row represents and how you would check the result.
How should you handle an ambiguous SQL question?
For an ambiguous SQL interview question, ask which result the interviewer needs. Clarify duplicates, nulls, the database engine, and ties before choosing syntax. If you cannot ask, state your assumption.
Should every SQL interview answer mention trade-offs?
A SQL interview answer needs trade-offs when the choice affects correctness, speed, write cost, or concurrent access. A basic definition does not need a forced downside.
How can you practice SQL interview answers without memorizing scripts?
Practice SQL interview answers with tiny tables. Predict the output, run the query, and explain any difference. Then add a duplicate or null value and work out how the answer changes.
Should you write SQL exactly as it would run in production during a whiteboard interview?
Whiteboard SQL should communicate a correct query, but minor dialect details may be acceptable if the interviewer agrees. Name any shortcut and explain how you would write the production version, including parameter binding.
Is it acceptable to say you do not know the answer to a SQL interview question?
It is acceptable to say you do not know a SQL interview answer. Explain what you would check in the database documentation or a small example rather than guessing confidently.
Do junior candidates need to know window functions and CTEs?
Junior SQL candidates should prepare basic window functions and CTEs when the role involves reporting or data analysis. Requirements vary by employer; joins, filtering, grouping, and null handling remain useful foundations for developer roles too.
Self-Check
Answer these out loud before reading the answers. Speaking the answer is closer to the interview than recognizing it on a page.
Use this small grouped query for the first question:
WITH employees (department_id) AS (
VALUES (10), (10), (20)
)
SELECT department_id, COUNT(*) AS employee_count
FROM employees
GROUP BY department_id
HAVING COUNT(*) >= 2; - Predict the output: which department row and count does the query return?
- Multiple choice: which clause filters groups after aggregation:
WHERE,HAVING, orORDER BY? - Multiple choice: which join keeps every row from the left table: inner join, left join, or cross join?
- Multiple choice: which database runs without a separate server process: MySQL, PostgreSQL, or SQLite?
- Predict the output: a table holds four users, and
deleted_atis null for three of them. What doCOUNT(*)andCOUNT(deleted_at)return? - Multiple choice: which tool checks the planned access path:
EXPLAIN,COMMIT, orUNION? - Short answer: a join between users, orders, and order items inflates an order count. What causes it, and what fixes it?
- Short answer: an interviewer asks whether to use SQL or NoSQL for a new checkout system. What do you ask before answering?
Answers
- Department 10 with a count of 2. Department 20 has one row, so
HAVINGremoves that group. HAVING. It runs against grouped results after the aggregate is calculated.- Left join. Unmatched right-side columns become
NULL. - SQLite. It is embedded, so the application reads and writes the database file directly.
- 4 and 1.
COUNT(*)counts rows, whileCOUNT(deleted_at)counts only the non-null values. EXPLAIN. It reports the access plan selected by the database.- The item join multiplies rows before the aggregate runs. Count the thing you mean with
COUNT(DISTINCT orders.id), after naming the meaning of each result row. - Ask about the data and the access pattern. Checkout records have relationships and money movement, so the burden of proof sits with any non-relational alternative.
Sources
-
[1]
PostgreSQL Joins Between Tables(postgresql.org)
-
[2]
PostgreSQL Indexes(postgresql.org)
-
[3]
PostgreSQL Transactions(postgresql.org)
-
[4]
MySQL InnoDB and the ACID Model(dev.mysql.com)
-
[5]
About SQLite(sqlite.org)
-
[6]
MariaDB Versus MySQL Compatibility(mariadb.com)
-
[7]
PostgreSQL 18 Documentation(postgresql.org)
Read Next
Understand inner joins, left joins, self joins, and why explicit JOIN syntax makes SQL easier to review.
Learn SQL window functions with examples: OVER, PARTITION BY, ROW_NUMBER vs RANK vs DENSE_RANK, running totals, LAG and LEAD, top-N per group, and frames.
Compare relational SQL with document, key-value, graph, wide-column, and search models through workload and ownership criteria.
Guides to the common SQL database engines: MySQL, PostgreSQL, SQLite, and MariaDB, and when to reach for each.
Learn what SQL indexes do, what they cost, and how to use EXPLAIN without guessing.
Understand transactions, commits, rollbacks, and the ACID model for reliable database writes.