SQL Interview Questions
These are the SQL questions interviewers ask most, with short answers you can say out loud in under a minute. They're grouped by level, fifteen per level, from definitions to production troubleshooting. Each answer links to the lesson that explains it in full, with runnable examples. Read the question, answer it yourself first, then open the answer.
How to Use This Page
- Answer aloud before opening. Interviews test explanation, not recognition.
- Add an example. A good answer names a table and a query: "In the Fee Tracker,
count(email)skips Advitha and Navika, who have no email." - Practice writing too. Pair this page with the SQL Query Puzzles and the SQL Mock Interview, where you write and run real queries.
Beginner Questions
What is SQL?
The standard language for defining, querying and changing data in relational databases. See What Is SQL.
What is the difference between a database and a DBMS?
The database is the data; the DBMS (such as PostgreSQL) is the software that stores, protects and queries it. See What Is a Database.
What are DDL, DML, DCL and TCL?
Definition (CREATE, ALTER), manipulation (SELECT, INSERT, UPDATE, DELETE), control (GRANT, REVOKE) and transaction control (COMMIT, ROLLBACK). See What Is SQL.
What is a primary key?
A column or set of columns that uniquely identifies each row; it is unique and never NULL. See UNIQUE and PRIMARY KEY.
What is a foreign key?
A column that must match a key in another table, so rows can only point to rows that exist. See FOREIGN KEY.
What is the difference between WHERE and HAVING?
WHERE filters rows before grouping; HAVING filters groups after GROUP BY, so it can use aggregates. See HAVING.
What does NULL mean, and how do you test for it?
"Unknown or missing". Test with IS NULL / IS NOT NULL; = NULL is never true. See NULL Values.
What is the difference between DELETE, TRUNCATE and DROP?
DELETE removes chosen rows; TRUNCATE removes all rows quickly; DROP removes the table itself. See DELETE.
What does DISTINCT do?
Removes duplicate rows from the result. See SELECT DISTINCT.
How do you sort descending?
ORDER BY column DESC; add a second column to break ties. See ORDER BY.
What do % and _ mean in LIKE?
% matches any number of characters; _ matches exactly one. See LIKE and Wildcards.
What is the difference between count(*) and count(column)?
count(*) counts rows; count(column) counts non-NULL values. See Aggregate Functions.
Is BETWEEN inclusive?
Yes, both ends are included. See IN and BETWEEN.
What is a constraint? Name four.
A rule the database enforces: NOT NULL, UNIQUE, PRIMARY KEY, FOREIGN KEY, CHECK and DEFAULT. See Constraints.
Which type should you use for money?
NUMERIC(p, s), which is exact; never FLOAT. See SQL Data Types.
Intermediate Questions
Explain the types of joins.
INNER keeps matches; LEFT/RIGHT keep all rows of one side; FULL keeps both; CROSS pairs every row with every row; a self join joins a table to itself. See How Joins Work.
How do you find rows with no match, such as customers without orders?
NOT EXISTS, or LEFT JOIN ... WHERE right.key IS NULL. Avoid NOT IN when the list can contain NULL. See EXISTS.
What is the difference between UNION and UNION ALL?
UNION removes duplicates (extra work); UNION ALL keeps every row. See UNION and UNION ALL.
What is a correlated subquery?
A subquery that refers to the outer query, so it is evaluated for each outer row. See Correlated Subqueries.
What is a view? A materialized view?
A view is a saved query run each time; a materialized view stores its result until refreshed. See Views.
What is an index, and what does it cost?
A structure that finds rows by column values quickly; it uses space and slows writes. See Indexes.
What are ACID properties?
Atomicity, consistency, isolation and durability: the guarantees a transaction gives. See ACID.
What is a transaction? Show the commands.
BEGIN, statements, then COMMIT or ROLLBACK: all-or-nothing changes. See Transactions.
What does COALESCE do?
Returns its first non-NULL argument. See NULL Functions.
What is an upsert?
Insert a row, or update it if the key exists: INSERT ... ON CONFLICT ... DO UPDATE or MERGE. See Upsert and MERGE.
How do you get the second-highest fee?
SELECT DISTINCT fee_usd FROM courses ORDER BY fee_usd DESC OFFSET 1 LIMIT 1, or DENSE_RANK() = 2. See Ranking Functions.
How do you find duplicate emails?
SELECT email, count(*) FROM t GROUP BY email HAVING count(*) > 1. See HAVING.
What does CASE do?
Returns a value from the first WHEN that is true, else the ELSE (or NULL). See CASE Expressions.
What is a self join? Give an example.
A table joined to itself, such as students joined to their mentors in the same table. See Self Join.
What is a natural or surrogate key?
A natural key is a real-world value (an email); a surrogate key is a generated id with no meaning. See Choosing Keys.
Advanced Questions
What is a CTE, and when is it recursive?
A named subquery (WITH); WITH RECURSIVE lets it refer to itself, for trees and sequences. See Recursive CTEs.
What are window functions?
Functions computed over a set of related rows (OVER (...)) that keep every row, such as rankings and running totals. See Window Functions.
ROW_NUMBER vs RANK vs DENSE_RANK?
All number rows; on ties, ROW_NUMBER gives different numbers, RANK repeats and skips, DENSE_RANK repeats without gaps. See Ranking Functions.
What do LAG and LEAD do?
Read a value from a previous or next row in the window. See Running Totals, LAG and LEAD.
What is normalization? Explain 1NF, 2NF and 3NF briefly.
Storing each fact once: atomic values (1NF), no partial dependency on a composite key (2NF), no dependency on non-key columns (3NF). See Normalization.
When would you denormalize?
When reads dominate and joins are too costly, accepting the work of keeping copies in sync. See Denormalization.
Explain the isolation levels and their anomalies.
Read Uncommitted (dirty reads), Read Committed (non-repeatable reads), Repeatable Read (phantoms in the standard), Serializable (none). See Isolation Levels.
What is MVCC?
Multi-version concurrency control: writers create new row versions, readers see a snapshot, so readers and writers rarely block each other. See MVCC.
What is a deadlock, and how do you avoid it?
Two transactions waiting on each other's locks; access rows in a consistent order and keep transactions short. See Locks and Deadlocks.
How do you read an execution plan?
Inside out; compare estimated and actual rows; look for scans that discard most rows, and expensive sorts or loops. See Reading EXPLAIN.
How do you choose the column order of a composite index?
Equality columns first, then range or sort columns; match the queries you run. See Index Design.
Why is OFFSET pagination slow on deep pages?
The database reads and discards every skipped row; keyset pagination continues from the last key instead. See Pagination.
What is the difference between a function and a procedure in PostgreSQL?
Functions return values and run inside the caller's transaction; procedures are called with CALL and can commit. See Stored Procedures.
When would you use a trigger?
To enforce rules or keep audit history automatically on every change; avoid hiding business logic in them. See Triggers.
json vs jsonb in PostgreSQL?
jsonb is parsed binary, indexable and the usual choice; json keeps the exact text. See JSON in SQL.
Professional Questions
How do you prevent SQL injection?
Parameters for every value; allow-lists for identifiers; least-privilege accounts. See SQL Injection.
What is the principle of least privilege?
Give each role only the privileges it needs, such as a read-only reporting role. See Users, Roles and Privileges.
What is row-level security?
Policies that limit which rows each user can see or change. See Row-Level Security.
Logical vs physical backups?
Logical backups (pg_dump) store SQL or data; physical backups copy files and allow point-in-time recovery with the WAL. See Backup and Restore.
How do you change a big table without downtime?
Small steps: add nullable columns, backfill in batches, NOT VALID then VALIDATE, CREATE INDEX CONCURRENTLY, expand-migrate-contract. See Schema Migrations.
Managed vs self-managed databases?
Managed services run backups, patches and failover; you still own schema, queries and access. See Database Hosting.
What is partitioning, and when does it help?
Splitting a large table by a key, usually a date; helps when queries filter on that key and old data is dropped in bulk. See Partitioning.
What is replication lag, and how do you handle it?
The delay before a replica shows a commit; read your own writes from the primary and monitor lag. See Replication and Scaling.
Sharding vs replication?
Replication copies all data for reads and failover; sharding splits data across servers to scale writes. See Replication and Scaling.
A query got slow. Walk through your approach.
Confirm the symptom, find the query (slow log, pg_stat_statements), read EXPLAIN (ANALYZE), fix the cause, add monitoring. See Troubleshooting a Database.
Why use a connection pool?
Connections are expensive and limited; a pool reuses a few for many requests. See Replication and Scaling.
What is the N+1 query problem?
One query for a list, then one per item; fix with eager loading or a join. See ORMs and Query Builders.
How do you test SQL?
A disposable database, known fixtures, rollback after each test, assertions on results and refusals, migrations tested in CI. See Testing SQL.
OLTP vs OLAP?
OLTP handles many small transactions; OLAP summarizes large data, often in a column store. See SQL for Analytics.
Name some differences between SQL dialects.
Limiting rows, ids, text joining, date functions, upserts, integer division, empty strings in Oracle, NULLs in SQL Server unique columns. See Dialect Differences Cheat Sheet.
Was this tutorial helpful?