Interview Prep — SQL Track
SQL Interview Questions
40+ SQL questions — joins, window functions, subqueries, indexes, normalization, and query optimization. Tested at virtually every backend and data role.
QueriesJoinsWindow FnsIndexesNormalization
40+Total
10Queries
8Joins
6Window Fns
5Indexes
5Normal.
01
What is the difference between DELETE, TRUNCATE, and DROP?
SQL
▾
| Command | Type | Rollback | Speed |
|---|---|---|---|
DELETE | DML | Yes | Slower (logs each row) |
TRUNCATE | DDL | Limited | Faster (deallocates pages) |
DROP | DDL | No | Fastest (removes table) |
Note: TRUNCATE resets auto-increment counters; DELETE does not.
02
Explain the difference between WHERE and HAVING clauses.
SQL
▾
WHERE: Filters rows before grouping. Cannot use aggregate functions.
HAVING: Filters groups after GROUP BY. Can use aggregate functions.
HAVING: Filters groups after GROUP BY. Can use aggregate functions.
sql
-- WHERE filters before grouping SELECT dept, COUNT(*) AS emp_count FROM employees WHERE salary > 50000 GROUP BY dept HAVING COUNT(*) > 5;
03
What are the different types of SQL constraints?
SQL
▾
- PRIMARY KEY: Uniquely identifies each row. Cannot be NULL.
- FOREIGN KEY: Enforces referential integrity between tables.
- UNIQUE: Ensures all values in a column are different.
- NOT NULL: Column cannot have NULL values.
- CHECK: Validates that values meet a condition.
- DEFAULT: Sets a default value if none is provided.
sql
CREATE TABLE users ( id INT PRIMARY KEY, email VARCHAR(255) UNIQUE NOT NULL, age INT CHECK (age >= 18), status VARCHAR(20) DEFAULT 'active', dept_id INT REFERENCES departments(id) );
04
What is normalization? Explain 1NF, 2NF, and 3NF.
SQL
▾
Normalization organizes data to reduce redundancy and improve integrity.
1NF (First Normal Form): Each column contains atomic values; no repeating groups.
2NF: 1NF + no partial dependency (all columns depend on the entire primary key).
3NF: 2NF + no transitive dependency (non-key columns depend only on the primary key).
1NF (First Normal Form): Each column contains atomic values; no repeating groups.
2NF: 1NF + no partial dependency (all columns depend on the entire primary key).
3NF: 2NF + no transitive dependency (non-key columns depend only on the primary key).
Mnemonic: "The key, the whole key, and nothing but the key."
05
What is the difference between UNION and UNION ALL?
SQL
▾
| Feature | UNION | UNION ALL |
|---|---|---|
| Duplicates | Removes | Keeps all |
| Performance | Slower (sorts to remove dups) | Faster |
| Use case | When you need unique results | When duplicates are OK |
06
What is a transaction? Explain ACID properties.
SQL
▾
A transaction is a sequence of operations performed as a single logical unit of work.
ACID Properties:
ACID Properties:
- Atomicity: All or nothing — either all operations succeed or all fail.
- Consistency: Database remains in a valid state before and after.
- Isolation: Concurrent transactions don't interfere with each other.
- Durability: Once committed, changes persist even after system failure.
21
What are DDL, DML, DCL, and TCL? Give examples of each.
SQL
▾
SQL commands are grouped into four categories based on their purpose:
| Category | Full Form | Commands | Purpose |
|---|---|---|---|
| DDL | Data Definition Language | CREATE, ALTER, DROP, TRUNCATE | Define/modify database structure |
| DML | Data Manipulation Language | INSERT, UPDATE, DELETE, SELECT | Manipulate data in tables |
| DCL | Data Control Language | GRANT, REVOKE | Control access permissions |
| TCL | Transaction Control Language | COMMIT, ROLLBACK, SAVEPOINT | Manage transactions |
Key point: DDL commands are auto-committed and cannot be rolled back. DML changes can be rolled back within a transaction.
22
What is the difference between CHAR and VARCHAR? When should you use each?
SQL
▾
| Feature | CHAR | VARCHAR |
|---|---|---|
| Storage | Fixed-length (pads with spaces) | Variable-length (no padding) |
| Performance | Faster for fixed-size data | More space-efficient |
| Max size | 255 bytes | 65,535 bytes |
| Use case | Country codes, phone numbers, status flags | Names, emails, descriptions |
sql
CREATE TABLE users ( country_code CHAR(2), -- Always 2 chars: 'IN', 'US' email VARCHAR(255) -- Varies in length );
23
What is a NULL value? How do you handle NULLs in SQL?
SQL
▾
NULL represents missing, unknown, or inapplicable data — it is not zero or an empty string.
Key behaviours:
Key behaviours:
- Any comparison with NULL returns UNKNOWN (use
IS NULL/IS NOT NULL) - Arithmetic with NULL produces NULL
- Aggregate functions (COUNT, SUM) ignore NULLs except
COUNT(*)
sql
-- Wrong: this never matches SELECT * FROM users WHERE phone = NULL; -- Correct SELECT * FROM users WHERE phone IS NULL; -- COALESCE: return first non-null value SELECT COALESCE(phone, 'N/A') FROM users;
24
What is the CASE statement in SQL? Give an example.
SQL
▾
The CASE statement implements conditional logic directly in SQL — similar to if/else in programming.
sql
-- Simple CASE SELECT name, CASE status WHEN 'A' THEN 'Active' WHEN 'I' THEN 'Inactive' ELSE 'Unknown' END AS status_label FROM users; -- Searched CASE (with conditions) SELECT name, salary, CASE WHEN salary < 50000 THEN 'Junior' WHEN salary < 100000 THEN 'Mid' ELSE 'Senior' END AS level FROM employees;
Use cases: Salary banding, conditional aggregation, data transformation, pivoting rows to columns.
Joins
07
Explain the different types of SQL JOINs.
SQL
▾
- INNER JOIN: Returns only matching rows from both tables.
- LEFT (OUTER) JOIN: All rows from left table + matching from right. NULLs for non-matches.
- RIGHT (OUTER) JOIN: All rows from right table + matching from left.
- FULL (OUTER) JOIN: All rows from both tables. NULLs where no match.
- CROSS JOIN: Cartesian product — every row paired with every row.
sql
-- LEFT JOIN example SELECT e.name, d.dept_name FROM employees e LEFT JOIN departments d ON e.dept_id = d.id;
08
What is the difference between JOIN and UNION?
SQL
▾
| Aspect | JOIN | UNION |
|---|---|---|
| Purpose | Combine columns from tables | Combine rows from queries |
| Result | Wider (more columns) | Longer (more rows) |
| Requirement | JOIN condition | Same column structure |
09
What is a self-join? Give an example.
SQL
▾
A self-join joins a table to itself — useful for hierarchical data.
Use cases: Org charts, category hierarchies, finding duplicates.
sql
-- Find employees and their managers SELECT e.name AS employee, m.name AS manager FROM employees e LEFT JOIN employees m ON e.manager_id = m.id;
10
How do you find duplicate records in a table?
SQL
▾
sql
-- Find duplicates by email SELECT email, COUNT(*) AS cnt FROM users GROUP BY email HAVING COUNT(*) > 1; -- Delete duplicates, keep first DELETE FROM users WHERE id NOT IN ( SELECT MIN(id) FROM users GROUP BY email );
11
What is a CROSS JOIN and when would you use it?
SQL
▾
A CROSS JOIN produces the Cartesian product — every row from table A paired with every row from table B.
Use cases: Generating test data, combinations, permutations.
Caution: Can produce very large results (rows = A × B).
sql
-- Generate all size-color combinations SELECT s.size, c.color FROM sizes s CROSS JOIN colors c;
Caution: Can produce very large results (rows = A × B).
Advanced
12
What are window functions? Explain ROW_NUMBER, RANK, and DENSE_RANK.
SQL
▾
Window functions perform calculations across rows related to the current row without collapsing them.
Ranking functions:
Ranking functions:
ROW_NUMBER()— Unique sequential number (1, 2, 3, 4)RANK()— Skips after ties (1, 2, 2, 4)DENSE_RANK()— No gaps after ties (1, 2, 2, 3)
sql
SELECT name, salary, ROW_NUMBER() OVER (ORDER BY salary DESC) AS row_num, RANK() OVER (ORDER BY salary DESC) AS rank_num, DENSE_RANK() OVER (ORDER BY salary DESC) AS dense_rank FROM employees;
13
What is a CTE (Common Table Expression)? When should you use it?
SQL
▾
A CTE is a temporary result set defined within a query using the WITH clause.
Benefits:
sql
WITH high_earners AS ( SELECT id, name, salary FROM employees WHERE salary > 100000 ) SELECT AVG(salary) FROM high_earners;
- More readable than nested subqueries
- Can be referenced multiple times
- Supports recursion (hierarchical queries)
14
How do you find the Nth highest salary?
SQL
▾
sql
-- Method 1: Using DENSE_RANK (recommended) SELECT salary FROM ( SELECT salary, DENSE_RANK() OVER (ORDER BY salary DESC) AS rnk FROM employees ) t WHERE rnk = 3; -- Method 2: Using LIMIT/OFFSET (MySQL, PostgreSQL) SELECT DISTINCT salary FROM employees ORDER BY salary DESC LIMIT 1 OFFSET 2;
15
What is the difference between a view and a materialized view?
SQL
▾
| Aspect | View | Materialized View |
|---|---|---|
| Storage | Virtual (no storage) | Physical (stored on disk) |
| Performance | Runs query each time | Fast (pre-computed) |
| Data freshness | Always current | Needs refresh |
| Use case | Simple abstraction | Complex aggregations |
16
What are indexes? When should you create them?
SQL
▾
An index is a data structure that speeds up data retrieval at the cost of slower writes.
Create indexes on:
Create indexes on:
- Primary key (automatic) and foreign keys
- Columns used in WHERE clauses
- Columns used in JOIN conditions
- Columns used in ORDER BY
- Small tables
- Columns with many NULLs
- Frequently updated columns
25
What is a subquery? Difference between correlated and non-correlated subquery?
SQL
▾
A subquery is a query nested inside another query.
Non-correlated subquery — executes independently, once:
Correlated subquery — references the outer query, re-executes for each row:
Non-correlated subquery — executes independently, once:
sql
-- Runs once, result used by outer query SELECT name FROM employees WHERE salary > (SELECT AVG(salary) FROM employees);
sql
-- Runs for every row in 'e' SELECT e.name FROM employees e WHERE e.salary = ( SELECT MAX(salary) FROM employees WHERE dept_id = e.dept_id -- references outer 'e' );
Performance: Correlated subqueries can be slow on large datasets. Prefer JOINs or CTEs where possible.
26
What are stored procedures and triggers? How do they differ?
SQL
▾
| Feature | Stored Procedure | Trigger |
|---|---|---|
| Execution | Called explicitly | Fires automatically on event |
| Trigger event | N/A | INSERT, UPDATE, DELETE |
| Use case | Business logic, reusable SQL | Auditing, validation, cascades |
| Parameters | Accepts IN/OUT params | No parameters |
sql
-- Stored Procedure CREATE PROCEDURE GetEmployeesByDept(IN dept INT) BEGIN SELECT * FROM employees WHERE dept_id = dept; END; -- Trigger: log every salary update CREATE TRIGGER log_salary_change AFTER UPDATE ON employees FOR EACH ROW INSERT INTO audit_log VALUES (OLD.salary, NEW.salary, NOW());
27
What is a recursive CTE? When would you use it?
SQL
▾
A recursive CTE references itself to process hierarchical or tree-structured data (e.g., org charts, file systems).
It has two parts: an anchor member (base case) and a recursive member that builds on the previous result.
It has two parts: an anchor member (base case) and a recursive member that builds on the previous result.
sql
WITH RECURSIVE org_tree AS ( -- Anchor: start from the top manager SELECT id, name, manager_id, 0 AS level FROM employees WHERE manager_id IS NULL UNION ALL -- Recursive: get each employee's reports SELECT e.id, e.name, e.manager_id, o.level + 1 FROM employees e INNER JOIN org_tree o ON e.manager_id = o.id ) SELECT * FROM org_tree ORDER BY level;
28
What is a cursor in SQL? When should you use or avoid it?
SQL
▾
A cursor allows row-by-row processing of a query result — useful when set-based operations aren't sufficient.
sql
DECLARE emp_cursor CURSOR FOR SELECT id, name FROM employees; OPEN emp_cursor; FETCH NEXT FROM emp_cursor INTO @id, @name; WHILE @@FETCH_STATUS = 0 BEGIN -- process each row FETCH NEXT FROM emp_cursor INTO @id, @name; END; CLOSE emp_cursor; DEALLOCATE emp_cursor;
Avoid cursors when possible — they are slow and resource-intensive. Prefer set-based operations, window functions, or CTEs.
29
What is pivoting and unpivoting in SQL?
SQL
▾
Pivoting rotates rows into columns. Unpivoting does the reverse — converts columns into rows.
sql
-- PIVOT: show monthly sales as columns SELECT product, SUM(CASE WHEN month = 'Jan' THEN sales END) AS Jan, SUM(CASE WHEN month = 'Feb' THEN sales END) AS Feb, SUM(CASE WHEN month = 'Mar' THEN sales END) AS Mar FROM sales_data GROUP BY product; -- UNPIVOT: convert columns back to rows (SQL Server) SELECT product, month, sales FROM sales_pivot UNPIVOT (sales FOR month IN (Jan, Feb, Mar)) u;
30
What are transaction isolation levels? What is a dirty read?
SQL
▾
Isolation levels control how concurrent transactions interact with each other's data.
Dirty read — reading data that another transaction has modified but not yet committed.
| Level | Dirty Read | Non-Repeatable Read | Phantom Read |
|---|---|---|---|
READ UNCOMMITTED | Yes | Yes | Yes |
READ COMMITTED | No | Yes | Yes |
REPEATABLE READ | No | No | Yes |
SERIALIZABLE | No | No | No |
Default: Most databases default to
READ COMMITTED. MySQL (InnoDB) defaults to REPEATABLE READ.
31
What is the difference between a composite key, surrogate key, and candidate key?
SQL
▾
- Candidate key — any column (or combination) that could serve as a primary key.
- Composite key — a primary key formed by combining two or more columns (e.g.,
order_id + product_id). - Surrogate key — an artificial, system-generated unique identifier (typically auto-increment INT or UUID) with no business meaning.
sql
-- Composite key CREATE TABLE order_items ( order_id INT, product_id INT, PRIMARY KEY (order_id, product_id) ); -- Surrogate key CREATE TABLE users ( id INT AUTO_INCREMENT PRIMARY KEY, -- surrogate email VARCHAR(255) UNIQUE -- natural candidate );
Optimization
17
How do you optimize a slow SQL query?
SQL
▾
Optimization techniques:
- Use
EXPLAINto analyze the query plan - Add appropriate indexes
- Avoid
SELECT *— only fetch needed columns - Use WHERE to filter early
- Avoid functions on indexed columns in WHERE
- Use EXISTS instead of IN for subqueries
- Partition large tables
- Update table statistics
Pro tip: Always test with realistic data volumes.
18
What is a query execution plan?
SQL
▾
An execution plan shows how the database engine will execute a query.
Key elements:
Key elements:
- Table access method (scan vs index seek)
- Join algorithms (nested loop, hash join, merge join)
- Sort operations
- Estimated cost and row counts
sql
-- PostgreSQL EXPLAIN ANALYZE SELECT * FROM users WHERE email = 'user@example.com'; -- MySQL EXPLAIN SELECT * FROM users WHERE email = 'user@example.com';
19
What is the N+1 query problem and how do you fix it?
SQL
▾
N+1 problem: Fetching N records, then executing 1 additional query per record.
Solutions:
python
# Bad: N+1 queries for user in users: orders = db.query("SELECT * FROM orders WHERE user_id = ?", user.id) # Good: 2 queries with eager loading users = db.query("SELECT * FROM users") orders = db.query("SELECT * FROM orders WHERE user_id IN (...)")
- Eager loading (JOIN or IN clause)
- Batch loading
- Use ORM features like
select_related(Django)
20
What is database sharding? When should you use it?
SQL
▾
Sharding is horizontal partitioning — splitting a large table across multiple databases/servers.
Sharding strategies:
Sharding strategies:
- Key-based (hash of key)
- Range-based (by date, ID range)
- Directory-based (lookup service)
- Single database can't handle write load
- Data volume exceeds single server capacity
- Need geographic distribution
Trade-offs: Increased complexity, cross-shard joins are expensive, rebalancing is hard.
32
What is the difference between clustered and non-clustered indexes?
SQL
▾
| Feature | Clustered Index | Non-Clustered Index |
|---|---|---|
| Storage | Data rows are physically sorted by this index | Separate structure, points to data rows |
| Count per table | Only one | Multiple allowed |
| Speed | Faster for range queries | Extra lookup step needed |
| Default | Primary key creates it automatically | Created manually on other columns |
Analogy: A clustered index is like a phone book sorted by surname — the data itself is ordered. A non-clustered index is like a book's index — it points you to the right page.
33
What is table partitioning? How does it differ from sharding?
SQL
▾
| Aspect | Partitioning | Sharding |
|---|---|---|
| Scope | Within a single database/server | Across multiple servers |
| Transparency | Transparent to the application | Application must be aware |
| Complexity | Low–Medium | High |
| Use case | Large tables, time-series data | Write-heavy, massive scale |
Security
34
What is SQL injection? How do you prevent it?
SQL
▾
SQL injection is an attack where malicious SQL is inserted into a query, allowing unauthorized data access or manipulation.
Prevention methods:
python
# VULNERABLE: string concatenation query = "SELECT * FROM users WHERE name = '" + user_input + "'" # SAFE: parameterized query cursor.execute("SELECT * FROM users WHERE name = %s", (user_input,))
- Use parameterized queries / prepared statements
- Use an ORM (SQLAlchemy, Django ORM)
- Validate and sanitize all user input
- Apply least-privilege database accounts
- Use stored procedures
Classic payload:
' OR '1'='1 — always evaluates to true, bypassing authentication.
35
What is the principle of least privilege in databases?
SQL
▾
Users and applications should be granted only the minimum database permissions required to perform their tasks — nothing more.
sql
-- Grant only SELECT on specific table GRANT SELECT ON sales.orders TO reporting_user; -- Revoke dangerous permissions REVOKE DROP ON *.* FROM app_user;
Best practice: Create separate DB users for app reads, app writes, admin, and reporting.
36
What is database encryption? When is it applied?
SQL
▾
Database encryption protects data from unauthorized access at rest or in transit.
Types:
Types:
- Encryption at rest — protects stored files/tablespaces (e.g., AES-256, TDE in SQL Server/MySQL).
- Encryption in transit — protects data moving over the network (TLS/SSL connections).
- Column-level encryption — encrypt specific sensitive columns (PII, credit card numbers).
Compliance: GDPR, HIPAA, and PCI-DSS all require encryption of sensitive data.
Architecture
37
What is the difference between OLTP and OLAP databases?
SQL
▾
| Aspect | OLTP | OLAP |
|---|---|---|
| Purpose | Day-to-day operations | Business intelligence, reporting |
| Query type | Simple, fast CRUD | Complex aggregations over large data |
| Data volume | Gigabytes | Terabytes to Petabytes |
| Examples | Banking, e-commerce, ERP | Data warehouses, dashboards |
38
What is data warehousing? What is the ETL process?
SQL
▾
A data warehouse is a central repository that consolidates integrated data from multiple sources, optimized for analysis and reporting.
ETL (Extract, Transform, Load) is the pipeline that feeds a data warehouse:
ETL (Extract, Transform, Load) is the pipeline that feeds a data warehouse:
- Extract — pull raw data from source systems (databases, APIs, files)
- Transform — clean, deduplicate, format, join and aggregate the data
- Load — insert transformed data into the warehouse
Modern trend: ELT (Extract, Load, Transform) — load raw data first, then transform inside the warehouse using its compute power (e.g., Snowflake, BigQuery).
39
What is CDC (Change Data Capture)? What is a transaction log?
SQL
▾
A transaction log is a file that records every modification made to the database in sequential order — the backbone of durability and recovery.
CDC (Change Data Capture) reads the transaction log to detect and capture data changes in near-real-time — without modifying the source database.
CDC use cases:
CDC (Change Data Capture) reads the transaction log to detect and capture data changes in near-real-time — without modifying the source database.
CDC use cases:
- Syncing data to data warehouses or search indexes
- Event-driven microservices (database as event source)
- Audit trails and compliance logging
- Replicating data to read replicas
Tools: Debezium, AWS DMS, Kafka Connect, SQL Server CDC.
40
What are replication, mirroring, and clustering in databases?
SQL
▾
All three are high-availability and scalability strategies, but they serve different purposes:
| Strategy | What it does | Primary goal |
|---|---|---|
| Replication | Copies data from one DB to one or more replicas (can be async) | Read scalability, disaster recovery |
| Mirroring | Maintains an exact duplicate database in sync (synchronous) | High availability, automatic failover |
| Clustering | Multiple servers share the same storage, appear as one DB | Load balancing, failover, zero downtime |
Real world: Most production systems combine these — e.g., a clustered primary with replicas for read-heavy workloads.
No questions match your search.