SQL & Databases Interview Questions and Answers
Relational database fundamentals, query execution lifecycle, advanced JOINs, subqueries, window functions, indexing, ACID transactions, and query optimization.
Whether you are preparing for entry-level SQL & Databases interview questions for freshers or senior software engineer interview questions addressing concurrency, scalability, and system architecture, this track provides peer-reviewed model answers with syntax walkthroughs, edge cases, and practical interview tips.
1 What type of language is SQL? Medium
Declarative (non-procedural). You state *what* result you want, not *how* to compute it. The database's query optimizer decides the "how" — which indexes to use, which join order is fastest, etc.
Compare with PL/SQL (Oracle) or T-SQL (SQL Server), which are procedural extensions that add loops, variables, and conditional logic.
2 Which are valid SQL keywords? Medium
SELECT, FROM, WHERE, GROUP BY, HAVING, ORDER BY, JOIN, INSERT, UPDATE, DELETE, CREATE, ALTER, DROP, INDEX, UNION, LIMIT, DISTINCT, AS, AND, OR, NOT, IN, BETWEEN, LIKE, IS NULL, EXISTS, CASE, WHEN, THEN, ELSE, END.
3 Which SQL statement extracts data? Medium
SELECT. Optional clauses: WHERE, GROUP BY, HAVING, ORDER BY, LIMIT, JOIN.
SELECT name AS full_name, salary * 12 AS annual_salary
FROM employees
WHERE department = 'Engineering'
ORDER BY annual_salary DESC;
4 How to select all records from table Products? Medium
SELECT * FROM products;
⚠️ *Interview tip*: Always follow up with "But in production, I list explicit columns to reduce network overhead and prevent breaking if columns are reordered or added."
5 What does the FROM clause do? Medium
The FROM clause identifies the source table(s), views, joined tables, or subqueries from which data is to be retrieved, filtered, and aggregated.
### Logical SQL Processing Order:
In SQL execution internals, FROM is the very first clause evaluated by the database engine:
FROM(identifies source tables and evaluatesJOINoperations)WHERE(filters individual rows)GROUP BY(aggregates rows into groups)HAVING(filters aggregated groups)SELECT(projects columns and computes expressions)DISTINCT(deduplicates rows)ORDER BY(sorts output)LIMIT/OFFSET(paginates results)
Because FROM executes first, aliases defined in the FROM clause are recognized in all subsequent clauses.
6 Correct GROUP BY syntax? Medium
SELECT name, COUNT(name) FROM customers GROUP BY name;
In standard SQL (and MySQL 5.7+ with ONLY_FULL_GROUP_BY), any non-aggregated column in SELECT must appear in GROUP BY.
7 WHERE vs HAVING? Medium
| WHERE | HAVING |
|-------|--------|
| Filters rows | Filters groups |
| Executes before GROUP BY | Executes after GROUP BY |
| Cannot use aggregates | Can use COUNT(), SUM(), etc. |
| Can reference any column | Can only reference grouped columns or aggregates |
SELECT department, AVG(salary) AS avg_sal
FROM employees
WHERE hire_date > '2020-01-01' -- Filter rows first
GROUP BY department
HAVING AVG(salary) > 60000; -- Then filter groups
---
8 What is JOIN used for? Medium
A JOIN clause in SQL combines rows from two or more tables based on a related column between them (typically a Foreign Key referencing a Primary Key).
### The Need for JOINs:
In relational databases, data is normalized across multiple tables to avoid data redundancy:
SELECT
orders.order_id,
orders.order_date,
customers.first_name,
customers.email
FROM orders
JOIN customers ON orders.customer_id = customers.customer_id;
### Common Join Types:
INNER JOIN: Returns rows when there is a match in both tables.LEFT JOIN: Returns all rows from left table, with matching rows from right table (or NULLs).RIGHT JOIN: Returns all rows from right table.FULL OUTER JOIN: Returns rows when there is a match in either table.CROSS JOIN: Produces a Cartesian product of both tables.
9 Most common type of join? Medium
The INNER JOIN is the most widely used type of join in relational database systems.
In fact, INNER is the default join type in standard SQL—writing FROM A JOIN B ON ... is parsed by database engines as FROM A INNER JOIN B ON ....
It returns exclusively those rows where the join condition evaluates to TRUE in both tables, filtering out orphan records.
10 What are different JOINs in SQL? Medium
- INNER JOIN — matching rows only
- LEFT (OUTER) JOIN — all left + matched right
- RIGHT (OUTER) JOIN — all right + matched left
- FULL OUTER JOIN — all rows from both
- CROSS JOIN — Cartesian product
- SELF JOIN — table joined to itself
11 Which is NOT TRUE about the ON clause? Medium
The ON clause specifies the join condition. It improves readability over the old comma-syntax, supports multi-column joins (ON a.id = b.id AND a.type = b.type), and is required for outer joins. Any statement claiming otherwise is false.
12 Inner join result? Medium
An INNER JOIN returns only the subset of rows where the join predicate (ON condition) matches in both tables simultaneously:
### Visual Venn Diagram Concept:
If Table A has IDs [1, 2, 3] and Table B has IDs [2, 3, 4], the inner join on A.id = B.id returns only rows for IDs [2, 3].
SELECT e.name, d.dept_name
FROM employees e
INNER JOIN departments d ON e.dept_id = d.id;
If an employee has a NULL or non-existent dept_id, that employee will not appear in the result set.
13 Can you join 3 tables with INNER JOIN? Medium
Yes. There's no practical limit (though performance degrades with many joins).
SELECT f.name, d.name AS division, c.name AS country
FROM faculty f
INNER JOIN division d ON f.division_id = d.id
INNER JOIN country c ON f.country_id = c.id;
14 Can you join a table to itself? Medium
Yes — SELF JOIN. You must use aliases to distinguish the two instances.
SELECT a.name AS employee, b.name AS manager
FROM employees a, employees b
WHERE a.manager_id = b.id;
15 What is true about Cartesian Products? Medium
A Cartesian product occurs when tables are joined without a condition. Every row in Table A pairs with every row in Table B: m × n rows total. It's usually a bug, but CROSS JOIN is explicit and valid for combinatorial data.
16 UNION in relational algebra? Medium
In relational algebra, the UNION of two sets $A \cup B$ combines all distinct tuples from both relations into a single unified relation.
### UNION vs UNION ALL in SQL:
-- UNION removes duplicate records (performs sorting/deduplication)
SELECT city FROM customers
UNION
SELECT city FROM suppliers;
-- UNION ALL retains all rows including duplicates (much faster)
SELECT city FROM customers
UNION ALL
SELECT city FROM suppliers;
*Performance rule:* Always prefer UNION ALL unless business logic strictly requires deduplicating rows across the combined sets.
17 UNION vs UNION ALL? Medium
| UNION | UNION ALL |
|-------|-----------|
| Removes duplicates | Keeps duplicates |
| Slower (sort + dedup) | Faster |
| Use when uniqueness matters | Use when sets are already distinct or duplicates are meaningful |
18 A SELECT statement whose results are used in filtering the main query is called? Medium
A SELECT statement nested inside another SQL statement to supply values for filtering or computation is called a subquery (also known as an inner query or nested query):
SELECT product_name, price
FROM products
WHERE price > (
SELECT AVG(price) FROM products
);
### Types of Subqueries:
- Scalar Subquery: Returns exactly one row and one column.
- Multi-Row Subquery: Returns a list of values, evaluated with
IN,ANY, orALL. - Correlated Subquery: References columns from the outer query, re-evaluated for each outer row.
19 Subqueries can be nested in... Medium
Subqueries can be nested within virtually every major SQL clause and statement:
WHEREClause: Filtering candidate rows (WHERE id IN (SELECT ...))FROMClause: Acting as a derived table or inline view (FROM (SELECT ...) AS sub)SELECTProjection Clause: Computing scalar values per rowHAVINGClause: Filtering aggregated groupsINSERT INTOStatement: Populating tables from query resultsUPDATEandDELETEStatements: Targeting records based on subquery criteria
20 A subquery inside a subquery is called? Medium
A subquery placed inside another subquery is called a nested subquery (or multi-level subquery):
SELECT customer_name
FROM customers
WHERE customer_id IN (
SELECT customer_id
FROM orders
WHERE order_id IN (
SELECT order_id
FROM order_items
WHERE product_id = 101
)
);
While nested subqueries are intuitive, deeply nested subqueries can degrade execution plan efficiency. Modern optimizers often rewrite them into JOIN operations, or developers rewrite them into Common Table Expressions (CTEs) using WITH.
21 A subquery that references the outer query? Medium
A correlated subquery. It executes once for each row of the outer query.
SELECT * FROM employees e
WHERE salary > (SELECT AVG(salary) FROM employees WHERE dept = e.dept);
22 Which is NOT a DML statement? Medium
Statements such as COMMIT, ROLLBACK, CREATE, ALTER, and DROP are NOT DML statements:
COMMITandROLLBACKare TCL (Transaction Control Language).CREATE,ALTER,DROP, andTRUNCATEare DDL (Data Definition Language).GRANTandREVOKEare DCL (Data Control Language).
*DML statements are strictly:* SELECT, INSERT, UPDATE, and DELETE.
23 DELETE vs TRUNCATE? Medium
See the comparison table above. Key differences: DELETE is DML (row-by-row, rollbackable, fires triggers, has WHERE). TRUNCATE is DDL (bulk page deallocation, faster, no WHERE, resets auto-increment, doesn't fire triggers).
24 Valid constraints in MySQL? Medium
MySQL supports a complete set of integrity constraints:
PRIMARY KEY: Uniquely identifies each row (impliesNOT NULLandUNIQUE).FOREIGN KEY: Enforces referential integrity matching a primary key in another table.UNIQUE: Guarantees all values in a column are distinct.NOT NULL: ProhibitsNULLvalues.CHECK(MySQL 8.0+): Validates that values satisfy a boolean expression (CHECK (age >= 18)).DEFAULT: Assigns a fallback value if omitted during insert.AUTO_INCREMENT: Auto-generates sequential integer identifiers.
25 Which is NOT TRUE about constraints? Medium
Any assertion claiming that constraints are optional in production or that constraints significantly slow down reads is false.
### Why Constraints Are Vital:
- Constraints preserve data integrity at the lowest physical database tier, preventing corrupted data even if application code contains bugs.
- Primary key and unique constraints automatically create underlying B-tree indexes, accelerating query performance rather than degrading it.
26 NOT NULL constraint? Medium
The NOT NULL constraint enforces that a column must always contain a valid data value and cannot accept NULL:
CREATE TABLE employees (
id INT PRIMARY KEY,
full_name VARCHAR(100) NOT NULL,
hired_date DATE NOT NULL
);
Attempting to insert an empty NULL into a NOT NULL column causes the database to reject the transaction with an integrity violation error.
27 An unique (non-key) field? Medium
To enforce that every value in a non-primary key column is unique, apply the UNIQUE constraint:
CREATE TABLE users (
id INT PRIMARY KEY,
email VARCHAR(255) UNIQUE NOT NULL,
phone_number VARCHAR(20) UNIQUE
);
### PRIMARY KEY vs UNIQUE:
- A table can have only one
PRIMARY KEY. - A table can have multiple
UNIQUEconstraints. UNIQUEcolumns typically allowNULLvalues (in SQL standards, multipleNULLvalues are permitted becauseNULL != NULL).
28 What is CHECK constraint? Medium
A CHECK constraint ensures that all values stored in a column satisfy a specific boolean condition:
CREATE TABLE products (
product_id INT PRIMARY KEY,
name VARCHAR(100) NOT NULL,
price DECIMAL(10, 2) CHECK (price > 0),
discount_percent INT CHECK (discount_percent BETWEEN 0 AND 100)
);
*(Note: MySQL introduced full enforcement of CHECK constraints in MySQL 8.0.16. Earlier MySQL 5.7 versions parsed the syntax but silently ignored enforcement.)*
29 UNIQUE vs PRIMARY KEY? Medium
| PRIMARY KEY | UNIQUE |
|-------------|--------|
| One per table | Multiple per table |
| Cannot be NULL | Usually allows one NULL |
| Implicitly indexed | Explicitly indexed |
| Identifies the row | Alternate identifier |
30 What does DROP TABLE do? Medium
Permanently removes the table definition, all data, indexes, triggers, and constraints. Cannot be undone (unless in a transaction that rolls back, in some DBs).
DROP TABLE IF EXISTS old_customers;
31 What does "locking" refer to? Medium
A mechanism to prevent concurrent transactions from interfering with each other. Locks can be shared (read locks, multiple allowed) or exclusive (write locks, only one allowed).
32 Main transaction controls? Medium
COMMIT— Make changes permanentROLLBACK— Undo all changes in the transactionSAVEPOINT— Set a partial rollback point
START TRANSACTION;
UPDATE accounts SET balance = balance - 100 WHERE id = 1;
SAVEPOINT before_credit;
UPDATE accounts SET balance = balance + 100 WHERE id = 2;
-- Oops, wrong account!
ROLLBACK TO SAVEPOINT before_credit;
-- Now retry with correct account
COMMIT;
33 A transaction that completes execution is said to be? Medium
A database transaction that finishes all operations successfully and persists its changes permanently to durable storage is said to be Committed:
START TRANSACTION;
UPDATE accounts SET balance = balance - 100 WHERE id = 1;
UPDATE accounts SET balance = balance + 100 WHERE id = 2;
COMMIT; -- Transaction is now committed and permanent
Once committed, the transaction satisfies the Durability property of ACID and survives power outages or server crashes.
34 Valid properties of a transaction? Medium
The four foundational properties that guarantee database transactions are processed reliably are known as ACID:
- Atomicity: "All or nothing." If any statement within the transaction fails, all changes are rolled back to the initial state.
- Consistency: Transactions transition the database from one valid state to another, strictly obeying all constraints, cascades, and triggers.
- Isolation: Concurrent transactions execute independently without interfering with each other (governed by isolation levels like
READ COMMITTED,REPEATABLE READ, andSERIALIZABLE). - Durability: Once committed, changes are permanently recorded on disk and will not be lost even during system failure.
35 What if autocommit is enabled? Medium
Every individual statement is automatically committed. In MySQL, autocommit is ON by default. Turn it off for multi-statement transactions:
SET autocommit = 0;
-- ... multiple statements ...
COMMIT;
SET autocommit = 1;
36 What is a virtual table in MySQL? Medium
In MySQL and relational databases, a virtual table is called a View:
CREATE VIEW active_customer_summary AS
SELECT id, first_name, last_name, email
FROM Customers
WHERE is_active = 1;
### Characteristics of a View:
- A view does not store physical data rows on disk (unlike base tables).
- It stores a pre-packaged
SELECTquery definition. - When an application queries the view (
SELECT * FROM active_customer_summary), the database dynamically runs the underlying query against the base tables.
37 Are views updatable? Medium
Some views are updatable, but under strict structural criteria:
### Conditions for a View to Be Updatable:
- Must reference only one base table in the
FROMclause. - Cannot contain aggregate functions (
SUM,COUNT,AVG,MAX,MIN). - Cannot contain
DISTINCT,GROUP BY,HAVING, orUNION/UNION ALL. - Cannot use
LIMITin the view definition. - All underlying
NOT NULLcolumns without default values must be included in the view projection so thatINSERTstatements can populate required fields.
38 Advantages of views? Medium
- Simplify complex queries — hide JOINs and aggregations
- Security — expose only specific columns/rows
- Logical independence — shield apps from schema changes
- Consistency — same calculation logic everywhere
39 Does a view contain data? Medium
Standard SQL views do NOT contain data.
- Standard Views (Virtual): Contain only a stored SQL query definition in the data dictionary. Every query against the view executes dynamically against the underlying base tables.
- Materialized Views (Cached on Disk): Supported in PostgreSQL, Oracle, and SQL Server (and via plugins/triggers in MySQL), materialized views physically cache query results on disk and must be periodically refreshed (
REFRESH MATERIALIZED VIEW).
40 How to remove a view? Medium
To delete a view from the database, use the DROP VIEW command:
DROP VIEW IF EXISTS active_customer_summary;
Dropping a view removes only the stored query definition; the underlying base tables and their data rows remain completely unaffected.
41 Can a view be based on another view? Medium
Yes, a view can be defined on top of another existing view (known as a nested view):
CREATE VIEW us_customers AS
SELECT * FROM Customers WHERE country = 'USA';
CREATE VIEW vip_us_customers AS
SELECT * FROM us_customers WHERE total_spend > 5000;
### Architectural Caution:
While nested views promote modular query definitions, deeply nesting views (3+ levels) can make query execution plan optimization difficult for the query planner, leading to unexpected performance bottlenecks.
42 Iterate over rows in a stored procedure? Medium
To iterate row-by-row over a query result set inside a stored procedure, use a CURSOR:
### Cursor Lifecycle Steps:
DECLARE: Define the cursor and query.OPEN: Initialize the cursor result set.FETCH: Retrieve the next row into local variables.CLOSE: Free cursor memory resources.
DELIMITER //
CREATE PROCEDURE ProcessCustomers()
BEGIN
DECLARE done INT DEFAULT FALSE;
DECLARE cust_id INT;
DECLARE cur CURSOR FOR SELECT id FROM Customers;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;
OPEN cur;
read_loop: LOOP
FETCH cur INTO cust_id;
IF done THEN
LEAVE read_loop;
END IF;
-- Process each customer ID here
END LOOP;
CLOSE cur;
END //
DELIMITER ;
*Performance Warning:* Databases are optimized for set-based operations. Cursors execute row-by-row ($O(n)$ procedural execution) and should only be used when set-based SQL logic is impossible.
43 What is a trigger? Medium
A stored procedure that automatically executes in response to a DML event (INSERT, UPDATE, DELETE) or DDL event (CREATE, ALTER, DROP). Components: Event (when), Condition (optional), Action (what to do).
44 A stored procedure auto-executing on INSERT/UPDATE/DELETE? Medium
A specialized database procedure that automatically executes in response to data modification events (INSERT, UPDATE, or DELETE) on a specific table is called a Trigger:
CREATE TRIGGER before_order_insert
BEFORE INSERT ON orders
FOR EACH ROW
BEGIN
IF NEW.order_total < 0 THEN
SIGNAL SQLSTATE '45000'
SET MESSAGE_TEXT = 'Order total cannot be negative';
END IF;
END;
### Common Use Cases for Triggers:
- Automated audit logging (recording who modified a record and when into an audit table).
- Enforcing complex multi-table business validation rules.
- Maintaining real-time summary aggregation tables.
All 44 questions loaded
Frequently Asked Questions About SQL & Databases Interviews
What do hiring managers evaluate in SQL & Databases technical rounds?
Technical interviewers look for foundational fluency, idiomatic syntax, clarity when communicating complex logic, and awareness of performance trade-offs (e.g. memory footprint, render performance, and network latency) in production environments.
What are the best interview tips for practicing SQL & Databases questions?
Use active recall: summarize each answer in your own words before revealing the model solution. Focus on explaining why a certain approach is chosen rather than just memorizing code syntax.