100 SQL Interview Questions & Answers
SQL interviews cover a wide range — fundamentals and joins, sure, but also window functions, transaction isolation, indexing internals, and query optimization that most day-to-day query-writing never forces you to think about explicitly. This walks through all of it, organized by topic, with real (mostly dialect-neutral ANSI SQL, with call-outs where PostgreSQL/MySQL/SQL Server genuinely diverge) code, a few diagrams, and a mock test at the end.
SQL Fundamentals
Q1. What is SQL and what is it used for?
SQL (Structured Query Language) is the standard language for defining, querying, and manipulating data in a relational database — creating tables, inserting/updating/deleting rows, and asking questions of the data with SELECT. It's declarative: you describe the result you want, and the database's query optimizer figures out how to actually get it, rather than you writing step-by-step retrieval logic yourself.
Q2. Describe the difference between SQL and NoSQL databases.
| SQL (relational) | NoSQL | |
|---|---|---|
| Schema | Fixed, defined up front (tables, columns, types) | Flexible/schema-less — documents, key-value, graph, column-family |
| Consistency model | Strong consistency, ACID transactions | Often eventual consistency, tunable per system |
| Relationships | First-class — joins across tables | Usually denormalized/embedded, or handled in application code |
| Scaling | Traditionally vertical; horizontal is possible but harder | Built for horizontal scaling from the ground up |
| Examples | PostgreSQL, MySQL, SQL Server, Oracle | MongoDB, Cassandra, DynamoDB, Redis |
Q3. What are the different types of SQL commands?
| Category | Purpose | Examples |
|---|---|---|
| DDL (Data Definition) | Define/alter structure | CREATE, ALTER, DROP, TRUNCATE |
| DML (Data Manipulation) | Read/change data | SELECT, INSERT, UPDATE, DELETE |
| DCL (Data Control) | Manage permissions | GRANT, REVOKE |
| TCL (Transaction Control) | Manage transactions | COMMIT, ROLLBACK, SAVEPOINT |
Q4. Explain the purpose of the SELECT statement.
SELECT first_name, last_name, department
FROM employees
WHERE hire_date >= '2024-01-01'
ORDER BY last_name;SELECT retrieves data from one or more tables without modifying it — the only DML statement that's purely read-only. Its clauses execute in a logical order that's the opposite of how you type them: FROM/JOIN first, then WHERE, then GROUP BY, then HAVING, then SELECT's own column list, then ORDER BY last.
Q5. What is the difference between WHERE and HAVING clauses?
| WHERE | HAVING | |
|---|---|---|
| Filters | Individual rows, before grouping | Groups, after GROUP BY has run |
| Can reference aggregates? | No — SUM()/COUNT() don't exist yet at this stage | Yes — that's specifically what it's for |
| Runs | Before GROUP BY | After GROUP BY |
SELECT department, COUNT(*) AS headcount
FROM employees
WHERE active = TRUE -- filters rows first
GROUP BY department
HAVING COUNT(*) > 10; -- then filters the resulting groupsQ6. Define what a JOIN is in SQL and list its types.
A JOIN combines rows from two or more tables based on a related column between them — the whole point of a relational model, where data is normalized across tables instead of duplicated in one giant sheet.
| Join type | Returns |
|---|---|
| INNER JOIN | Only rows with a match in both tables |
| LEFT (OUTER) JOIN | Every row from the left table, matched columns or NULL from the right |
| RIGHT (OUTER) JOIN | Every row from the right table, matched columns or NULL from the left |
| FULL (OUTER) JOIN | Every row from both tables, NULLs where there's no match on either side |
| CROSS JOIN | Every combination of rows from both tables (Cartesian product) |
| SELF JOIN | A table joined to itself, to compare rows within it |
Q7. What is a primary key in a database?
A primary key uniquely identifies every row in a table — it can't be NULL and can't repeat, and a table has exactly one (though it may span multiple columns as a composite key). It's also what foreign keys in other tables point back to, forming the actual relationships in a relational schema.
Q8. Explain what a foreign key is and how it is used.
CREATE TABLE orders (
id INT PRIMARY KEY,
customer_id INT NOT NULL,
FOREIGN KEY (customer_id) REFERENCES customers(id)
);A foreign key column references another table's primary key, enforcing referential integrity — the database physically won't let you insert an order for a customer_id that doesn't exist, and by default won't let you delete a customer who still has orders (unless ON DELETE CASCADE/SET NULL says otherwise).
Q9. How can you prevent SQL injections?
-- Vulnerable: string-concatenated user input becomes part of the query text
-- "SELECT * FROM users WHERE username = '" + input + "'"
-- Safe: a parameterized query — the value is bound, never parsed as SQL
SELECT * FROM users WHERE username = ?; -- or @username / :username depending on driver- Always use parameterized queries / prepared statements — never string-concatenate user input into SQL text
- Apply the principle of least privilege to the DB account your app connects with (it shouldn't be able to DROP TABLE if it only ever needs SELECT/INSERT)
- Validate and constrain input at the application layer too, as a second line of defense
- Use an ORM's parameter binding rather than its raw-SQL escape hatches for anything touching user input
Q10. What is normalization? Explain with examples.
Normalization organizes data to eliminate redundancy and prevent update anomalies, by progressively splitting data into related tables. 1NF requires atomic values (no comma-separated lists in a cell); 2NF removes partial dependencies (every non-key column depends on the whole primary key, not just part of a composite one); 3NF removes transitive dependencies (a non-key column can't depend on another non-key column) — e.g. storing a customer's city in the orders table when it really belongs to a customers table is a 3NF violation.
Enjoyed this?
Let's talk about building something together.