Complete Interview Questions & Answer Bank
50 curated SQL technical interview questions ranging from fundamental syntax and database design to advanced analytical window functions, query execution plans, and concurrency control.
Q1: What is the difference between SQL (Relational) and NoSQL (Non-Relational) databases?
SQL databases are relational, structured, and enforce a predefined schema. They store data in tables composed of rows and columns, leveraging ACID properties to guarantee transactional consistency.
NoSQL databases are non-relational, schema-flexible, and designed for horizontal scalability across distributed clusters. They utilize dynamic data models including Key-Value pairs, Document stores (JSON/BSON), Wide-Column stores, and Property Graphs.
Relational Tables vs Key-Value / Document / GraphVertical (Scale-Up) vs Horizontal (Scale-Out)ACID vs BASE (Eventually Consistent)- SQL databases excel at complex JOIN queries and strict transactional consistency (ACID).
- NoSQL databases excel at handling unstructured or rapidly changing data at massive distributed scale.
Q2: What are DDL, DML, DCL, TCL, and DQL in SQL?
SQL statements are categorized into five sublanguages based on operational scope:
- DDL (Data Definition Language): Defines and alters schema structures. Commands:
CREATE,ALTER,DROP,TRUNCATE,RENAME. - DML (Data Manipulation Language): Modifies stored data rows. Commands:
INSERT,UPDATE,DELETE,MERGE. - DQL (Data Query Language): Retrieves records from schemas. Command:
SELECT. - DCL (Data Control Language): Manages permissions and administrative privileges. Commands:
GRANT,REVOKE. - TCL (Transaction Control Language): Manages atomic transactional changes. Commands:
COMMIT,ROLLBACK,SAVEPOINT.
- DDL alters schema metadata; DML and DQL operate directly on table data rows.
- TCL manages state persistence across transactions; DCL enforces security permissions.
Q3: What are the differences between Primary Key, Foreign Key, and Unique Key constraints?
Keys enforce entity integrity and relationship constraints within relational schemas:
- Primary Key: Uniquely identifies each record in a table. Enforces non-nullability and uniqueness. A table can have only one Primary Key (which can be composite).
- Unique Key: Ensures all values in a column or column group are distinct. Allows one or more
NULLvalues (database dependent). - Foreign Key: Maintains referential integrity by linking a column in a child table to the Primary Key or Unique Key of a parent table.
- A table has exactly one Primary Key, which strictly forbids NULL values.
- Foreign Keys enforce referential integrity across relational boundaries.
Q4: What is the logical execution order of an SQL query?
Although an SQL query is written starting with SELECT, the database engine processes clauses in a distinct logical order to construct result sets.
- WHERE evaluates before GROUP BY and aggregations, whereas HAVING evaluates after GROUP BY.
- Column aliases defined in SELECT cannot be used directly in WHERE or HAVING clauses.
Q5: What is the difference between the WHERE and HAVING clauses?
The fundamental difference lies in aggregation pipeline execution timing:
- WHERE: Filters individual records before group aggregations occur. It cannot evaluate aggregate functions like
SUM(),AVG(), orCOUNT(). - HAVING: Filters aggregated groups after the
GROUP BYstep finishes computing group statistics.
SELECT department_id, COUNT(*) AS employee_count
FROM employees
WHERE status = 'ACTIVE' -- Filters raw rows first
GROUP BY department_id
HAVING COUNT(*) > 5; -- Filters aggregated groups- WHERE operates on individual records; HAVING operates on aggregated groups.
- Filtering records as early as possible with WHERE improves performance by reducing group calculation payload size.
Q6: Explain INNER, LEFT, RIGHT, FULL, and CROSS JOINs with examples.
JOIN clauses combine columns from one or more tables using related attributes:
- INNER JOIN: Returns only matching records existing in both tables.
- LEFT (OUTER) JOIN: Returns all records from the left table and matching records from the right table. Unmatched right values return
NULL. - RIGHT (OUTER) JOIN: Returns all records from the right table and matching left records.
- FULL (OUTER) JOIN: Returns all records when a match exists in either left or right table.
- CROSS JOIN: Produces the Cartesian product of both tables (N × M rows).
- LEFT JOIN guarantees all rows from the primary left table are retained.
- CROSS JOIN produces N * M rows and should be used with caution on large dataset sizes.
Q7: What is the difference between DELETE, TRUNCATE, and DROP commands?
These commands clear records or schema definitions with varying performance and transactional characteristics.
DML | Row-by-Row | Slow | RollbackableDDL | Page Allocation Reset | FastDDL | Schema Removal | Destructive- TRUNCATE is a high-performance DDL operation that resets identity seeds and deallocates data pages.
- DELETE supports conditional WHERE filtering and logs individual row removals.
Q8: How does SQL evaluate NULL values and Three-Valued Logic?
NULL in SQL represents an unknown or missing value, not zero or an empty string ('').
Because NULL is unknown, direct equality comparisons (field = NULL or NULL = NULL) evaluate to UNKNOWN, not TRUE or FALSE. SQL utilizes Three-Valued Logic (TRUE, FALSE, UNKNOWN).
To check for missing values, use IS NULL or IS NOT NULL. Functions like COALESCE(col, fallback) or NVL() replace NULL values with predefined defaults.
-- Incorrect: evaluates to UNKNOWN for nulls
SELECT * FROM employees WHERE commission_pct = NULL;
-- Correct: handles null check explicitly
SELECT * FROM employees WHERE commission_pct IS NULL;
-- Replacing null values in calculations
SELECT employee_id, salary + COALESCE(commission_pct, 0) AS total_comp
FROM employees;- Arithmetic operations involving NULL return NULL (
100 + NULL = NULL). - Always use
IS NULLorCOALESCE()when comparing columns that permit nullability.
Q9: How do GROUP BY and Aggregate Functions work, and how are NULLs handled?
GROUP BY collapses set rows sharing common values into summary groups. Aggregate functions (SUM(), AVG(), COUNT(), MIN(), MAX()) summarize each group.
NULL Handling in Aggregates
COUNT(*)counts all rows, including rows containingNULLvalues.COUNT(column_name)counts only non-null values in that column.SUM(),AVG(),MIN(), andMAX()automatically ignoreNULLvalues during calculation.
COUNT(*)includes NULL rows;COUNT(column)ignores NULL entries.- All non-aggregated columns listed in the SELECT clause must be included in the GROUP BY clause.
Q10: What is the difference between UNION and UNION ALL?
Both operators merge result sets from multiple SELECT queries into a single output set. They require matching column counts and compatible data types across positional indices.
- UNION: Combines result sets and performs an implicit duplicate elimination pass (sorting or hashing output records).
- UNION ALL: Concatenates result sets directly without deduplication, preserving all records.
-- UNION ALL avoids expensive sorting overhead
SELECT customer_id, city FROM domestic_customers
UNION ALL
SELECT customer_id, city FROM international_customers;- UNION performs duplicate removal; UNION ALL retains all rows directly.
- UNION ALL offers superior performance because it avoids expensive memory sorting or hash deduplication operations.