Interview Preparation

Practice real interview questions with detailed answers

104 Questions
Easy 25 questions
SQL #1.1
Q1: What is SQL?
Ans: SQL (Structured Query Language) is a standard language used to create, query, update, and manage data stored in relational database management systems (RDBMS) like MySQL, PostgreSQL, SQL Server, and Oracle.
SQL #1.2
Q2: What is the difference between SQL and MySQL?
Ans: SQL is a standardized query language for interacting with relational databases, while MySQL is a specific open-source RDBMS software that implements SQL (with some vendor-specific extensions) to store and manage data.
SQL #1.3
Q3: What are the different types of SQL commands?
Ans: SQL commands are grouped into DDL (Data Definition Language: CREATE, ALTER, DROP), DML (Data Manipulation Language: SELECT, INSERT, UPDATE, DELETE), DCL (Data Control Language: GRANT, REVOKE), and TCL (Transaction Control Language: COMMIT, ROLLBACK, SAVEPOINT).
SQL #1.4
Q4: What is the difference between DDL and DML?
Ans: DDL statements define or modify database structure (tables, schemas, indexes) and are auto-committed, while DML statements manipulate the actual data within tables (inserting, updating, deleting, or querying rows) and can typically be rolled back within a transaction.
Code Example
-- DDL
CREATE TABLE users (id INT, name VARCHAR(50));
-- DML
INSERT INTO users VALUES (1, 'Sara');
SQL #1.5
Q5: What is a primary key?
Ans: A primary key is a column or set of columns that uniquely identifies each row in a table; it cannot contain NULL values and a table can have only one primary key.
Code Example
CREATE TABLE users (
  id INT PRIMARY KEY,
  name VARCHAR(50)
);
SQL #1.6
Q6: What is a foreign key?
Ans: A foreign key is a column (or set of columns) in one table that references the primary key of another table, enforcing referential integrity by ensuring the referenced value actually exists in the parent table.
Code Example
CREATE TABLE orders (
  id INT PRIMARY KEY,
  user_id INT,
  FOREIGN KEY (user_id) REFERENCES users(id)
);
SQL #1.7
Q7: What is a NULL value in SQL?
Ans: NULL represents missing, unknown, or inapplicable data; it is not equal to zero, an empty string, or any other value, and comparisons with NULL using = or != always evaluate to unknown rather than true or false, which is why IS NULL / IS NOT NULL must be used.
Code Example
SELECT * FROM users WHERE phone IS NULL;
SQL #1.8
Q8: What is the difference between INNER JOIN and LEFT JOIN?
Ans: INNER JOIN returns only rows that have matching values in both joined tables, while LEFT JOIN returns all rows from the left table regardless of a match, filling in NULLs for columns from the right table when no match exists.
Code Example
SELECT c.name, o.id
FROM customers c
LEFT JOIN orders o ON c.id = o.customer_id;
SQL #1.9
Q9: What are aggregate functions in SQL?
Ans: Aggregate functions perform a calculation across a set of rows and return a single value, including COUNT(), SUM(), AVG(), MIN(), and MAX(), commonly used together with GROUP BY.
Code Example
SELECT dept, AVG(salary) FROM employees GROUP BY dept;
SQL #1.10
Q10: What is the GROUP BY clause used for?
Ans: GROUP BY groups rows that share the same values in specified columns into summary rows, typically used together with aggregate functions to compute per-group statistics like totals or averages.
Code Example
SELECT customer_id, SUM(amount) FROM orders GROUP BY customer_id;
SQL #1.11
Q11: What is the difference between COUNT(*) and COUNT(column_name)?
Ans: COUNT(*) counts all rows regardless of NULL values, while COUNT(column_name) counts only the rows where that specific column's value is not NULL.
Code Example
SELECT COUNT(*), COUNT(phone) FROM users;
SQL #1.12
Q12: What is the difference between COMMIT and ROLLBACK?
Ans: COMMIT permanently saves all changes made during the current transaction to the database, while ROLLBACK undoes all changes made since the transaction began (or since the last savepoint), restoring the previous state.
Code Example
COMMIT;
-- or
ROLLBACK;
SQL #1.13
Q13: What are constraints in SQL?
Ans: Constraints are rules enforced on table columns to maintain data integrity, including NOT NULL, UNIQUE, PRIMARY KEY, FOREIGN KEY, CHECK, and DEFAULT, preventing invalid data from being inserted or updated.
Code Example
CREATE TABLE products (
  id INT PRIMARY KEY,
  price DECIMAL(10,2) CHECK (price > 0)
);
SQL #1.14
Q14: What is the DEFAULT constraint used for?
Ans: The DEFAULT constraint specifies a value to automatically use for a column when no explicit value is provided during an INSERT, ensuring consistent fallback values without requiring application-level logic.
Code Example
CREATE TABLE orders (
  id INT PRIMARY KEY,
  status VARCHAR(20) DEFAULT 'pending'
);
SQL #1.15
Q15: What is the ORDER BY clause used for?
Ans: ORDER BY sorts the rows of a query's result set by one or more columns, ascending (ASC, the default) or descending (DESC).
Code Example
SELECT * FROM products ORDER BY price DESC;
SQL #1.16
Q16: What is the LIMIT (or TOP/FETCH) clause used for?
Ans: LIMIT (MySQL/PostgreSQL) or TOP (SQL Server) or FETCH FIRST (standard SQL/Oracle) restricts the number of rows returned by a query, commonly combined with ORDER BY for pagination or 'top N' style queries.
Code Example
SELECT * FROM products ORDER BY price DESC LIMIT 10;
SQL #1.17
Q17: What are wildcard characters in SQL LIKE?
Ans: % matches any sequence of zero or more characters, and _ matches exactly one character, both used within a LIKE pattern to perform flexible partial string matching.
Code Example
SELECT * FROM products WHERE name LIKE 'App%';
SQL #1.18
Q18: What is the difference between BETWEEN and comparison operators?
Ans: BETWEEN is inclusive shorthand for checking whether a value falls within a range (equivalent to >= AND <=), improving readability compared to writing out two separate comparison conditions.
Code Example
SELECT * FROM orders WHERE order_date BETWEEN '2026-01-01' AND '2026-01-31';
SQL #1.19
Q19: What is an ER (Entity-Relationship) diagram?
Ans: An ER diagram is a visual representation of a database's entities (tables), their attributes (columns), and the relationships between them (one-to-one, one-to-many, many-to-many), commonly used during database design.
SQL #1.20
Q20: What is the purpose of the ALTER TABLE statement?
Ans: ALTER TABLE modifies an existing table's structure, such as adding, dropping, or modifying columns, adding or removing constraints, or renaming the table, without needing to drop and recreate it.
Code Example
ALTER TABLE users ADD COLUMN age INT;
ALTER TABLE users DROP COLUMN age;
SQL #1.21
Q21: What are the ANSI SQL date/time functions commonly used for?
Ans: Common date/time functions include NOW()/CURRENT_TIMESTAMP for the current date and time, DATEADD/DATE_ADD for adding intervals, DATEDIFF for calculating the difference between two dates, and EXTRACT for pulling out a specific part (like year or month) from a date value.
Code Example
SELECT DATEDIFF(NOW(), created_at) AS days_since_signup FROM users;
SQL #1.22
Q22: What is MySQL?
Ans: MySQL is an open-source relational database management system (RDBMS) that uses SQL to store, manage, and retrieve data, widely used in web applications for its speed, reliability, and free licensing.
SQL #1.23
Q23: What is the current stable version of MySQL?
Ans: MySQL 8.0 is the current major stable version, which introduced features like window functions, common table expressions (CTEs), improved JSON support, and better default security compared to MySQL 5.7.
SQL #1.24
Q24: What is the difference between a primary key and a foreign key?
Ans: A primary key uniquely identifies each row within its own table and cannot be NULL, while a foreign key is a column in one table that references the primary key of another table, establishing and enforcing a relationship between the two tables.
SQL #1.25
Q25: Can a table have multiple primary keys?
Ans: No, a table can have only one primary key, though that primary key can be composite, meaning it spans multiple columns that together uniquely identify each row.
Medium 59 questions
SQL #2.1
Q1: What is the difference between a primary key and a unique key?
Ans: Both enforce uniqueness of values in a column, but a table can have only one primary key (which also disallows NULLs) while it can have multiple unique keys, and unique keys do allow a single NULL value (in most databases).
SQL #2.2
Q2: What is a composite key?
Ans: A composite key is a primary key made up of two or more columns that together uniquely identify a row, used when no single column is sufficient to guarantee uniqueness on its own.
Code Example
CREATE TABLE enrollments (
  student_id INT,
  course_id INT,
  PRIMARY KEY (student_id, course_id)
);
SQL #2.3
Q3: What is a candidate key?
Ans: A candidate key is any column or combination of columns that could qualify as the primary key because it uniquely identifies rows; a table may have multiple candidate keys, and one of them is chosen as the primary key.
SQL #2.4
Q4: What is the difference between WHERE and HAVING?
Ans: WHERE filters individual rows before any grouping occurs and cannot reference aggregate functions directly, while HAVING filters groups after GROUP BY has been applied and is used specifically to filter based on aggregate results.
Code Example
SELECT dept, COUNT(*) FROM employees
GROUP BY dept
HAVING COUNT(*) > 5;
SQL #2.5
Q5: What is the difference between DELETE, TRUNCATE, and DROP?
Ans: DELETE removes rows one at a time (optionally filtered by WHERE), is logged, and can be rolled back; TRUNCATE removes all rows at once, resets identity counters, is minimally logged, and is faster but generally cannot target specific rows; DROP removes the entire table structure along with its data.
Code Example
DELETE FROM users WHERE id = 1;
TRUNCATE TABLE users;
DROP TABLE users;
SQL #2.6
Q6: What are the different types of JOINs in SQL?
Ans: The main JOIN types are INNER JOIN (only matching rows in both tables), LEFT JOIN (all rows from the left table plus matches from the right, NULLs where no match), RIGHT JOIN (all rows from the right table plus matches from the left), and FULL OUTER JOIN (all rows from both tables, with NULLs where there's no match on either side).
Code Example
SELECT o.id, c.name
FROM orders o
INNER JOIN customers c ON o.customer_id = c.id;
SQL #2.7
Q7: What is a self join and when would you use one?
Ans: A self join joins a table to itself using table aliases, commonly used to compare rows within the same table, such as finding employees and their managers stored in the same employees table.
Code Example
SELECT e.name AS employee, m.name AS manager
FROM employees e
JOIN employees m ON e.manager_id = m.id;
SQL #2.8
Q8: What is a CROSS JOIN?
Ans: A CROSS JOIN returns the Cartesian product of two tables, pairing every row in the first table with every row in the second table, resulting in a row count equal to the product of the two tables' row counts.
Code Example
SELECT a.color, b.size
FROM colors a CROSS JOIN sizes b;
SQL #2.9
Q9: What is the difference between UNION and UNION ALL?
Ans: UNION combines the result sets of two or more SELECT queries and removes duplicate rows, requiring an internal sort/distinct operation, while UNION ALL combines the results without removing duplicates, making it faster when duplicates are acceptable or known not to exist.
Code Example
SELECT city FROM customers
UNION ALL
SELECT city FROM suppliers;
SQL #2.10
Q10: What are the requirements for using UNION?
Ans: All SELECT statements combined with UNION must have the same number of columns, in the same order, with compatible data types across corresponding columns.
SQL #2.11
Q11: What is a subquery?
Ans: A subquery (or inner query) is a query nested inside another SQL statement (SELECT, INSERT, UPDATE, or DELETE), used to compute a value or set of values that the outer query then uses for filtering, joining, or comparison.
Code Example
SELECT name FROM employees
WHERE salary > (SELECT AVG(salary) FROM employees);
SQL #2.12
Q12: What is the difference between a subquery and a JOIN?
Ans: A JOIN combines columns from multiple tables into a single result set and is often more efficient because the optimizer can plan it as a single set operation, while a subquery nests one query inside another and can sometimes be less efficient, though modern optimizers often rewrite subqueries into equivalent joins internally.
SQL #2.13
Q13: What is a Common Table Expression (CTE)?
Ans: A CTE, defined with the WITH clause, is a named temporary result set that exists only for the duration of a single query, improving readability by breaking complex queries into logical, reusable steps.
Code Example
WITH high_earners AS (
  SELECT * FROM employees WHERE salary > 100000
)
SELECT dept, COUNT(*) FROM high_earners GROUP BY dept;
SQL #2.14
Q14: What is normalization in database design?
Ans: Normalization is the process of organizing tables and columns to minimize data redundancy and avoid update, insertion, and deletion anomalies, typically achieved by decomposing tables through a series of normal forms (1NF, 2NF, 3NF, etc.).
SQL #2.15
Q15: What is First Normal Form (1NF)?
Ans: A table is in 1NF if each column contains only atomic (indivisible) values, each row is unique, and there are no repeating groups or arrays stored within a single column.
SQL #2.16
Q16: What is Second Normal Form (2NF)?
Ans: A table is in 2NF if it is already in 1NF and every non-key column is fully functionally dependent on the entire primary key, not just part of a composite key (eliminating partial dependencies).
SQL #2.17
Q17: What is Third Normal Form (3NF)?
Ans: A table is in 3NF if it is already in 2NF and has no transitive dependencies, meaning non-key columns depend only on the primary key and not on other non-key columns.
SQL #2.18
Q18: What is denormalization and when would you use it?
Ans: Denormalization intentionally introduces redundancy into a database design (e.g., duplicating data or pre-computing aggregates) to reduce the number of joins needed for read-heavy workloads, trading some write complexity and storage for improved query performance.
SQL #2.19
Q19: What is an index in SQL and why is it used?
Ans: An index is a database structure (often a B-tree) that speeds up data retrieval by allowing the database to find rows without scanning the entire table, at the cost of additional storage and slower writes since indexes must also be updated.
Code Example
CREATE INDEX idx_users_email ON users(email);
SQL #2.20
Q20: What are the downsides of adding too many indexes to a table?
Ans: Every additional index increases storage usage and slows down INSERT, UPDATE, and DELETE operations because each index must also be updated whenever the underlying data changes, so indexes should be added deliberately based on actual query patterns.
SQL #2.21
Q21: What is a database transaction?
Ans: A transaction is a sequence of one or more SQL operations executed as a single logical unit of work, which either fully completes (COMMIT) or is fully undone (ROLLBACK), ensuring the database never ends up in a partially-updated, inconsistent state.
Code Example
BEGIN TRANSACTION;
UPDATE accounts SET balance = balance - 100 WHERE id = 1;
UPDATE accounts SET balance = balance + 100 WHERE id = 2;
COMMIT;
SQL #2.22
Q22: What does ACID stand for in the context of databases?
Ans: ACID stands for Atomicity (a transaction fully completes or fully fails), Consistency (a transaction moves the database from one valid state to another), Isolation (concurrent transactions don't interfere with each other), and Durability (once committed, changes survive system failures).
SQL #2.23
Q23: What is the difference between a view and a table?
Ans: A table physically stores data on disk, while a view is a stored, named SELECT query that presents data virtually and is recomputed (or partially materialized, depending on the database) each time it's queried, without storing the data itself.
Code Example
CREATE VIEW active_users AS
SELECT * FROM users WHERE status = 'active';
SQL #2.24
Q24: What is a stored procedure?
Ans: A stored procedure is a precompiled, named collection of SQL statements stored in the database that can accept parameters and be invoked repeatedly, useful for encapsulating complex business logic close to the data.
Code Example
CREATE PROCEDURE GetUserById(IN uid INT)
BEGIN
  SELECT * FROM users WHERE id = uid;
END;
SQL #2.25
Q25: What is the difference between a stored procedure and a function?
Ans: A stored procedure can perform actions (like INSERT/UPDATE/DELETE) and may or may not return a value, and is invoked with CALL, while a user-defined function must return a single value or table and can be used directly within a SELECT statement, but generally cannot modify data.
SQL #2.26
Q26: What is a trigger in SQL?
Ans: A trigger is a stored procedure that automatically executes in response to a specific event (INSERT, UPDATE, or DELETE) on a table, commonly used for enforcing business rules, auditing changes, or maintaining derived data.
Code Example
CREATE TRIGGER before_insert_users
BEFORE INSERT ON users
FOR EACH ROW
SET NEW.created_at = NOW();
SQL #2.27
Q27: What is the difference between CHAR and VARCHAR data types?
Ans: CHAR is a fixed-length string type that pads shorter values with spaces up to the defined length, while VARCHAR is a variable-length string type that only uses as much storage as the actual data requires (plus a small overhead), making VARCHAR generally more space-efficient for variable-length text.
SQL #2.28
Q28: What is the difference between TEXT and VARCHAR?
Ans: VARCHAR requires a defined maximum length and is typically stored inline with the row for faster access, while TEXT (or similar large-object types) is designed for very large, variable-length text and may be stored separately from the row depending on the database engine.
SQL #2.29
Q29: What is the CHECK constraint used for?
Ans: The CHECK constraint enforces that values in a column satisfy a specific boolean condition, rejecting any INSERT or UPDATE that would violate it, such as ensuring an age column is always non-negative.
Code Example
ALTER TABLE employees ADD CONSTRAINT chk_age CHECK (age >= 18);
SQL #2.30
Q30: What is the ON DELETE CASCADE option used for?
Ans: ON DELETE CASCADE, defined on a foreign key, automatically deletes child rows referencing a parent row when that parent row is deleted, maintaining referential integrity without requiring the application to manually clean up related records.
Code Example
FOREIGN KEY (customer_id) REFERENCES customers(id) ON DELETE CASCADE
SQL #2.31
Q31: How do you implement pagination in SQL?
Ans: Pagination is typically implemented using LIMIT combined with OFFSET (or FETCH NEXT ... OFFSET in SQL Server/standard SQL), which skips a specified number of rows before returning the next page's worth of results.
Code Example
SELECT * FROM products ORDER BY id LIMIT 10 OFFSET 20;
SQL #2.32
Q32: What is the difference between LIKE and REGEXP for pattern matching?
Ans: LIKE performs simple pattern matching using wildcards (% for any sequence of characters and _ for a single character), while REGEXP (or RLIKE) supports full regular expression pattern matching, offering much more powerful and complex text matching capabilities.
Code Example
SELECT * FROM users WHERE email LIKE '%@gmail.com';
SELECT * FROM users WHERE email REGEXP '^[a-z]+@gmail\.com$';
SQL #2.33
Q33: What is the difference between IN and EXISTS?
Ans: IN compares a value against a fixed or subquery-derived list of values and works well for smaller sets, while EXISTS checks only whether a correlated subquery returns any rows at all (stopping at the first match) and often performs better for large or correlated subqueries.
Code Example
SELECT * FROM customers c
WHERE EXISTS (SELECT 1 FROM orders o WHERE o.customer_id = c.id);
SQL #2.34
Q34: What is the COALESCE function used for?
Ans: COALESCE returns the first non-NULL value from a list of expressions, commonly used to provide a fallback/default value when a column might contain NULL.
Code Example
SELECT COALESCE(phone, 'N/A') FROM users;
SQL #2.35
Q35: What is the difference between COALESCE and ISNULL?
Ans: COALESCE is standard SQL and can accept any number of arguments, returning the first non-NULL one, while ISNULL (SQL Server-specific, or IFNULL in MySQL) accepts exactly two arguments and is not portable across all database systems.
SQL #2.36
Q36: What is the CASE statement used for in SQL?
Ans: CASE provides conditional (if-else-like) logic within a SQL query, letting you compute different output values in a SELECT, ORDER BY, or WHERE clause based on evaluated conditions.
Code Example
SELECT name,
  CASE
    WHEN salary > 100000 THEN 'High'
    WHEN salary > 50000 THEN 'Medium'
    ELSE 'Low'
  END AS salary_band
FROM employees;
SQL #2.37
Q37: What is the difference between DISTINCT and GROUP BY?
Ans: DISTINCT simply removes duplicate rows from the result set, while GROUP BY groups rows by shared column values specifically to enable aggregate calculations per group; GROUP BY without aggregates behaves similarly to DISTINCT but is generally used with aggregate functions.
Code Example
SELECT DISTINCT city FROM customers;
SQL #2.38
Q38: What is a schema in SQL?
Ans: A schema is a logical namespace or container that organizes database objects like tables, views, and procedures, helping separate and manage related objects, control access permissions, and avoid naming collisions within a database.
SQL #2.39
Q39: What is the difference between a database and a schema?
Ans: A database is the overall container that holds data and its structures, while a schema is a logical grouping within a database (in systems like PostgreSQL and SQL Server); in MySQL, however, 'database' and 'schema' are often used interchangeably.
SQL #2.40
Q40: What is a many-to-many relationship and how is it implemented in a relational database?
Ans: A many-to-many relationship, where multiple rows in one table can relate to multiple rows in another, is implemented using a junction (or bridge/associative) table that holds foreign keys referencing both related tables.
Code Example
CREATE TABLE student_courses (
  student_id INT,
  course_id INT,
  PRIMARY KEY (student_id, course_id)
);
SQL #2.41
Q41: What is a full table scan and why is it usually undesirable?
Ans: A full table scan occurs when the database reads every row in a table to satisfy a query instead of using an index, which is slow and resource-intensive for large tables, typically indicating a missing or unused index for the query's filter conditions.
SQL #2.42
Q42: What is SQL injection and how can it be prevented?
Ans: SQL injection is a security vulnerability where untrusted user input is concatenated directly into a SQL query, allowing an attacker to alter the query's logic; it is prevented by using parameterized queries or prepared statements instead of string concatenation, and by validating/escaping user input.
Code Example
-- Vulnerable:
"SELECT * FROM users WHERE username = '" + input + "'"
-- Safe (parameterized):
"SELECT * FROM users WHERE username = ?"
SQL #2.43
Q43: What is the difference between a prepared statement and a regular query?
Ans: A prepared statement separates the SQL query structure from the data values, sending the query template to the database once and binding parameter values separately, which prevents SQL injection and can improve performance for repeated executions of the same query shape.
SQL #2.44
Q44: What is the difference between a temporary table and a regular table?
Ans: A temporary table exists only for the duration of a session or transaction (depending on the database and how it's declared) and is automatically dropped afterward, while a regular table persists permanently until explicitly dropped.
Code Example
CREATE TEMPORARY TABLE temp_results AS
SELECT * FROM orders WHERE status = 'pending';
SQL #2.45
Q45: What is the difference between a relational database and a NoSQL database?
Ans: A relational database stores structured data in tables with a fixed schema and enforces relationships via foreign keys, typically prioritizing strong consistency (ACID), while NoSQL databases (document, key-value, column-family, or graph stores) offer flexible or schema-less data models and often favor horizontal scalability and eventual consistency over strict relational integrity.
SQL #2.46
Q46: What is the difference between horizontal and vertical scaling for a database?
Ans: Vertical scaling increases the capacity of a single server (more CPU, RAM, or storage), while horizontal scaling adds more servers and distributes the data and load across them (as with sharding or read replicas), generally offering better long-term scalability for very large workloads.
SQL #2.47
Q47: What is a database replica and what is it used for?
Ans: A replica is a copy of a database (often read-only) kept synchronized with a primary database, used to distribute read traffic across multiple servers, provide failover in case the primary fails, or support geographically distributed access.
SQL #2.48
Q48: What is the difference between OLTP and OLAP systems?
Ans: OLTP (Online Transaction Processing) systems are optimized for many short, frequent read/write transactions typical of everyday application use, while OLAP (Online Analytical Processing) systems are optimized for complex, read-heavy analytical queries over large historical datasets, often using denormalized or star-schema designs.
SQL #2.49
Q49: What is a data warehouse?
Ans: A data warehouse is a centralized repository that consolidates data from multiple operational sources for reporting and analysis, typically organized using star or snowflake schemas optimized for complex analytical (OLAP) queries rather than transactional workloads.
SQL #2.50
Q50: What is the GROUP_CONCAT (or STRING_AGG) function used for?
Ans: GROUP_CONCAT (MySQL) or STRING_AGG (PostgreSQL/SQL Server) concatenates values from multiple rows within a group into a single delimited string, useful for producing comma-separated lists in a result set.
Code Example
SELECT dept, GROUP_CONCAT(name SEPARATOR ', ') FROM employees GROUP BY dept;
SQL #2.51
Q51: What are the different storage engines in MySQL?
Ans: MySQL supports multiple storage engines that determine how data is stored and accessed, including InnoDB (the default, supporting transactions and foreign keys), MyISAM (faster reads but no transaction support), MEMORY (stores data entirely in RAM for speed), and CSV (stores data in plain comma-separated files).
Code Example
CREATE TABLE logs (
  id INT,
  message VARCHAR(255)
) ENGINE=MyISAM;
SQL #2.52
Q52: What is the difference between the MEMORY and MyISAM storage engines?
Ans: The MEMORY engine stores all table data directly in RAM, making it extremely fast but volatile (data is lost on server restart), while MyISAM stores data persistently on disk, surviving restarts but with slower access than in-memory storage.
SQL #2.53
Q53: Why is InnoDB the default storage engine in MySQL?
Ans: InnoDB became the default engine because it supports ACID-compliant transactions, foreign key constraints, and row-level locking, making it far more suitable for reliable, concurrent, real-world applications than the older MyISAM engine.
SQL #2.54
Q54: What are the advantages of the InnoDB storage engine?
Ans: InnoDB offers ACID compliance for reliable transactions, automatic crash recovery, row-level locking for better write concurrency, and support for foreign key constraints to enforce referential integrity.
SQL #2.55
Q55: What are the disadvantages of the InnoDB storage engine?
Ans: InnoDB generally uses more disk space and memory than simpler engines like MyISAM, and can be somewhat slower for simple, read-only workloads where MyISAM's lighter-weight design and full-text indexing (in older MySQL versions) had an edge.
SQL #2.56
Q56: What is a super key?
Ans: A super key is any combination of one or more columns that can uniquely identify a row in a table; unlike a candidate key, a super key may include extra, redundant columns beyond what's strictly necessary for uniqueness.
SQL #2.57
Q57: How do you find the nth highest salary in SQL?
Ans: A common approach is to use LIMIT with OFFSET after sorting in descending order, or to use the DENSE_RANK() window function to properly handle ties, then filter for the desired rank.
Code Example
-- Using LIMIT/OFFSET (nth = 3rd highest)
SELECT DISTINCT salary FROM employees
ORDER BY salary DESC LIMIT 1 OFFSET 2;

-- Using DENSE_RANK
SELECT salary FROM (
  SELECT salary, DENSE_RANK() OVER (ORDER BY salary DESC) AS rnk
  FROM employees
) t WHERE rnk = 3;
SQL #2.58
Q58: What is row-level locking?
Ans: Row-level locking locks only the specific rows being read or modified by a transaction, rather than the entire table, allowing other transactions to concurrently access unrelated rows and improving overall concurrency; InnoDB supports row-level locking while MyISAM only supports table-level locking.
SQL #2.59
Q59: How do you provide security to a database?
Ans: Database security is achieved through a combination of measures: using prepared statements/parameterized queries to prevent SQL injection, enforcing strict access control and least-privilege user permissions, encrypting sensitive data at rest and in transit, using strong passwords and rotating credentials, and maintaining regular backups.
Hard 20 questions
SQL #3.1
Q1: What is the difference between a correlated and a non-correlated subquery?
Ans: A non-correlated subquery runs independently of the outer query and executes only once, while a correlated subquery references a column from the outer query and is re-evaluated once for every row processed by the outer query, which can be significantly slower.
Code Example
SELECT e.name FROM employees e
WHERE salary > (
  SELECT AVG(salary) FROM employees e2
  WHERE e2.dept_id = e.dept_id
);
SQL #3.2
Q2: What is a recursive CTE?
Ans: A recursive CTE references itself within its own definition, combining an anchor member (base case) with a recursive member (which joins back to the CTE) via UNION ALL, commonly used to traverse hierarchical data like org charts or category trees.
Code Example
WITH RECURSIVE org_chart AS (
  SELECT id, manager_id, name FROM employees WHERE manager_id IS NULL
  UNION ALL
  SELECT e.id, e.manager_id, e.name
  FROM employees e
  JOIN org_chart o ON e.manager_id = o.id
)
SELECT * FROM org_chart;
SQL #3.3
Q3: What are window functions in SQL?
Ans: Window functions perform calculations across a set of rows related to the current row (defined by an OVER clause with PARTITION BY and ORDER BY) without collapsing the result into a single row per group, unlike regular aggregate functions.
Code Example
SELECT name, salary,
  AVG(salary) OVER (PARTITION BY dept) AS dept_avg
FROM employees;
SQL #3.4
Q4: What is the difference between RANK(), DENSE_RANK(), and ROW_NUMBER()?
Ans: ROW_NUMBER() assigns a unique sequential number to each row regardless of ties, RANK() assigns the same rank to tied rows but skips subsequent rank numbers, and DENSE_RANK() assigns the same rank to tied rows without skipping any rank numbers.
Code Example
SELECT name, salary,
  RANK() OVER (ORDER BY salary DESC) AS rnk,
  DENSE_RANK() OVER (ORDER BY salary DESC) AS dense_rnk,
  ROW_NUMBER() OVER (ORDER BY salary DESC) AS row_num
FROM employees;
SQL #3.5
Q5: What is the PARTITION BY clause used for?
Ans: PARTITION BY, used within a window function's OVER clause, divides the result set into partitions (groups) to which the window function is applied separately, similar to GROUP BY but without collapsing rows.
Code Example
SELECT name, dept, salary,
  SUM(salary) OVER (PARTITION BY dept) AS dept_total
FROM employees;
SQL #3.6
Q6: What is the LAG() and LEAD() window function used for?
Ans: LAG() returns the value of a column from a previous row within the same result set/partition, and LEAD() returns the value from a following row, both commonly used for comparing a row to the row before or after it, like computing period-over-period differences.
Code Example
SELECT month, revenue,
  LAG(revenue) OVER (ORDER BY month) AS prev_month_revenue
FROM sales;
SQL #3.7
Q7: What is the difference between a clustered and a non-clustered index?
Ans: A clustered index determines the physical order in which table rows are stored on disk, so a table can have only one, while a non-clustered index is a separate structure that stores pointers back to the actual rows, and a table can have multiple non-clustered indexes.
SQL #3.8
Q8: What is a composite index?
Ans: A composite (or compound) index is built on two or more columns together, useful for queries that filter or sort on that same combination of columns, though the column order in the index definition matters for which query patterns it can efficiently serve.
Code Example
CREATE INDEX idx_orders_customer_date ON orders(customer_id, order_date);
SQL #3.9
Q9: What is a SAVEPOINT in SQL?
Ans: A SAVEPOINT marks an intermediate point within a transaction that you can later roll back to without undoing the entire transaction, useful for partially undoing work while keeping earlier changes intact.
Code Example
SAVEPOINT before_update;
UPDATE accounts SET balance = 0 WHERE id = 1;
ROLLBACK TO before_update;
SQL #3.10
Q10: What are the different transaction isolation levels?
Ans: The standard SQL isolation levels, from least to most strict, are READ UNCOMMITTED (allows dirty reads), READ COMMITTED (prevents dirty reads), REPEATABLE READ (prevents dirty and non-repeatable reads), and SERIALIZABLE (fully isolates transactions, preventing phantom reads too, at the cost of concurrency).
Code Example
SET TRANSACTION ISOLATION LEVEL READ COMMITTED;
SQL #3.11
Q11: What is a dirty read?
Ans: A dirty read occurs when a transaction reads data that has been modified by another transaction but not yet committed, meaning the read value might later be rolled back and never actually exist in the database's final state.
SQL #3.12
Q12: What is a deadlock in SQL and how can it be avoided?
Ans: A deadlock occurs when two or more transactions each hold a lock the other needs and wait indefinitely for each other to release it; it can be mitigated by always acquiring locks in a consistent order, keeping transactions short, and using appropriate isolation levels or timeout settings.
SQL #3.13
Q13: What is a materialized view?
Ans: A materialized view is a view whose result set is physically stored on disk and periodically refreshed, trading storage and staleness for much faster read performance compared to recomputing a complex query every time.
SQL #3.14
Q14: What is the difference between BEFORE and AFTER triggers?
Ans: A BEFORE trigger fires prior to the triggering event actually being applied to the table, allowing you to validate or modify the incoming data, while an AFTER trigger fires once the event has already been applied, useful for logging or cascading updates to other tables.
SQL #3.15
Q15: What is the difference between ON DELETE CASCADE, SET NULL, and RESTRICT?
Ans: CASCADE deletes child rows automatically when the referenced parent row is deleted, SET NULL sets the foreign key column in child rows to NULL instead of deleting them, and RESTRICT (or NO ACTION) prevents the parent row from being deleted at all while matching child rows still exist.
SQL #3.16
Q16: What is the difference between WHERE and ON in a JOIN?
Ans: The ON clause specifies the condition used to match rows between the joined tables, evaluated as the join is performed, while the WHERE clause filters the combined result set afterward; this distinction matters especially with OUTER JOINs, where conditions in ON versus WHERE can produce different results.
Code Example
SELECT * FROM a
LEFT JOIN b ON a.id = b.a_id AND b.active = 1
WHERE a.status = 'open';
SQL #3.17
Q17: What is query optimization and what is the EXPLAIN statement used for?
Ans: Query optimization involves rewriting queries or adjusting indexes/schema so the database engine can execute them more efficiently; the EXPLAIN (or EXPLAIN ANALYZE) statement shows the execution plan a database will use for a given query, revealing whether it uses indexes, full table scans, or particular join strategies.
Code Example
EXPLAIN SELECT * FROM orders WHERE customer_id = 5;
SQL #3.18
Q18: What is the difference between UPDATE and MERGE (UPSERT)?
Ans: UPDATE modifies existing rows that match a condition but does nothing if no matching row exists, while MERGE (or an UPSERT pattern like INSERT ... ON CONFLICT / ON DUPLICATE KEY UPDATE) inserts a new row if no match is found or updates the existing row if one is, combining both operations in a single statement.
Code Example
INSERT INTO inventory (product_id, quantity)
VALUES (1, 10)
ON DUPLICATE KEY UPDATE quantity = quantity + 10;
SQL #3.19
Q19: What is database sharding?
Ans: Sharding is a horizontal scaling technique that splits a large database into smaller, independent pieces (shards) distributed across multiple servers, typically partitioned by a key (like customer ID), so that each server handles only a subset of the total data.
SQL #3.20
Q20: What is the difference between a natural join and an equi join?
Ans: A natural join automatically joins tables based on all columns that share the same name, without needing an explicit ON clause, while an equi join requires you to explicitly specify the columns to compare using an equality condition, giving more control and clarity over which columns are used.