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
65Total
10Queries
8Joins
6Window Fns
5Indexes
5Normal.
Progress saved locally. Check off questions — saves to your browser. No account needed.
0
/ 40 Done
01 What is the difference between DELETE, TRUNCATE, and DROP? SQL
CommandTypeRollbackSpeed
DELETEDMLYesSlower (logs each row)
TRUNCATEDDLLimitedFaster (deallocates pages)
DROPDDLNoFastest (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.
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).
Mnemonic: "The key, the whole key, and nothing but the key."
05 What is the difference between UNION and UNION ALL? SQL
FeatureUNIONUNION ALL
DuplicatesRemovesKeeps all
PerformanceSlower (sorts to remove dups)Faster
Use caseWhen you need unique resultsWhen 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:
  • 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.
07 What are DDL, DML, DCL, and TCL? Give examples of each. SQL
SQL commands are grouped into four categories based on their purpose:
CategoryFull FormCommandsPurpose
DDLData Definition LanguageCREATE, ALTER, DROP, TRUNCATEDefine/modify database structure
DMLData Manipulation LanguageINSERT, UPDATE, DELETE, SELECTManipulate data in tables
DCLData Control LanguageGRANT, REVOKEControl access permissions
TCLTransaction Control LanguageCOMMIT, ROLLBACK, SAVEPOINTManage transactions
Key point: DDL commands are auto-committed and cannot be rolled back. DML changes can be rolled back within a transaction.
08 What is the difference between CHAR and VARCHAR? When should you use each? SQL
FeatureCHARVARCHAR
StorageFixed-length (pads with spaces)Variable-length (no padding)
PerformanceFaster for fixed-size dataMore space-efficient
Max size255 bytes65,535 bytes
Use caseCountry codes, phone numbers, status flagsNames, emails, descriptions
sql
CREATE TABLE users (
    country_code CHAR(2),       -- Always 2 chars: 'IN', 'US'
    email        VARCHAR(255)    -- Varies in length
);
09 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:
  • 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;
10 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.
11 What is the difference between WHERE and HAVING? SQL
WHERE filters rows before grouping and cannot see aggregates. HAVING filters groups after aggregation and is the only place an aggregate can be tested. SELECT dept FROM emp WHERE salary > 50000 GROUP BY dept HAVING COUNT(*) > 5 reads as: keep the well-paid rows, group them, then keep the departments with more than five of them.
12 What does DISTINCT actually cost? SQL
It forces the database to de-duplicate the whole result — a sort or a hash over every returned row, which is why it turns a cheap query expensive on a large set. DISTINCT appearing in a query is often a sign that a join is fanning out rows; fixing the join usually beats deduplicating after the fact.
13 What is an alias, and when does it change behaviour rather than just readability? SQL
AS renames a column or table for the duration of the query. A table alias is required when self-joining, since both sides need distinguishing. A column alias defined in SELECT is not visible to WHERE — the clauses are evaluated in the order FROM → WHERE → GROUP BY → HAVING → SELECT → ORDER BY, so only ORDER BY can see it.
14 Compare LIKE, wildcards, and why %term% is slow. SQL
% matches any run of characters and _ matches exactly one. A pattern anchored at the start ('abc%') can use a B-tree index, because the index is ordered by prefix. A leading wildcard ('%abc%') cannot — the database must test every row. When you need infix search on a large table, that is what full-text indexing exists for.
15 What is the DEFAULT constraint, and how does it interact with NULL? SQL
DEFAULT supplies a value when the column is omitted from an INSERT. It does not fire when you insert NULL explicitly — that is an instruction to store nothing, and it succeeds unless the column is also NOT NULL. Pairing NOT NULL DEFAULT is the usual way to guarantee a column always has a usable value.
16 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;
17 What is the difference between JOIN and UNION? SQL
AspectJOINUNION
PurposeCombine columns from tablesCombine rows from queries
ResultWider (more columns)Longer (more rows)
RequirementJOIN conditionSame column structure
18 What is a self-join? Give an example. SQL
A self-join joins a table to itself — useful for hierarchical data.
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;
Use cases: Org charts, category hierarchies, finding duplicates.
19 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
);
20 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.
sql
-- Generate all size-color combinations
SELECT s.size, c.color
FROM sizes s
CROSS JOIN colors c;
Use cases: Generating test data, combinations, permutations.
Caution: Can produce very large results (rows = A × B).
21 Walk through all four join types on the same two tables. SQL
With users and orders: INNER returns only users who have orders. LEFT returns every user, with NULLs where there are no orders — the one you want for "users and their order count, including zero". RIGHT is the mirror, and is rare because most people reorder the tables and use LEFT instead. FULL OUTER returns everything from both sides, matched where possible — useful for reconciliation, finding rows that exist on one side only.
22 How do you find rows in one table with no match in another? SQL
A LEFT JOIN with IS NULL on the right side, or NOT EXISTS. Both are correct; NOT EXISTS usually reads better and, unlike NOT IN, behaves sanely when the subquery can return NULLNOT IN with a single NULL in the list returns no rows at all, which is the classic silent-wrong-answer bug.
23 What is a lateral join, and what problem does it solve? SQL
LATERAL (or CROSS APPLY in SQL Server) lets the right-hand subquery reference columns from the left, so it is evaluated once per left row. That is what makes "top N per group" expressible directly — the three most recent orders for each customer — without window functions or a correlated mess.
24 What is a self-join and when do you need one? SQL
A table joined to itself under two aliases. It is how you relate rows within one table: an employee to their manager in the same employees table, or a row to the previous row in a sequence. Both sides need aliases so the columns can be told apart.
25 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:
  • 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;
26 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.
sql
WITH high_earners AS (
    SELECT id, name, salary
    FROM employees
    WHERE salary > 100000
)
SELECT AVG(salary) FROM high_earners;
Benefits:
  • More readable than nested subqueries
  • Can be referenced multiple times
  • Supports recursion (hierarchical queries)
27 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;
28 What is the difference between a view and a materialized view? SQL
AspectViewMaterialized View
StorageVirtual (no storage)Physical (stored on disk)
PerformanceRuns query each timeFast (pre-computed)
Data freshnessAlways currentNeeds refresh
Use caseSimple abstractionComplex aggregations
29 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:
  • Primary key (automatic) and foreign keys
  • Columns used in WHERE clauses
  • Columns used in JOIN conditions
  • Columns used in ORDER BY
Avoid indexing:
  • Small tables
  • Columns with many NULLs
  • Frequently updated columns
30 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:
sql
-- Runs once, result used by outer query
SELECT name FROM employees
WHERE salary > (SELECT AVG(salary) FROM employees);
Correlated subquery — references the outer query, re-executes for each row:
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.
31 What are stored procedures and triggers? How do they differ? SQL
FeatureStored ProcedureTrigger
ExecutionCalled explicitlyFires automatically on event
Trigger eventN/AINSERT, UPDATE, DELETE
Use caseBusiness logic, reusable SQLAuditing, validation, cascades
ParametersAccepts IN/OUT paramsNo 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());
32 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.
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;
33 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.
34 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;
35 What are transaction isolation levels? What is a dirty read? SQL
Isolation levels control how concurrent transactions interact with each other's data.
LevelDirty ReadNon-Repeatable ReadPhantom Read
READ UNCOMMITTED Yes Yes Yes
READ COMMITTED No Yes Yes
REPEATABLE READ No No Yes
SERIALIZABLE No No No
Dirty read — reading data that another transaction has modified but not yet committed.
Default: Most databases default to READ COMMITTED. MySQL (InnoDB) defaults to REPEATABLE READ.
36 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
);
37 Compare COALESCE, ISNULL and NVL. SQL
All substitute a fallback for NULL. COALESCE is standard SQL, takes any number of arguments and returns the first non-NULL one — prefer it. ISNULL (SQL Server) and NVL (Oracle) are vendor-specific two-argument forms. NULLIF(a, b) is the inverse: it produces NULL when the two are equal, which is the standard guard against division by zero.
38 When do you use EXISTS instead of IN? SQL
EXISTS stops at the first match, so it suits a correlated check against a large subquery. IN materialises the list, which is fine when the list is small and constant. The real difference is NULL: NOT IN against a subquery containing a NULL returns nothing, because the comparison is unknown rather than false. NOT EXISTS does not have that trap.
39 What do ANY and ALL do? SQL
They compare a value against every result of a subquery. > ANY (…) is true if it beats at least one — equivalent to beating the minimum. > ALL (…) is true only if it beats every one — beating the maximum. = ANY is exactly IN.
40 What is a recursive CTE, and what stops it running forever? SQL
A common table expression that references itself: an anchor query, UNION ALL, then a step that joins back to the CTE. It walks hierarchies — org charts, category trees, graph paths — to arbitrary depth. It terminates when the recursive step returns no new rows; a cycle in the data will loop, so guard with a depth counter or track the visited path in an array.
41 What is a temporary table, and how does it differ from a CTE? SQL
A temp table is physically created and lives for the session, so it can be indexed, written to more than once, and read by several statements. A CTE is scoped to a single statement and is usually inlined by the optimiser. Reach for a temp table when the same intermediate result is used repeatedly or is large enough to want an index; a CTE when it is a naming convenience within one query.
42 What is dynamic SQL, and what does it cost you? SQL
SQL built as text at runtime, then executed — needed when the table, column or pivot list is not known until the query runs. It costs the plan cache (a new statement text is a new plan) and it is the shortest path to an injection hole. Bind every value as a parameter, and allow-list any identifier you must interpolate; never concatenate user input.
43 How do you optimize a slow SQL query? SQL
Optimization techniques:
  1. Use EXPLAIN to analyze the query plan
  2. Add appropriate indexes
  3. Avoid SELECT * — only fetch needed columns
  4. Use WHERE to filter early
  5. Avoid functions on indexed columns in WHERE
  6. Use EXISTS instead of IN for subqueries
  7. Partition large tables
  8. Update table statistics
Pro tip: Always test with realistic data volumes.
44 What is a query execution plan? SQL
An execution plan shows how the database engine will execute a query.

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';
45 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.
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 (...)")
Solutions:
  • Eager loading (JOIN or IN clause)
  • Batch loading
  • Use ORM features like select_related (Django)
46 What is database sharding? When should you use it? SQL
Sharding is horizontal partitioning — splitting a large table across multiple databases/servers.

Sharding strategies:
  • Key-based (hash of key)
  • Range-based (by date, ID range)
  • Directory-based (lookup service)
Use when:
  • 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.
47 What is the difference between clustered and non-clustered indexes? SQL
FeatureClustered IndexNon-Clustered Index
StorageData rows are physically sorted by this indexSeparate structure, points to data rows
Count per tableOnly oneMultiple allowed
SpeedFaster for range queriesExtra lookup step needed
DefaultPrimary key creates it automaticallyCreated 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.
48 What is table partitioning? How does it differ from sharding? SQL
AspectPartitioningSharding
ScopeWithin a single database/serverAcross multiple servers
TransparencyTransparent to the applicationApplication must be aware
ComplexityLow–MediumHigh
Use caseLarge tables, time-series dataWrite-heavy, massive scale
49 A query is slow. What do you do, in order? SQL
Confirm it is the query and not the surrounding code. Run EXPLAIN ANALYZE and find the node with the largest actual time. Check estimated against actual rows — a large gap means stale statistics, and refreshing them fixes more slow queries than rewriting does. Then look for a scan that an index would turn into a seek. Rewrite the SQL last, and re-measure after each change so you know which one worked.
50 What makes a good composite index? SQL
Column order. An index on (a, b) serves WHERE a = ? and WHERE a = ? AND b = ?, but not WHERE b = ? alone — the index is sorted by a first, so without it there is no starting point. Put the column you always filter on first, and the most selective one early. A covering index that also contains the selected columns lets the query be answered from the index alone.
51 What is plan caching, and how does it interact with parameters? SQL
The database caches the compiled plan so repeated statements skip planning. Parameterised queries share one plan across all values, which is faster and is another reason to use them. The flip side is parameter sniffing: the plan is built for the first value seen, which can be wrong for a later, very different one — the reason a query is sometimes fast for one customer and slow for another.
52 What are optimizer hints, and when are they justified? SQL
Directives that force an index, a join method or a join order. They are a last resort: a hint that is right today freezes the plan against tomorrow, when the data has grown or the distribution has shifted, and the optimiser can no longer adapt. Fix the statistics, the index or the query first; keep a hint only with a comment recording why, and revisit it.
53 What is query parallelism, and when does it hurt? SQL
The database splits a query across several worker threads and merges the results, which helps large scans and aggregations. It hurts on small queries, where coordination costs more than the work, and under high concurrency, where every query grabbing workers starves the pool. Most engines expose a cost threshold below which they stay serial.
54 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.
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,))
Prevention methods:
  • 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.
55 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.
56 What is database encryption? When is it applied? SQL
Database encryption protects data from unauthorized access at rest or in transit.

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.
57 What is the difference between OLTP and OLAP databases? SQL
AspectOLTPOLAP
PurposeDay-to-day operationsBusiness intelligence, reporting
Query typeSimple, fast CRUDComplex aggregations over large data
Data volumeGigabytesTerabytes to Petabytes
ExamplesBanking, e-commerce, ERPData warehouses, dashboards
58 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:
  • 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).
59 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:
  • 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.
60 What are replication, mirroring, and clustering in databases? SQL
All three are high-availability and scalability strategies, but they serve different purposes:
StrategyWhat it doesPrimary goal
ReplicationCopies data from one DB to one or more replicas (can be async)Read scalability, disaster recovery
MirroringMaintains an exact duplicate database in sync (synchronous)High availability, automatic failover
ClusteringMultiple servers share the same storage, appear as one DBLoad balancing, failover, zero downtime
Real world: Most production systems combine these — e.g., a clustered primary with replicas for read-heavy workloads.
61 Explain COMMIT, ROLLBACK, SAVEPOINT and checkpoints. SQL
COMMIT makes a transaction's changes permanent and visible. ROLLBACK discards them entirely. SAVEPOINT marks a point you can roll back to, undoing part of a transaction while keeping the rest. A checkpoint is internal housekeeping, not something you issue per transaction: the engine flushes dirty pages to disk so recovery after a crash has less log to replay.
62 What are the transaction isolation levels, and which anomaly does each allow? SQL
READ UNCOMMITTED allows dirty reads (seeing uncommitted data). READ COMMITTED prevents those but allows non-repeatable reads (the same row read twice differs). REPEATABLE READ prevents those but allows phantoms (the same query returns a different set of rows). SERIALIZABLE prevents all three, at the cost of the most blocking. Most systems default to READ COMMITTED as the practical middle.
63 What is a deadlock, and how do you reduce them? SQL
Two transactions each hold a lock the other needs, so neither can proceed; the database detects the cycle and aborts one. Reduce them by touching tables in the same order everywhere, keeping transactions short, taking the narrowest locks you can, and avoiding user interaction inside a transaction. Under load they are normal, not exceptional — the application should catch the deadlock error and retry.
64 What is referential integrity, and what is an orphan record? SQL
The guarantee that every foreign key points at a row that exists. An orphan is a row where that has stopped being true — a child whose parent was deleted — which happens when the constraint is missing or was disabled for a bulk load. ON DELETE decides the behaviour: CASCADE removes the children, RESTRICT refuses the delete, SET NULL orphans them deliberately.
65 Sharding, partitioning and replication — what is the difference? SQL
Partitioning splits one table into segments inside one database, letting the planner skip segments that cannot match. Sharding splits the dataset across separate databases on separate servers, buying write throughput at the cost of cross-shard joins and transactions. Replication copies data to replicas for read scale-out and failover, at the cost of replica lag: a read straight after a write may not see it.
No questions match your search.