1. SQL Intro & RDBMS
Beginner
SQL (Structured Query Language) is the standard database language used to create, store, query, update, and manage relational databases. In this course, all 25 topics are standardized on two core relational tables: students and enrollments.
💡 IN SIMPLE WORDS / REAL-LIFE ANALOGY
Think of a Database like a massive electronic filing cabinet in a corporate headquarters, where every drawer is labeled and protected from fires and power outages!
📊 Course Standard Relational Datasets
All interactive code editors across all 25 topics query these two interconnected tables. Notice how enrollments.student_id references students.id:
📋 Table 1: students
Master Profile · 6 Rows
id INT · PK
name VARCHAR(50)
age INT
grade VARCHAR(5)
city VARCHAR(50)
email VARCHAR(100)
📋 Table 2: enrollments
Registrations · 5 Rows
enroll_id INT · PK
student_id INT · FK
course_name VARCHAR(50)
fee DECIMAL(10,2)
join_date DATE
📄 Table 1 Data: students (6 Records)
⇄ Swipe to view all columns
| id | name | age | grade | city | |
|---|---|---|---|---|---|
| 1 | Aarav Sharma | 20 | A | Hyderabad | aarav.sharma@example.com |
| 2 | Priya Patel | 22 | A | Bangalore | priya.patel@example.com |
| 3 | Rahul Varma | 21 | B | Mumbai | rahul.varma@example.com |
| 4 | Sneha Reddy | 23 | A | Hyderabad | sneha.reddy@example.com |
| 5 | Vikram Joshi | 20 | C | Delhi | vikram.joshi@example.com |
| 6 | Ananya Roy | 22 | B | Pune | ananya.roy@example.com |
📄 Table 2 Data: enrollments (5 Records)
⇄ Swipe to view all columns
| enroll_id | student_id | course_name | fee | join_date |
|---|---|---|---|---|
| 101 | 1 (Aarav) | Python AI | ₹3,500.00 | 2023-01-15 |
| 102 | 2 (Priya) | Cloud Architecture | ₹4,000.00 | 2023-02-20 |
| 103 | 3 (Rahul) | Full Stack Java | ₹3,000.00 | 2023-03-10 |
| 104 | 1 (Aarav) | Data Science | ₹4,500.00 | 2023-04-05 |
| 105 | 4 (Sneha) | Python AI | ₹3,500.00 | 2023-05-18 |
💡 Notice: Students 5 (Vikram) & 6 (Ananya) have no enrollment records yet, which is used across the course to practice LEFT JOIN and IS NULL queries.
📌 1. Table 1: Querying Students Dataset
studentstable stores primary learner records including ID, Name, Age, Grade, City, and Email.- Click Run to execute a real query against the in-memory database simulator.
📌 2. Table 2: Querying Course Enrollments Dataset
enrollmentstable tracks which courses students registered for, tuition fees, and joining dates.- Notice how
student_idmatches up withstudents.id.
🧠 Topic 1 Practice Quiz
Q1. What does SQL stand for?
✅ Correct Answer: Option C
Explanation: (SQL stands for Structured Query Language, the standard language for relational databases.)
Explanation: (SQL stands for Structured Query Language, the standard language for relational databases.)
Q2. What is the primary purpose of an RDBMS (Relational Database Management System)?
✅ Correct Answer: Option A
Explanation: (An RDBMS organizes and stores data in tables consisting of rows and columns with defined relationships.)
Explanation: (An RDBMS organizes and stores data in tables consisting of rows and columns with defined relationships.)
Q3. Which of the following is a widely used Relational Database Management System?
✅ Correct Answer: Option D
Explanation: (MySQL, PostgreSQL, and SQL Server are all popular industry-standard RDBMS systems.)
Explanation: (MySQL, PostgreSQL, and SQL Server are all popular industry-standard RDBMS systems.)
Q4. In an SQL relational table, what does each row represent?
✅ Correct Answer: Option B
Explanation: (Each row in an SQL table represents an individual record or entity (e.g. one specific student or employee).)
Explanation: (Each row in an SQL table represents an individual record or entity (e.g. one specific student or employee).)
Topic 1 Interview Questions & Answers
Q1: What is the difference between SQL and RDBMS?
Answer: SQL is the standard language used to write queries, while RDBMS (like MySQL or Oracle) is the database software that stores the data and runs those SQL queries.
Q2: What are tables, rows, and columns in a database?
Answer: A table is a structured collection of data. Columns represent attributes or fields (like Name, Age), and rows represent individual data records.
Q3: Why is SQL called a declarative language?
Answer: In SQL, you specify what data you want to retrieve or modify (e.g. SELECT * FROM users), without needing to program how the computer fetches it step-by-step.
2. Database Schemas & Data Models
Beginner
A Schema defines the logical structure of a database, including table names, field data types, relationships, views, indexes, and constraints.
💡 IN SIMPLE WORDS / REAL-LIFE ANALOGY
Think of a Data Model like an architectural blueprint of a bank's account ledgers, ensuring accounts, customers, and cards connect with mathematical precision!
📌 1. Inspecting Table Schema (DESCRIBE)
DESCRIBE table_name;outputs column definitions, data types, NULL allowance, and keys.- Notice
idis the Primary Key of the students table.
📌 2. Inspecting Enrollments Schema (DESCRIBE)
- Inspect column types and foreign key relationships for the enrollments table.
- Notice
enroll_idis the primary key andstudent_idis the relational key.
📌 3. Listing Database Tables (SHOW TABLES)
SHOW TABLES;reveals all active tables in the currently selected database.- Run the command below to see both standardized datasets.
🧠 Topic 2 Practice Quiz
Q1. What SQL statement displays the column details and data types of a table?
✅ Correct Answer: Option B
Explanation: (
Explanation: (
DESCRIBE table_name; (or DESC / EXPLAIN) displays column names, data types, nullability, and keys.)
Q2. What is a Database Schema?
✅ Correct Answer: Option D
Explanation: (A database schema is the structural design and blueprint defining how tables, columns, and constraints are organized.)
Explanation: (A database schema is the structural design and blueprint defining how tables, columns, and constraints are organized.)
Q3. Which SQL data type is best suited for storing variable-length text like an email address?
✅ Correct Answer: Option A
Explanation: (
Explanation: (
VARCHAR stores variable-length character strings, only consuming space for the actual characters entered.)
Q4. What does the NULL value represent in an SQL table?
✅ Correct Answer: Option C
Explanation: (
Explanation: (
NULL represents unknown, unassigned, or missing data. It is completely different from zero or an empty string.)
Topic 2 Interview Questions & Answers
Q1: What is the difference between a Database Schema and a Database Instance?
Answer: A Schema is the structural blueprint (tables and column definitions) created during design. An Instance is the actual collection of data present in the database at a specific moment.
Q2: What is the difference between CHAR and VARCHAR?
Answer: CHAR is fixed-length and pads unused space with spaces. VARCHAR is variable-length and only uses storage for the characters entered, saving disk space.
Q3: How does NULL differ from 0 or an empty string?
Answer:
NULL means the value is unknown or absent. 0 is an actual numeric value, and "" is an actual text string with zero characters.
3. SQL Comments & Documentation
Beginner
Master standard ANSI SQL comment syntax: single-line comments using double hyphens (--), multi-line comments (/* ... */), and optimizer hints. Clear documentation ensures complex database scripts, views, and migrations are readable and maintainable across enterprise teams.
💡 IN SIMPLE WORDS / REAL-LIFE ANALOGY
Think of SQL comments like the blueprint notes and surveyor markings on a construction site. The bulldozers and bricklayers (the database engine) only lay concrete where the actual foundation walls are specified, completely ignoring the chalk guidelines and pencil notes, but the architects and engineers cannot maintain or inspect the skyscraper without them!
📌 Core Concepts Breakdown
- Single-Line Comments (
--): Standard ANSI SQL token. Everything from--to the end of the line is ignored by the database parser. Always put a space after the hyphens. - Multi-Line Comments (
/* ... */): C-style block comments spanning multiple lines. Perfect for detailing script headers, author info, or disabling filters during debugging. - Inline Query Comments: Placed directly after column definitions or clauses (e.g.
SELECT age, grade /* verified */ FROM students;). - Optimizer Hints (
/*+ ... */): Special comments parsed by engines like Oracle and MySQL to suggest query plans (e.g. index usage) while remaining valid comments in other DBMSs.
🧠 Topic 3 Practice Quiz
Q1. Which character sequence is the standard ANSI SQL single-line comment token?
✅ Correct Answer: Option B
Explanation: In ANSI standard SQL, double hyphens (--) mark all text to the end of that line as a comment, which is ignored during query execution.
Explanation: In ANSI standard SQL, double hyphens (--) mark all text to the end of that line as a comment, which is ignored during query execution.
Q2. How are multi-line or block comments opened and closed in SQL?
✅ Correct Answer: Option A
Explanation: Multi-line comments in SQL use C-style /* and */ syntax, allowing documentation across multiple lines.
Explanation: Multi-line comments in SQL use C-style /* and */ syntax, allowing documentation across multiple lines.
Q3. Can SQL comments be embedded inline between column names in a SELECT clause?
✅ Correct Answer: Option C
Explanation: Inline comments using /* ... */ or -- at line ends can be freely placed between column names or filter expressions without causing syntax errors.
Explanation: Inline comments using /* ... */ or -- at line ends can be freely placed between column names or filter expressions without causing syntax errors.
Q4. What special comment delimiter is recognized by Oracle and MySQL for Optimizer Hints?
✅ Correct Answer: Option C
Explanation: Relational optimizers parse /*+ as execution hints (like forcing an index scan) while preserving backward compatibility as ordinary comments elsewhere.
Explanation: Relational optimizers parse /*+ as execution hints (like forcing an index scan) while preserving backward compatibility as ordinary comments elsewhere.
Topic 3 Interview Questions & Answers
Q1: Do comments affect SQL query execution performance in production?
Answer: No. The database lexical tokenizer completely removes all comments before compiling the query plan. Execution time, index lookups, and memory usage are completely unaffected.
Q2: What are SQL optimizer hints and why are they formatted as comments?
Answer: Optimizer hints (e.g.
/*+ INDEX(students idx_age) */) direct the query planner to use specific indexes or join algorithms. Using comment syntax prevents syntax crashes on databases that do not support those specific hints.
Q3: How do attackers use SQL comments in SQL Injection (SQLi) attacks?
Answer: Attackers inject double hyphens (
--) to comment out the remainder of a query, neutralizing password or security checks (e.g. ' OR 1=1 --). Parameterized PreparedStatements eliminate this threat entirely.
Q4: What is the recommended way to document database tables and columns in production schemas?
Answer: In addition to script comments, use DBMS metadata DDL statements like
COMMENT ON TABLE students IS 'Active enrolled students roster'; so documentation is queryable via information_schema.
4. Data Definition Language (DDL)
Core Concept
DDL commands (CREATE, ALTER, DROP, TRUNCATE) modify the structure of database objects such as tables and indexes.
💡 IN SIMPLE WORDS / REAL-LIFE ANALOGY
Think of DDL (
CREATE, DROP) like manufacturing empty filing cabinets and folders before any papers are placed inside!
📌 1. Creating Tables (CREATE TABLE)
CREATE TABLEdefines a new table schema with column constraints.- Below is how the
studentstable is created with PRIMARY KEY.
📌 2. Altering Tables (ALTER TABLE)
ALTER TABLE ... ADDadds new columns to an existing table schema without losing data.- Add a new phone contact column to the students table.
📌 3. Truncating Tables (TRUNCATE TABLE)
TRUNCATE TABLErapidly purges all data rows while keeping table structure intact.- Reset the enrollments table records.
📌 4. Dropping Tables (DROP TABLE)
DROP TABLEpermanently destroys a table and all its definitions.- Safely remove a temporary table using IF EXISTS.
🧠 Topic 4 Practice Quiz
Q1. Which DDL command completely deletes a table along with its schema and indexes?
✅ Correct Answer: Option D
Explanation: (
Explanation: (
DROP TABLE completely destroys both the table structure and all contained rows permanently.)
Q2. Which DDL statement is used to add, remove, or modify columns in an existing table?
✅ Correct Answer: Option B
Explanation: (
Explanation: (
ALTER TABLE modifies existing table definitions (adding, dropping, or renaming columns).)
Q3. What is the purpose of the TRUNCATE TABLE statement?
✅ Correct Answer: Option C
Explanation: (
Explanation: (
TRUNCATE TABLE rapidly empties all records from a table while preserving its schema for future inserts.)
Q4. Which of the following is NOT a DDL (Data Definition Language) command?
✅ Correct Answer: Option A
Explanation: (
Explanation: (
SELECT is a DQL (Data Query Language) command, not a DDL structural command.)
Topic 4 Interview Questions & Answers
Q1: What is the difference between DROP, TRUNCATE, and DELETE?
Answer: DROP deletes both data and the table structure. TRUNCATE removes all rows quickly while keeping the table structure (DDL). DELETE removes specific rows using a WHERE condition and can be rolled back (DML).
Q2: What are the core DDL commands in SQL?
Answer: The main DDL commands are
CREATE (creates database objects), ALTER (modifies structures), DROP (deletes objects), and TRUNCATE (empties tables).
Q3: Can a TRUNCATE command be rolled back in MySQL?
Answer: In MySQL and standard SQL, TRUNCATE is a DDL statement that causes an implicit commit, meaning it cannot be rolled back with ROLLBACK.
5. Data Manipulation Language (DML)
Core Concept
DML commands (INSERT, UPDATE, DELETE) insert new records, update values, or delete records from tables.
💡 IN SIMPLE WORDS / REAL-LIFE ANALOGY
Think of DML (
INSERT, UPDATE, DELETE) like filing new customer papers, correcting phone numbers, or shredding obsolete records!
📌 1. Inserting Data (INSERT INTO)
INSERT INTOinserts new record rows into a relational database table.- Add a new student profile for Rohan Verma.
📌 2. Updating Data (UPDATE ... SET ... WHERE)
UPDATEalters existing record values matching specified conditions.- Update student grade to A+ for ID 1.
📌 3. Deleting Data (DELETE FROM ... WHERE)
DELETE FROMremoves records matching a criteria safely.- Remove a canceled enrollment registration by its enroll_id.
🧠 Topic 5 Practice Quiz
Q1. Which SQL command is used to insert new rows into a table?
✅ Correct Answer: Option A
Explanation: (
Explanation: (
INSERT INTO table_name (columns) VALUES (values); adds new records into a table.)
Q2. What happens if an UPDATE statement is executed without a WHERE clause?
✅ Correct Answer: Option C
Explanation: (Without a
Explanation: (Without a
WHERE condition, UPDATE applies the changes to every single row in the table.)
Q3. Which command removes specific rows matching a condition from a table?
✅ Correct Answer: Option B
Explanation: (
Explanation: (
DELETE FROM table_name WHERE condition; safely deletes matching rows.)
Q4. Which of the following are the primary DML commands?
✅ Correct Answer: Option D
Explanation: (
Explanation: (
INSERT, UPDATE, and DELETE are the standard Data Manipulation Language (DML) commands.)
Topic 5 Interview Questions & Answers
Q1: Why is executing UPDATE or DELETE without a WHERE clause dangerous in production?
Answer: Because without a WHERE clause, the command applies to all rows in the table, potentially overwriting or deleting all company data.
Q2: What is the difference between DDL and DML?
Answer: DDL (CREATE, ALTER, DROP) defines the table structure/schema. DML (INSERT, UPDATE, DELETE) modifies the actual data records stored inside tables.
Q3: How can you insert multiple rows in a single SQL statement?
Answer: By providing multiple value tuples separated by commas:
INSERT INTO users (id, name) VALUES (1, 'Alice'), (2, 'Bob'), (3, 'Charlie');.
6. DQL & SELECT Queries
Core Concept
The SELECT statement retrieves data from one or more tables with optional column aliases.
💡 IN SIMPLE WORDS / REAL-LIFE ANALOGY
Think of
SELECT like asking a helpful librarian: "Please find all books in the fiction section written after 2020!"
📌 1. Basic Column Selection & Math Expressions
- Specify desired columns and compute dynamic calculations on the fly.
- Calculate student age next academic year.
📌 2. Column Aliases (AS)
- Assign clean, readable headers to output fields using the
ASkeyword. - Format student columns into friendly labels.
📌 3. Unique Distinct Rows (SELECT DISTINCT)
- Eliminate duplicate values from result sets using
SELECT DISTINCT. - Retrieve unique home cities where students reside.
🧠 Topic 6 Practice Quiz
Q1. Which clause in SQL is used to specify the columns you want to retrieve?
✅ Correct Answer: Option C
Explanation: (
Explanation: (
SELECT is the fundamental clause used to specify which columns to retrieve from a database.)
Q2. What keyword is used to assign a temporary alias name to a column or table in query results?
✅ Correct Answer: Option D
Explanation: (The
Explanation: (The
AS keyword creates column or table aliases, e.g. SELECT first_name AS Name.)
Q3. What wildcard character is used to select all columns from a table?
✅ Correct Answer: Option B
Explanation: (The asterisk
Explanation: (The asterisk
* represents all columns, e.g., SELECT * FROM employees;.)
Q4. Which keyword filters out duplicate rows from query results?
✅ Correct Answer: Option A
Explanation: (
Explanation: (
SELECT DISTINCT column_name FROM table; returns only unique, non-duplicate values.)
Topic 6 Interview Questions & Answers
Q1: What does SELECT DISTINCT do?
Answer: It eliminates duplicate rows from the query output so that only unique values are returned.
Q2: What is a column alias in SQL and why is it used?
Answer: An alias (using
AS) provides a temporary, readable name for a column or computed expression in the output (e.g. SELECT salary * 12 AS AnnualSalary).
Q3: Can you perform mathematical calculations directly inside a SELECT statement?
Answer: Yes! You can compute values directly, such as
SELECT name, price, price * 0.18 AS tax FROM products;.
7. WHERE & Filter Operators
Core Concept
Filter records using comparison operators, AND, OR, IN, BETWEEN, and LIKE clause matching.
💡 IN SIMPLE WORDS / REAL-LIFE ANALOGY
Think of
WHERE like a security guard checking attendee badges at an entrance gate: only visitors with age >= 18 are admitted!
📌 1. Comparison & Logical Operators (AND, OR, NOT)
- Combine conditions using boolean logic (AND, OR, NOT).
- Filter students who earned grade 'A' and live in Hyderabad.
📌 2. Range & List Matching (BETWEEN & IN)
- Use
BETWEENfor inclusive numeric ranges andINfor membership lists. - Filter students aged 20-22 living in Hyderabad or Mumbai.
📌 3. Pattern Matching (LIKE & IS NULL)
- Perform flexible wildcard search using
%(multiple chars) or_(single char). - Find students whose names begin with the letter 'A'.
🧠 Topic 7 Practice Quiz
Q1. Which operator checks if a column value matches any value in a list?
✅ Correct Answer: Option B
Explanation: (The
Explanation: (The
IN operator filters records matching any value in a provided list: WHERE city IN ('Delhi', 'Mumbai');.)
Q2. Which operator checks whether a value falls within an inclusive range?
✅ Correct Answer: Option A
Explanation: (
Explanation: (
BETWEEN value1 AND value2 selects values within an inclusive range.)
Q3. Which wildcard character in a LIKE clause represents zero or more characters?
✅ Correct Answer: Option C
Explanation: (
Explanation: (
% represents zero, one, or multiple characters, while _ represents exactly one single character.)
Q4. How do you test for missing/null values in a WHERE clause?
✅ Correct Answer: Option D
Explanation: (Always use
Explanation: (Always use
IS NULL (or IS NOT NULL). In SQL, = NULL evaluates to NULL/unknown, not TRUE.)
Topic 7 Interview Questions & Answers
Q1: What is the difference between the AND and OR operators?
Answer:
AND displays a record if all conditions are true. OR displays a record if at least one condition is true.
Q2: Why can't we use '= NULL' to check for null values?
Answer: Because in SQL, NULL represents an unknown value. Comparing anything to NULL using
= returns NULL (unknown), not true. Therefore, IS NULL must be used.
Q3: What is the difference between '%' and '_' wildcards in LIKE?
Answer:
% matches any sequence of zero or more characters (e.g. 'A%' matches 'A', 'Alex', 'Ananya'). _ matches exactly one single character (e.g. 'A_' matches 'An', 'Al').
8. ORDER BY & LIMIT Clause
Core Concept
Sort result sets in ascending or descending order and limit the total returned row count.
💡 IN SIMPLE WORDS / REAL-LIFE ANALOGY
Think of
ORDER BY ... LIMIT like announcing the Top 3 Olympic gold medal winners arranged from fastest to slowest race time!
📌 1. Ascending & Descending Sorting (ORDER BY)
- Sort query results using
ORDER BY column ASC/DESC. - Sort students alphabetically by grade and then oldest first.
📌 2. Restricting Top N Records (LIMIT)
- Restrict the number of returned rows using
LIMIT n. - Fetch the top 3 highest earning employees from the company database.
📌 3. Database Pagination (LIMIT & OFFSET)
- Build pagination for web and mobile apps using
LIMIT n OFFSET m. - Retrieve page 2 of student records (skip 2 rows, take 2).
🧠 Topic 8 Practice Quiz
Q1. Which clause sorts the result set in ascending or descending order?
✅ Correct Answer: Option D
Explanation: (
Explanation: (
ORDER BY sorts rows by one or more specified columns.)
Q2. What is the default sort order if neither ASC nor DESC is specified?
✅ Correct Answer: Option C
Explanation: (By default,
Explanation: (By default,
ORDER BY sorts in ascending (ASC) order (smallest to largest / A to Z).)
Q3. Which clause restricts the maximum number of rows returned by a query?
✅ Correct Answer: Option A
Explanation: (
Explanation: (
LIMIT (in MySQL/PostgreSQL) specifies the maximum number of rows to return.)
Q4. How do you skip the first 10 rows and fetch the next 5 rows?
✅ Correct Answer: Option B
Explanation: (Both
Explanation: (Both
LIMIT 5 OFFSET 10 and MySQL's shorthand LIMIT 10, 5 skip 10 rows and retrieve 5.)
Topic 8 Interview Questions & Answers
Q1: What is the difference between ASC and DESC in ORDER BY?
Answer:
ASC sorts values in ascending order (A to Z, 1 to 100). DESC sorts in descending order (Z to A, 100 to 1).
Q2: Can you sort by multiple columns in SQL?
Answer: Yes. For example,
ORDER BY department ASC, salary DESC; sorts by department first, and within each department, sorts by salary highest to lowest.
Q3: How are LIMIT and OFFSET used for database pagination?
Answer:
LIMIT controls the number of items per page, while OFFSET skips past previous pages' records (e.g. LIMIT 10 OFFSET 20 fetches page 3).
9. SQL Aggregate Functions
Intermediate
Functions like COUNT, SUM, AVG, MIN, and MAX perform math calculations across row sets.
💡 IN SIMPLE WORDS / REAL-LIFE ANALOGY
Think of Aggregates (
SUM, AVG, COUNT) like a cash register totaling the daily receipts and finding the average customer spend!
📌 1. Row Counting (COUNT(*) vs COUNT(col))
- Compute total row volume and unique field values.
- Calculate total registered students and distinct cities.
📌 2. Sum & Average (SUM, AVG)
- Calculate cumulative sums and mean averages across numeric columns.
- Compute total tuition collected and average course fee.
📌 3. Minimum & Maximum Extrema (MIN, MAX)
- Find lowest and highest boundary values with
MINandMAX. - Determine minimum and maximum tuition fee across all courses.
🧠 Topic 9 Practice Quiz
Q1. Which aggregate function counts the total number of rows matching a query?
✅ Correct Answer: Option A
Explanation: (
Explanation: (
COUNT() returns the number of rows that match the specified criteria.)
Q2. Which function calculates the average value of a numeric column?
✅ Correct Answer: Option B
Explanation: (
Explanation: (
AVG() computes the arithmetic mean of numeric column values.)
Q3. How does COUNT(column_name) handle NULL values in that column?
✅ Correct Answer: Option D
Explanation: (
Explanation: (
COUNT(column_name) ignores NULL values and only counts rows containing non-null data.)
Q4. Which functions find the smallest and largest values in a column?
✅ Correct Answer: Option C
Explanation: (
Explanation: (
MIN() finds the minimum value, and MAX() finds the maximum value in a column.)
Topic 9 Interview Questions & Answers
Q1: What is the difference between COUNT(*) and COUNT(column_name)?
Answer:
COUNT(*) counts all rows in the table including rows with NULLs. COUNT(col) counts only rows where that specific column is NOT NULL.
Q2: How do aggregate functions handle NULL values?
Answer: All aggregate functions (SUM, AVG, MIN, MAX, and COUNT(col)) automatically ignore NULL values during calculation.
Q3: Can you use aggregate functions in a WHERE clause?
Answer: No!
WHERE filters rows before aggregation occurs. To filter based on aggregate results, you must use the HAVING clause.
10. GROUP BY & HAVING Clause
Intermediate
GROUP BY aggregates identical records; HAVING filters aggregated groups.
💡 IN SIMPLE WORDS / REAL-LIFE ANALOGY
Think of
GROUP BY like sorting a bucket of assorted LEGO bricks into piles by color, and counting how many red, blue, and yellow bricks you have!
📌 1. Grouping Datasets (GROUP BY)
- Aggregate dataset rows into summary buckets using
GROUP BY. - Group students by city to see headcount and average age.
📌 2. Filtering Grouped Data (HAVING)
- Filter aggregated group results using the
HAVINGclause. - Filter courses having 1 or more student registrations.
🧠 Topic 10 Practice Quiz
Q1. Which clause groups rows with the same values into summary rows?
✅ Correct Answer: Option C
Explanation: (
Explanation: (
GROUP BY groups rows sharing identical column values, often used with aggregate functions.)
Q2. Which clause is specifically used to filter groups based on aggregate conditions?
✅ Correct Answer: Option B
Explanation: (
Explanation: (
HAVING filters grouped rows after aggregation, e.g. HAVING COUNT(*) > 5.)
Q3. In SQL execution order, which clause runs first: WHERE or HAVING?
✅ Correct Answer: Option A
Explanation: (
Explanation: (
WHERE filters rows first before grouping, and HAVING filters the resulting groups.)
Q4. Can a query have both a WHERE clause and a HAVING clause?
✅ Correct Answer: Option D
Explanation: (Yes! A query can filter rows using
Explanation: (Yes! A query can filter rows using
WHERE, group them with GROUP BY, and filter groups with HAVING.)
Topic 10 Interview Questions & Answers
Q1: What is the difference between WHERE and HAVING in SQL?
Answer:
WHERE filters individual records before any grouping happens. HAVING filters grouped records after the GROUP BY aggregation.
Q2: Can you use aggregate functions in the HAVING clause?
Answer: Yes!
HAVING is designed specifically to test conditions against aggregate functions (e.g. HAVING AVG(salary) > 50000).
Q3: What is the logical execution order of WHERE, GROUP BY, and HAVING?
Answer: First
WHERE filters rows, then GROUP BY clusters rows into groups, and finally HAVING eliminates groups that don't meet criteria.
11. JOINs Overview & INNER JOIN
Intermediate
INNER JOIN retrieves records that have matching foreign key values in both tables.
💡 IN SIMPLE WORDS / REAL-LIFE ANALOGY
Think of an
INNER JOIN like matching student ID cards to library loan cards: showing only students who actually borrowed a book!
📌 1. Two-Table Relational INNER JOIN
- Combine rows from two tables where foreign key matches primary key.
- Connect student names with their registered courses.
📌 2. INNER JOIN with Filtering & Ordering
- Filter joined records with WHERE and sort with ORDER BY.
- Retrieve premium enrollments (fee >= 3500) sorted by highest tuition.
🧠 Topic 11 Practice Quiz
Q1. What does an INNER JOIN return?
✅ Correct Answer: Option B
Explanation: (
Explanation: (
INNER JOIN returns records that have matching values in both tables based on the join predicate.)
Q2. Which keyword defines the matching condition between two joined tables?
✅ Correct Answer: Option C
Explanation: (The
Explanation: (The
ON keyword defines the join condition, e.g. ON orders.customer_id = customers.id.)
Q3. If Table A has 5 rows and Table B has 0 matching rows, how many rows will INNER JOIN return?
✅ Correct Answer: Option D
Explanation: (Because there are no matching rows in Table B, an
Explanation: (Because there are no matching rows in Table B, an
INNER JOIN returns 0 rows.)
Q4. Why are table aliases used in JOIN queries (e.g. FROM orders o JOIN users u)?
✅ Correct Answer: Option A
Explanation: (Table aliases keep queries clean, readable, and prevent ambiguous column reference errors.)
Explanation: (Table aliases keep queries clean, readable, and prevent ambiguous column reference errors.)
Topic 11 Interview Questions & Answers
Q1: What is an INNER JOIN in SQL?
Answer: An INNER JOIN selects records that have matching values in both tables based on an ON condition.
Q2: What happens if you join two tables without specifying an ON condition?
Answer: It produces a Cartesian Product (Cross Join), combining every row from the first table with every row of the second table.
Q3: Can you join more than two tables in a single SQL query?
Answer: Yes! You can chain multiple JOIN clauses:
SELECT * FROM Orders o JOIN Customers c ON o.CustID = c.CustID JOIN Products p ON o.ProdID = p.ProdID;.
12. LEFT, RIGHT & FULL JOIN
IntermediateOuter JOINs return matching and non-matching records from connected tables.
💡 IN SIMPLE WORDS / REAL-LIFE ANALOGY
Think of a
LEFT JOIN like a school roll call: calling every student on the master attendance sheet, even if some have not paid their exam fees yet!
📌 1. Preserving Primary Records (LEFT JOIN)
- Preserve all primary table records even when no match exists in the secondary table.
- Display all students whether enrolled in a course or not.
📌 2. Finding Non-Matching Records (LEFT JOIN WHERE NULL)
- Identify orphaned or unenrolled primary records where the joined foreign key is NULL.
- Find students who have not enrolled in any courses yet.
📌 3. Simulating FULL OUTER JOIN (UNION)
- Combine LEFT JOIN and RIGHT JOIN using UNION to retain all rows from both datasets.
- Generate a complete bidirectional outer join matrix.
🧠 Topic 12 Practice Quiz
Q1. What does a LEFT JOIN return?
✅ Correct Answer: Option D
Explanation: (
Explanation: (
LEFT JOIN returns all records from the left table, and matched records from the right table (with NULL for non-matches).)
Q2. If a row in the left table has no match in the right table, what values appear for right table columns?
✅ Correct Answer: Option A
Explanation: (When there is no match on the right side, the result set fills those columns with
Explanation: (When there is no match on the right side, the result set fills those columns with
NULL.)
Q3. What is the functional difference between LEFT JOIN and RIGHT JOIN?
✅ Correct Answer: Option B
Explanation: (LEFT JOIN preserves all rows from the left table; RIGHT JOIN preserves all rows from the right table.)
Explanation: (LEFT JOIN preserves all rows from the left table; RIGHT JOIN preserves all rows from the right table.)
Q4. How can you find records in the left table that have NO corresponding record in the right table?
✅ Correct Answer: Option C
Explanation: (Using
Explanation: (Using
LEFT JOIN ... WHERE right_table.id IS NULL filters for records with no matching foreign key.)
Topic 12 Interview Questions & Answers
Q1: When would you choose a LEFT JOIN over an INNER JOIN?
Answer: Use a LEFT JOIN when you need to retain all records from the primary (left) table even if they don't have matching entries in the secondary table (e.g. listing all customers even if they haven't placed an order yet).
Q2: Why do most database developers use LEFT JOIN instead of RIGHT JOIN?
Answer: Because reading queries from left-to-right is more natural and consistent. Any RIGHT JOIN can be rewritten as a LEFT JOIN simply by swapping table order.
Q3: What is a FULL OUTER JOIN?
Answer: A FULL OUTER JOIN returns all rows from both tables, filling in NULLs on whichever side lacks a matching row.
13. CROSS JOIN & SELF JOIN
IntermediateSELF JOIN links a table to itself to query parent-child or manager-employee data.
💡 IN SIMPLE WORDS / REAL-LIFE ANALOGY
Think of a
SELF JOIN like an employee org chart where employees report to managers who are also listed in the exact same employee table!
📌 1. Cartesian Product (CROSS JOIN)
- Pair every row of the first table with every row of the second table (M × N matrix).
- Generate combinations of all students across all courses.
📌 2. Hierarchical & Peer Relationships (SELF JOIN)
- Join a table to itself to find internal relational connections.
- Find pairs of students who live in the same hometown.
🧠 Topic 13 Practice Quiz
Q1. What type of result does a CROSS JOIN produce?
✅ Correct Answer: Option A
Explanation: (
Explanation: (
CROSS JOIN produces every possible combination of rows between two tables (Cartesian Product).)
Q2. If Table A contains 4 rows and Table B contains 6 rows, how many rows will CROSS JOIN return?
✅ Correct Answer: Option D
Explanation: (A Cartesian Product multiplies row counts: 4 * 6 = 24 rows.)
Explanation: (A Cartesian Product multiplies row counts: 4 * 6 = 24 rows.)
Q3. What is a SELF JOIN in SQL?
✅ Correct Answer: Option C
Explanation: (A
Explanation: (A
SELF JOIN is a regular join where a table is joined with itself using distinct aliases.)
Q4. What is the most common use case for a SELF JOIN?
✅ Correct Answer: Option B
Explanation: (Hierarchical data (where an employee's ManagerID refers to another employee's EmpID in the same table) is the classic use case.)
Explanation: (Hierarchical data (where an employee's ManagerID refers to another employee's EmpID in the same table) is the classic use case.)
Topic 13 Interview Questions & Answers
Q1: What is a SELF JOIN and when is it used?
Answer: A SELF JOIN joins a table to itself. It is commonly used to query hierarchical data in a single table, such as finding which employee reports to which manager.
Q2: What is a CROSS JOIN?
Answer: A CROSS JOIN returns the Cartesian product of two tables, matching every row of the first table with every row of the second table.
Q3: Does a CROSS JOIN require an ON condition?
Answer: No, a CROSS JOIN does not require an ON condition because it combines every row unconditionally.
14. Subqueries & Nested Queries
AdvancedSubqueries embed inner SELECT statements within outer main queries.
💡 IN SIMPLE WORDS / REAL-LIFE ANALOGY
Think of a Subquery like a math question inside parentheses:
(5 + 3) * 2: SQL calculates the inner question first before answering the main query!
📌 1. Subquery in WHERE Clause
- Nest a subquery inside an outer query WHERE condition.
- Find students whose age is strictly above the classroom average age.
📌 2. Subquery with IN Operator
- Filter outer records against a dynamic list returned by a child subquery.
- Find students enrolled in premium courses with fees >= 3500.
🧠 Topic 14 Practice Quiz
Q1. What is a Subquery in SQL?
✅ Correct Answer: Option C
Explanation: (A subquery (or inner query) is a SELECT query enclosed in parentheses inside an outer query.)
Explanation: (A subquery (or inner query) is a SELECT query enclosed in parentheses inside an outer query.)
Q2. Where can a subquery be placed within an SQL statement?
✅ Correct Answer: Option A
Explanation: (Subqueries can be placed in WHERE, FROM, HAVING, and SELECT clauses.)
Explanation: (Subqueries can be placed in WHERE, FROM, HAVING, and SELECT clauses.)
Q3. What is a Correlated Subquery?
✅ Correct Answer: Option D
Explanation: (A correlated subquery depends on values from the outer query and re-evaluates for each outer row.)
Explanation: (A correlated subquery depends on values from the outer query and re-evaluates for each outer row.)
Q4. Which operator checks whether a subquery returns at least one record?
✅ Correct Answer: Option B
Explanation: (
Explanation: (
EXISTS returns TRUE if the subquery returns one or more rows.)
Topic 14 Interview Questions & Answers
Q1: What is the difference between a Subquery and a Correlated Subquery?
Answer: A standard subquery executes once independently. A correlated subquery references values from the outer query and executes repeatedly for each row of the outer query.
Q2: What is the difference between IN and EXISTS with subqueries?
Answer:
IN fetches all values into memory and checks for matches. EXISTS stops scanning as soon as it finds the first match, making it much faster for large datasets.
Q3: Can a subquery be used in the FROM clause?
Answer: Yes! A subquery in the FROM clause acts as a temporary virtual table (called a derived table) and must be given an alias.
15. Set Operators (UNION)
AdvancedUNION combines distinct rows from multiple SELECT statements.
💡 IN SIMPLE WORDS / REAL-LIFE ANALOGY
Think of
UNION like merging two customer email contact lists together while automatically throwing duplicate emails in the recycling bin!
📌 1. Combining Unique Records (UNION)
- Combine results from multiple SELECT queries into a single distinct list.
- Merge student cities with online campus location.
📌 2. Preserving All Records (UNION ALL)
- Combine query outputs preserving duplicates without deduplication overhead.
- List all student names and enrolled course titles in a single stream.
🧠 Topic 15 Practice Quiz
Q1. What does the UNION operator do in SQL?
✅ Correct Answer: Option B
Explanation: (
Explanation: (
UNION combines rows from two or more queries into a single combined result set.)
Q2. What is the key difference between UNION and UNION ALL?
✅ Correct Answer: Option D
Explanation: (
Explanation: (
UNION removes duplicates, while UNION ALL keeps all rows including duplicates and is faster.)
Q3. Why is UNION ALL faster than UNION?
✅ Correct Answer: Option A
Explanation: (
Explanation: (
UNION ALL simply concatenates the results without running an expensive distinct/sort operation.)
Q4. What rule must queries satisfy to be combined with UNION?
✅ Correct Answer: Option C
Explanation: (Each SELECT statement in a UNION must have the same number of columns in the same order with compatible types.)
Explanation: (Each SELECT statement in a UNION must have the same number of columns in the same order with compatible types.)
Topic 15 Interview Questions & Answers
Q1: What is the difference between UNION and UNION ALL?
Answer:
UNION combines query results and filters out duplicates. UNION ALL combines results and keeps all duplicates, making it significantly faster.
Q2: What is the difference between JOIN and UNION?
Answer: A JOIN combines columns horizontally from two tables based on a matching key. A UNION combines rows vertically from two queries into a single list.
Q3: What conditions must be met to combine two queries using UNION?
Answer: Both SELECT queries must have the same number of columns in the same order, and corresponding columns must have compatible data types.
16. String Functions
IntermediateCONCAT, SUBSTRING, and UPPER manipulate string data values.
💡 IN SIMPLE WORDS / REAL-LIFE ANALOGY
Think of String Functions like an editor with white-out and a red pen: trimming whitespace, converting names to UPPERCASE, and replacing nicknames!
📌 1. String Concatenation (CONCAT)
- Merge multiple string expressions together using
CONCAT(). - Generate clean display handles combining name and city.
📌 2. Case Conversion (UPPER & LOWER)
- Standardize string casing using
UPPER()andLOWER(). - Convert student names to capital letters and cities to lowercase.
📌 3. String Length & Substring (LENGTH & SUBSTRING)
- Measure text character length and extract prefixes or substrings.
- Extract 3-letter city airport codes and character lengths.
🧠 Topic 16 Practice Quiz
Q1. Which SQL function concatenates two or more strings into one?
✅ Correct Answer: Option D
Explanation: (
Explanation: (
CONCAT(str1, str2, ...) joins multiple strings together into a single text output.)
Q2. Which function converts all characters in a string to uppercase?
✅ Correct Answer: Option B
Explanation: (
Explanation: (
UPPER() (or UCASE() in MySQL) converts text to uppercase.)
Q3. What does LENGTH('Database') return?
✅ Correct Answer: Option C
Explanation: (The word 'Database' has 8 characters, so
Explanation: (The word 'Database' has 8 characters, so
LENGTH() returns 8.)
Q4. Which function removes leading and trailing whitespace from a text string?
✅ Correct Answer: Option A
Explanation: (
Explanation: (
TRIM() strips leading and trailing spaces from a text string.)
Topic 16 Interview Questions & Answers
Q1: What does the CONCAT() function do in SQL?
Answer:
CONCAT() merges two or more strings into a single string (e.g. CONCAT(first_name, ' ', last_name) to create a full name).
Q2: What does SUBSTRING() do?
Answer:
SUBSTRING(str, start, length) extracts a smaller portion of text from a string starting at a given position for a specified length.
Q3: How do UPPER() and LOWER() help with case-insensitive queries?
Answer: By converting both the table column and user input to the same case (e.g.
WHERE LOWER(email) = LOWER('User@Email.com')), ensuring accurate matching.
17. Math & Numeric Functions
IntermediateROUND, CEIL, and ABS perform numeric calculations on output values.
💡 IN SIMPLE WORDS / REAL-LIFE ANALOGY
Think of Math Functions like a financial banking calculator computing loan interest, rounding cents, and calculating currency exchanges!
📌 1. Number Rounding (ROUND)
- Round numbers to specified decimal precision using
ROUND(). - Calculate 3-month course tuition installment rounded to 2 decimals.
📌 2. Boundary Rounding (CEIL & FLOOR)
- Round up with
CEIL()or down withFLOOR(). - Compare fee division under integer boundary functions.
📌 3. Modulus & Absolute Values (MOD & ABS)
- Calculate remainder division with
MODand distances withABS. - Check enrollment ID parity and tuition deviation from base fee.
🧠 Topic 17 Practice Quiz
Q1. Which SQL function rounds a number to a specified number of decimal places?
✅ Correct Answer: Option A
Explanation: (
Explanation: (
ROUND(number, decimals) rounds a number to the specified number of decimal digits.)
Q2. What does CEIL(4.2) return in SQL?
✅ Correct Answer: Option C
Explanation: (
Explanation: (
CEIL() (or CEILING()) rounds upwards to the nearest integer, returning 5.)
Q3. What does FLOOR(7.9) return in SQL?
✅ Correct Answer: Option B
Explanation: (
Explanation: (
FLOOR() rounds downwards to the nearest integer, returning 7.)
Q4. Which function returns the absolute (positive) value of a number?
✅ Correct Answer: Option D
Explanation: (
Explanation: (
ABS(-25) returns 25 (the non-negative absolute value).)
Topic 17 Interview Questions & Answers
Q1: What is the difference between ROUND() and FLOOR()?
Answer:
ROUND() rounds to the nearest number based on whether decimals are >= 0.5. FLOOR() always rounds down to the next lowest integer.
Q2: What does the MOD() function do in SQL?
Answer:
MOD(a, b) returns the remainder of dividing a by b (e.g. MOD(10, 3) returns 1).
Q3: Can numeric functions be used directly inside WHERE clauses?
Answer: Yes! For example,
WHERE ABS(balance) > 1000 or WHERE MOD(id, 2) = 0 to find even IDs.
18. Date & Time Functions
IntermediateNOW and EXTRACT process dates and timestamps in SQL queries.
💡 IN SIMPLE WORDS / REAL-LIFE ANALOGY
Think of Date Functions like an automated calendar alert: finding all subscription renewals that expire in the next 7 days!
📌 1. Current Date & Time (NOW & CURDATE)
- Retrieve server timestamps and current execution dates.
- Query system clock with
NOW().
📌 2. Extracting Date Components (YEAR & EXTRACT)
- Isolate calendar year, month, or day from stored date fields.
- Extract year from student course enrollment join dates.
📌 3. Calculating Date Differences (DATEDIFF)
- Calculate elapsed days between two calendar timestamps.
- Determine days elapsed since course enrollment join date.
🧠 Topic 18 Practice Quiz
Q1. Which function returns the current date and time in SQL?
✅ Correct Answer: Option C
Explanation: (
Explanation: (
NOW() (or CURRENT_TIMESTAMP) returns the current system date and time.)
Q2. Which function calculates the difference in days between two date values?
✅ Correct Answer: Option D
Explanation: (
Explanation: (
DATEDIFF(date1, date2) returns the number of days between two dates.)
Q3. What is the standard ISO date format in SQL databases?
✅ Correct Answer: Option B
Explanation: (The standard SQL format for dates is
Explanation: (The standard SQL format for dates is
YYYY-MM-DD (e.g. 2026-10-21).)
Q4. Which function extracts a specific date part such as YEAR or MONTH from a date?
✅ Correct Answer: Option A
Explanation: (
Explanation: (
YEAR(date) or EXTRACT(YEAR FROM date) extracts specific date components.)
Topic 18 Interview Questions & Answers
Q1: What is the difference between CURDATE() and NOW()?
Answer:
CURDATE() returns only the current date (YYYY-MM-DD), while NOW() returns both the date and the current time (YYYY-MM-DD HH:MM:SS).
Q2: How does the DATEDIFF() function work in SQL?
Answer:
DATEDIFF(end_date, start_date) calculates the number of days between two dates.
Q3: Why is storing dates in standard DATE format better than using VARCHAR?
Answer: DATE formats validate genuine calendar dates, allow chronological sorting, enable date calculations (adding days/months), and can be indexed efficiently.
19. CASE WHEN Expressions
IntermediateCASE WHEN expressions apply conditional logic inside SQL queries.
💡 IN SIMPLE WORDS / REAL-LIFE ANALOGY
Think of
CASE WHEN like a traffic cop directing cars into lanes: if score >= 90 assign 'Grade A', else if score >= 75 'Grade B', else 'Grade C'!
📌 1. Categorizing Data with CASE WHEN
- Implement conditional IF-THEN-ELSE business logic in SQL queries.
- Categorize students into Senior and Junior tiers based on age.
📌 2. Conditional Aggregation
- Perform conditional counts inside aggregate groupings.
- Count top grade 'A' achievers for each home city.
🧠 Topic 19 Practice Quiz
Q1. What SQL expression allows you to write conditional if-else logic in queries?
✅ Correct Answer: Option B
Explanation: (
Explanation: (
CASE WHEN condition THEN result ELSE default END is SQL's if-else expression.)
Q2. Which keyword provides a fallback value if none of the WHEN conditions are met?
✅ Correct Answer: Option A
Explanation: (The
Explanation: (The
ELSE clause provides the fallback value when no WHEN conditions evaluate to true.)
Q3. Every CASE statement in SQL must terminate with which keyword?
✅ Correct Answer: Option C
Explanation: (A CASE expression must always conclude with the
Explanation: (A CASE expression must always conclude with the
END keyword.)
Q4. Can a CASE WHEN expression be nested inside aggregate functions like SUM()?
✅ Correct Answer: Option D
Explanation: (Yes!
Explanation: (Yes!
SUM(CASE WHEN status = 'Active' THEN 1 ELSE 0 END) is a common technique to count conditional records.)
Topic 19 Interview Questions & Answers
Q1: What is the purpose of CASE WHEN in SQL?
Answer: CASE WHEN provides if-then-else conditional logic directly inside SQL queries to dynamically compute or categorize values.
Q2: What happens if no WHEN condition matches and there is no ELSE clause?
Answer: If no conditions match and there is no ELSE clause, the CASE expression evaluates to
NULL.
Q3: Can you use CASE WHEN inside an ORDER BY clause?
Answer: Yes! You can use CASE WHEN in ORDER BY to apply custom sorting priorities (e.g. sorting 'High' priority tickets before 'Medium' and 'Low').
20. Constraints & Keys
IntermediatePRIMARY KEY, FOREIGN KEY, UNIQUE, and CHECK enforce integrity.
💡 IN SIMPLE WORDS / REAL-LIFE ANALOGY
Think of Primary Keys like government National ID numbers: guaranteed unique for every human, while Foreign Keys link family relatives together!
📌 1. Primary Key & Check Constraints
- Enforce data integrity rules: PRIMARY KEY, NOT NULL, and CHECK.
- Create enrollments table schema with non-negative fee check.
📌 2. Foreign Key Structure
- Verify relational foreign key links connecting child tables to master tables.
- Inspect enrollments key structure referencing students.
🧠 Topic 20 Practice Quiz
Q1. Which constraint uniquely identifies every record in a table and cannot contain NULL values?
✅ Correct Answer: Option D
Explanation: (A
Explanation: (A
PRIMARY KEY uniquely identifies each row and never allows NULL values.)
Q2. Which constraint links two tables by referencing the primary key of another table?
✅ Correct Answer: Option C
Explanation: (A
Explanation: (A
FOREIGN KEY enforces referential integrity by pointing to a primary key in another table.)
Q3. How does a UNIQUE constraint differ from a PRIMARY KEY?
✅ Correct Answer: Option A
Explanation: (A table can have multiple UNIQUE columns (which can accept NULL), whereas a table has only one PRIMARY KEY (which never allows NULL).)
Explanation: (A table can have multiple UNIQUE columns (which can accept NULL), whereas a table has only one PRIMARY KEY (which never allows NULL).)
Q4. Which constraint ensures that a column cannot store empty or blank values?
✅ Correct Answer: Option B
Explanation: (The
Explanation: (The
NOT NULL constraint ensures a column must always be provided a valid value.)
Topic 20 Interview Questions & Answers
Q1: What is the difference between a Primary Key and a Unique Key?
Answer: A table can have only one Primary Key and it never allows NULL values. A table can have multiple Unique keys, and Unique columns can allow NULL values.
Q2: What is a Foreign Key and why is it important?
Answer: A Foreign Key is a field in one table that references the Primary Key of another table, ensuring referential integrity and preventing orphan records.
Q3: What is the CHECK constraint in SQL?
Answer: The CHECK constraint limits the range of values that can be inserted into a column (e.g.
CHECK (age >= 18)).
21. Indexes & Optimization
AdvancedIndexes speed up data searching on frequently queried columns.
💡 IN SIMPLE WORDS / REAL-LIFE ANALOGY
Think of an Index like the alphabetical index at the back of a 1,000-page encyclopedia: flipping straight to page 842 instead of reading every page from page 1!
📌 1. Single Column Index (CREATE INDEX)
- Accelerate lookup operations on frequently filtered columns with B-Tree indexes.
- Index student email addresses for instant point searches.
📌 2. Composite Multi-Column Index
- Optimize compound queries filtering on multiple columns simultaneously.
- Create a composite index on city and grade.
🧠 Topic 21 Practice Quiz
Q1. What is the main purpose of creating an index on a database table?
✅ Correct Answer: Option A
Explanation: (Indexes allow the database engine to find specific rows much faster without scanning the entire table.)
Explanation: (Indexes allow the database engine to find specific rows much faster without scanning the entire table.)
Q2. Which SQL command creates an index on a table column?
✅ Correct Answer: Option B
Explanation: (
Explanation: (
CREATE INDEX index_name ON table_name (column_name); is the standard syntax.)
Q3. What is a major trade-off of having too many indexes on a table?
✅ Correct Answer: Option D
Explanation: (Every index requires disk space and slows down write operations (INSERT/UPDATE/DELETE) because the index must be updated on every change.)
Explanation: (Every index requires disk space and slows down write operations (INSERT/UPDATE/DELETE) because the index must be updated on every change.)
Q4. Is an index automatically created on PRIMARY KEY columns?
✅ Correct Answer: Option C
Explanation: (RDBMS engines automatically create a unique index for primary key columns to enforce uniqueness.)
Explanation: (RDBMS engines automatically create a unique index for primary key columns to enforce uniqueness.)
Topic 21 Interview Questions & Answers
Q1: What is a Database Index and how does it work?
Answer: An index is a specialized data structure (typically a B-Tree) that allows the database engine to find specific rows rapidly without scanning every record in the table.
Q2: What are the disadvantages of having too many indexes?
Answer: Indexes consume additional disk storage and slow down write operations (INSERT, UPDATE, DELETE) because every index must be refreshed on write.
Q3: On which columns should you typically create an index?
Answer: On columns that are frequently used in WHERE conditions, JOIN ON clauses, and ORDER BY sorting.
22. Database Views
AdvancedViews provide virtual customized table perspectives.
💡 IN SIMPLE WORDS / REAL-LIFE ANALOGY
Think of a View like a custom telescope looking into a locked vault: letting accountants see sales numbers without showing them private employee salaries!
📌 1. Creating a Virtual View (CREATE VIEW)
- Store a virtual named query table with
CREATE VIEW. - Save a view filtering top grade 'A' students.
📌 2. Querying Virtual Views
- Query views just like real physical tables.
- Fetch all rows from the virtual TopStudents view.
🧠 Topic 22 Practice Quiz
Q1. What is a Database View in SQL?
✅ Correct Answer: Option C
Explanation: (A View is a virtual table defined by a saved SELECT query. It contains no physical data rows of its own.)
Explanation: (A View is a virtual table defined by a saved SELECT query. It contains no physical data rows of its own.)
Q2. Does a standard SQL view physically store data on disk?
✅ Correct Answer: Option B
Explanation: (Standard views do not duplicate data; they query the underlying base tables dynamically whenever called.)
Explanation: (Standard views do not duplicate data; they query the underlying base tables dynamically whenever called.)
Q3. Which SQL command creates a new view?
✅ Correct Answer: Option A
Explanation: (
Explanation: (
CREATE VIEW view_name AS SELECT ...; creates a new virtual view.)
Q4. What is an important security benefit of using database views?
✅ Correct Answer: Option D
Explanation: (Views allow security administrators to expose only necessary fields (e.g. employee name and department) while hiding sensitive data like salaries.)
Explanation: (Views allow security administrators to expose only necessary fields (e.g. employee name and department) while hiding sensitive data like salaries.)
Topic 22 Interview Questions & Answers
Q1: What is a View in SQL and why is it used?
Answer: A View is a saved virtual table generated by an SQL query. It simplifies complex queries, promotes code reusability, and enhances security by hiding sensitive columns from end users.
Q2: Does a standard View store data physically on disk?
Answer: No. A standard View only stores the query definition in the database metadata. When you query the view, it fetches fresh data dynamically from the base tables.
Q3: What is the difference between a View and a Table?
Answer: A Table physically stores data rows on disk. A View is a virtual table that presents data fetched on-the-fly from one or more base tables.
23. SQL Transactions & ACID
AdvancedCOMMIT and ROLLBACK manage transaction integrity.
💡 IN SIMPLE WORDS / REAL-LIFE ANALOGY
Think of ACID Transactions like an ATM cash withdrawal: either money leaves your bank balance AND dispenses from the machine, or if a power cut happens, everything cancels cleanly with zero money lost!
📌 1. Transaction Commit (START TRANSACTION & COMMIT)
- Execute atomic database modifications and persist them permanently with
COMMIT. - Apply course fee update and commit.
📌 2. Transaction Rollback (ROLLBACK)
- Revert dangerous or failing operations safely using
ROLLBACK. - Safely undo accidental record deletions.
🧠 Topic 23 Practice Quiz
Q1. What does the ACID acronym stand for in database management?
✅ Correct Answer: Option B
Explanation: (ACID stands for Atomicity, Consistency, Isolation, and Durability.)
Explanation: (ACID stands for Atomicity, Consistency, Isolation, and Durability.)
Q2. Which command permanently saves all changes made during the current transaction?
✅ Correct Answer: Option C
Explanation: (
Explanation: (
COMMIT permanently saves all transactional changes to the database.)
Q3. Which command undoes all changes made during the current transaction?
✅ Correct Answer: Option D
Explanation: (
Explanation: (
ROLLBACK cancels and undoes all changes made since the transaction began.)
Q4. Which ACID property guarantees that all operations in a transaction succeed, or none do (all-or-nothing)?
✅ Correct Answer: Option A
Explanation: (Atomicity ensures that a transaction is treated as a single indivisible unit: either all steps execute or none do.)
Explanation: (Atomicity ensures that a transaction is treated as a single indivisible unit: either all steps execute or none do.)
Topic 23 Interview Questions & Answers
Q1: What do the 4 ACID properties mean in simple words?
Answer: Atomicity: All operations succeed or all fail (all-or-nothing).
Consistency: The database remains valid before and after.
Isolation: Concurrent transactions don't interfere with each other.
Durability: Committed changes survive crashes permanently.
Consistency: The database remains valid before and after.
Isolation: Concurrent transactions don't interfere with each other.
Durability: Committed changes survive crashes permanently.
Q2: What is the difference between COMMIT and ROLLBACK?
Answer:
COMMIT permanently saves changes made in a transaction to the database. ROLLBACK discards all changes and reverts the database to its previous state.
Q3: Give a real-world example of why database transactions are essential.
Answer: In a bank money transfer: deducting $100 from Account A and adding $100 to Account B must be atomic. If power fails halfway, ROLLBACK prevents money from disappearing into thin air.
24. Stored Procedures
AdvancedStored procedures store prepared SQL blocks on the server.
💡 IN SIMPLE WORDS / REAL-LIFE ANALOGY
Think of a Stored Procedure like a saved speed-dial shortcut on your phone that runs a 20-step monthly audit query with a single tap!
📌 1. Creating Stored Procedures (CREATE PROCEDURE)
- Compile reusable database code blocks inside server-side procedures.
- Define procedure to query student rosters.
📌 2. Invoking Stored Procedures (CALL)
- Invoke precompiled database stored procedures using
CALL. - Execute the GetStudents procedure.
🧠 Topic 24 Practice Quiz
Q1. What is a Stored Procedure in SQL?
✅ Correct Answer: Option D
Explanation: (A Stored Procedure is a compiled block of SQL code stored in the database catalog that can be reused repeatedly.)
Explanation: (A Stored Procedure is a compiled block of SQL code stored in the database catalog that can be reused repeatedly.)
Q2. Which statement executes a stored procedure in MySQL?
✅ Correct Answer: Option A
Explanation: (The
Explanation: (The
CALL procedure_name(); statement invokes and executes a stored procedure.)
Q3. What parameters can a stored procedure accept?
✅ Correct Answer: Option B
Explanation: (Stored procedures can accept
Explanation: (Stored procedures can accept
IN, OUT, and INOUT parameters.)
Q4. What is a key performance benefit of using stored procedures?
✅ Correct Answer: Option C
Explanation: (Stored procedures reduce network overhead (sending one CALL instead of multiple queries) and execute pre-compiled query plans.)
Explanation: (Stored procedures reduce network overhead (sending one CALL instead of multiple queries) and execute pre-compiled query plans.)
Topic 24 Interview Questions & Answers
Q1: What is a Stored Procedure and why is it used?
Answer: A Stored Procedure is pre-compiled SQL code saved in the database. It allows code reuse, reduces network traffic, improves execution speed, and increases security.
Q2: What is the difference between a Stored Procedure and a Function in SQL?
Answer: A Function must return a value and cannot execute DDL/DML inside SELECT queries. A Stored Procedure does not need to return a value, can return multiple result sets, and can execute any SQL statement.
Q3: What are IN, OUT, and INOUT parameters?
Answer:
IN passes data into the procedure. OUT returns calculated data back to the caller. INOUT accepts input and returns modified output.
25. Database Triggers
AdvancedTriggers run automatically in response to DML table events.
💡 IN SIMPLE WORDS / REAL-LIFE ANALOGY
Think of a Trigger like a smart motion detector alarm: the instant a burglar opens a window (an
INSERT or DELETE happens), the siren sounds and logs the event!
📌 1. Automatic Triggers (CREATE TRIGGER)
- Automatically execute logic on INSERT, UPDATE, or DELETE events.
- Trigger automatic student grade updates on new enrollment registration.
🧠 Topic 25 Practice Quiz
Q1. What is a Database Trigger in SQL?
✅ Correct Answer: Option A
Explanation: (A Trigger is a special routine that automatically executes whenever a specified event (INSERT, UPDATE, DELETE) occurs.)
Explanation: (A Trigger is a special routine that automatically executes whenever a specified event (INSERT, UPDATE, DELETE) occurs.)
Q2. Which database events can cause a trigger to execute?
✅ Correct Answer: Option D
Explanation: (Triggers fire in response to DML modification events:
Explanation: (Triggers fire in response to DML modification events:
INSERT, UPDATE, or DELETE.)
Q3. When can a trigger be configured to run relative to an event?
✅ Correct Answer: Option C
Explanation: (A trigger can be set to fire
Explanation: (A trigger can be set to fire
BEFORE or AFTER the triggering statement executes.)
Q4. Which keywords access the old and new column values of a modified row in a trigger?
✅ Correct Answer: Option B
Explanation: (
Explanation: (
OLD.column refers to the row before update/delete, and NEW.column refers to the new value being inserted/updated.)
Topic 25 Interview Questions & Answers
Q1: What is a Trigger in SQL and what is it commonly used for?
Answer: A Trigger is code that automatically runs when an INSERT, UPDATE, or DELETE event occurs. It is commonly used for audit logging, enforcing complex business rules, and validating data.
Q2: What is the difference between a BEFORE trigger and an AFTER trigger?
Answer: A
BEFORE trigger runs before changes are committed (ideal for validating or modifying values). An AFTER trigger runs after the changes are committed (ideal for audit logs or updating related tables).
Q3: What do the OLD and NEW qualifiers represent in triggers?
Answer:
OLD represents the column values before the modification (available in UPDATE and DELETE). NEW represents the new column values (available in INSERT and UPDATE).
26. Window Functions & Analytic Queries (OVER, PARTITION BY, ROW_NUMBER, RANK, LEAD, LAG)
Tier-1 MNC FavoriteWindow (Analytic) functions perform calculations across a set of table rows that are related to the current row without collapsing multiple rows into a single output row like GROUP BY does. They are the #1 most frequently tested SQL concept in technical interviews for Tier-1 product companies and data engineering roles.
💡 IN SIMPLE WORDS / REAL-LIFE ANALOGY
Think of Window Functions like a marathon runner looking over their shoulder to see their position relative to the runners immediately ahead and behind them!
📌 1. Ranking Functions: ROW_NUMBER(), RANK(), and DENSE_RANK()
ROW_NUMBER()assigns a unique, sequential integer to each row within a partition, never producing ties.RANK()assigns identical ranks to tied rows, but skips subsequent rank numbers (e.g. 1, 2, 2, 4).DENSE_RANK()assigns identical ranks to tied rows without skipping numbers (e.g. 1, 2, 2, 3) — ideal for N-th highest salary problems.- The
PARTITION BYclause divides the result set into distinct partitions, restarting the ranking for each group.
📌 2. Value Navigation & Running Aggregates: LEAD(), LAG(), and Running SUM()
LAG(col, offset)accesses data from a previous row in the partition without requiring a self-join — perfect for computing month-over-month growth.LEAD(col, offset)accesses data from a subsequent row in the partition.- Running total:
SUM(total_amount) OVER(ORDER BY order_date ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW)accumulates revenue continuously over time. - Window functions execute in the SELECT and ORDER BY phases, after WHERE, GROUP BY, and HAVING have evaluated.
🎯 Topic 26 Practice Quiz
Q1. What is the critical difference between RANK() and DENSE_RANK() when two rows tie for 2nd place?
✅ Correct Answer: Option C
Explanation: (RANK() leaves gaps when there are ties (1, 2, 2, 4), while DENSE_RANK() always assigns continuous rank numbers without gaps (1, 2, 2, 3).)
Explanation: (RANK() leaves gaps when there are ties (1, 2, 2, 4), while DENSE_RANK() always assigns continuous rank numbers without gaps (1, 2, 2, 3).)
Q2. Which clause inside the OVER() specification splits rows into independent calculation partitions?
✅ Correct Answer: Option A
Explanation: (PARTITION BY divides the dataset into independent subsets (like departments or countries); the window function resets its calculation for each partition.)
Explanation: (PARTITION BY divides the dataset into independent subsets (like departments or countries); the window function resets its calculation for each partition.)
Q3. Which window function allows you to inspect the value of a column from the immediately PRECEDING row?
✅ Correct Answer: Option D
Explanation: (LAG(column, offset) looks backward into earlier rows. LEAD(column, offset) looks forward into subsequent rows.)
Explanation: (LAG(column, offset) looks backward into earlier rows. LEAD(column, offset) looks forward into subsequent rows.)
Q4. In which SQL query phase are Window Functions evaluated by the database engine?
✅ Correct Answer: Option B
Explanation: (Window functions execute late in the query lifecycle: after FROM, WHERE, GROUP BY, and HAVING. For this reason, you cannot directly filter on a window function in a WHERE clause (use a CTE or subquery instead).)
Explanation: (Window functions execute late in the query lifecycle: after FROM, WHERE, GROUP BY, and HAVING. For this reason, you cannot directly filter on a window function in a WHERE clause (use a CTE or subquery instead).)
Topic 26 Interview Questions & Answers
Q1: How do you find the 2nd (or N-th) highest salary in each department using Window Functions?
Answer: Use a Common Table Expression (CTE) with
DENSE_RANK():WITH RankedSalaries AS (
SELECT name, Department, salary,
DENSE_RANK() OVER(PARTITION BY Department ORDER BY salary DESC) AS RankNo
FROM employees
)
SELECT name, Department, salary
FROM RankedSalaries
WHERE RankNo = 2;Using DENSE_RANK() ensures that if multiple employees tie for the highest salary, the next distinct salary receives rank 2.
Q2: What is the difference between GROUP BY and PARTITION BY?
Answer:
GROUP BY collapses multiple rows into a single summary row per group, eliminating individual row details unless aggregated. PARTITION BY (used in the OVER() clause) computes the aggregate or rank across the partition while preserving every individual original row in the final output.
Q3: What does the window frame specification 'ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW' mean?
Answer: It defines the exact sliding window of rows considered for the aggregate calculation. It instructs the engine to sum/average all rows from the very first row of the partition (
UNBOUNDED PRECEDING) down to the row currently being processed (CURRENT ROW), creating a true running cumulative calculation.
Q4: Can you use a Window Function directly inside a WHERE clause like 'WHERE ROW_NUMBER() OVER(...) <= 3'? Why or why not?
Answer: No. SQL evaluates the
WHERE clause before the SELECT clause where window functions are calculated. Attempting to place a window function in WHERE results in a syntax error. To filter by window function output, wrap the query in a CTE or derived subquery.
27. Common Table Expressions (CTEs) & Recursive Queries (WITH, WITH RECURSIVE)
Clean Modular SQLCommon Table Expressions (CTEs), defined using the WITH clause, create named temporary result sets that improve readability, modularity, and maintainability. Master both standard multi-step CTE pipelines and Recursive CTEs (WITH RECURSIVE) for traversing organizational hierarchies, tree categories, and graph networks.
💡 IN SIMPLE WORDS / REAL-LIFE ANALOGY
Think of a CTE (
WITH) like a clean whiteboard scratchpad where you work out intermediate calculations before writing the final solution on the blackboard!
📌 1. Standard Modular CTEs vs Deep Nested Subqueries
- Defined with
WITH CteName AS (SELECT ...), making queries read top-to-bottom like clean procedural code. - Chain multiple CTEs cleanly using comma separators:
WITH CteA AS (...), CteB AS (...) SELECT ... - Allows referencing the same intermediate result set multiple times in joins or unions without re-running expensive subqueries.
- Significantly easier to debug and unit test than 4-level nested inline subqueries.
📌 2. Recursive CTEs: Navigating Trees & Hierarchies
- A
WITH RECURSIVECTE references itself to iteratively unpack parent-child hierarchical trees. - Consists of two parts joined by
UNION ALL: the Anchor Member (base case, e.g. CEO) and the Recursive Member (step iterating child nodes). - A termination condition naturally halts recursion when no further child records exist, avoiding infinite loops.
- Standard production technique for Org Charts, Folder/File Trees, E-commerce Category Breadcrumbs, and Bill-of-Materials.
🎯 Topic 27 Practice Quiz
Q1. Which SQL keyword initiates the definition of a Common Table Expression (CTE)?
✅ Correct Answer: Option B
Explanation: (A CTE is always introduced with the WITH keyword: WITH CteName AS (SELECT ...).)
Explanation: (A CTE is always introduced with the WITH keyword: WITH CteName AS (SELECT ...).)
Q2. What are the two mandatory query components of a Recursive CTE joined by UNION ALL?
✅ Correct Answer: Option D
Explanation: (A Recursive CTE contains an Anchor query (returns the initial base set) and a Recursive query (references the CTE itself), joined by UNION ALL.)
Explanation: (A Recursive CTE contains an Anchor query (returns the initial base set) and a Recursive query (references the CTE itself), joined by UNION ALL.)
Q3. How do you define multiple CTEs within a single query?
✅ Correct Answer: Option A
Explanation: (Syntax: WITH Cte1 AS (...), Cte2 AS (...) SELECT ... The WITH keyword is written only once at the beginning.)
Explanation: (Syntax: WITH Cte1 AS (...), Cte2 AS (...) SELECT ... The WITH keyword is written only once at the beginning.)
Q4. What is a major advantage of a CTE over a temporary table created with 'CREATE TEMPORARY TABLE'?
✅ Correct Answer: Option C
Explanation: (CTEs exist only for the duration of the query. They require no DDL permissions, no disk space management, and no DROP statements.)
Explanation: (CTEs exist only for the duration of the query. They require no DDL permissions, no disk space management, and no DROP statements.)
Topic 27 Interview Questions & Answers
Q1: When would you choose a Common Table Expression (CTE) over a Subquery?
Answer: Use a CTE when: 1. You need clean, top-to-bottom readable code that avoids deep nesting. 2. You need to reference the intermediate result multiple times in the same query (avoiding repeated execution). 3. You need recursion to traverse hierarchical or graph data (Subqueries cannot do recursion).
Q2: How does a Recursive CTE prevent infinite loops, and how can you safeguard against runaway queries?
Answer: A Recursive CTE terminates automatically when the recursive member query returns zero rows (empty set). To prevent infinite loops caused by cyclical data (e.g. employee A reports to B who reports to A), developers use a recursion depth counter (
WHERE HierarchyLevel < 20) or database safety settings like MAXRECURSION.
Q3: Are CTEs materialized (cached in temporary memory) or evaluated inline like views?
Answer: In older PostgreSQL (pre-v12), CTEs were always materialized (acting as optimization fences). In modern PostgreSQL (v12+) and MySQL 8.0+, the cost-based optimizer inlines CTEs into the outer query unless explicitly instructed with
WITH cte AS MATERIALIZED (...).
Q4: Can a CTE be used with INSERT, UPDATE, or DELETE statements?
Answer: Yes. You can define a CTE before data manipulation statements, for example:
WITH StaleUsers AS (SELECT id FROM Users WHERE last_login < '2024-01-01') DELETE FROM Users WHERE id IN (SELECT id FROM StaleUsers);.
28. Database Normalization (1NF, 2NF, 3NF, BCNF) & Denormalization Architecture
Academic & System Design Core
Database Normalization is the art of organizing tables cleanly so you never duplicate the same customer address or phone number across 50 places. Each piece of information lives in exactly one place (1NF, 2NF, 3NF).
💡 IN SIMPLE WORDS / REAL-LIFE ANALOGY
Think of Normalization like organizing a messy tool shed: putting screws in one labeled drawer and wrenches on a pegboard so nothing is duplicated or lost!
📌 1. The Normal Forms: 1NF, 2NF, 3NF, and BCNF
- 1NF (First Normal Form): Every column value must be atomic (no arrays, comma-separated lists, or nested tables); each row must have a unique identifier.
- 2NF (Second Normal Form): Must be in 1NF AND have no Partial Functional Dependencies (non-key attributes must depend on the whole composite primary key, not just part of it).
- 3NF (Third Normal Form): Must be in 2NF AND have no Transitive Functional Dependencies (non-key attributes must not depend on other non-key attributes: A → B → C).
- BCNF (Boyce-Codd Normal Form): Stricter 3NF where every determinant (left side of functional dependency X → Y) must be a super key / candidate key.
📌 2. Database Anomalies & Production Denormalization (OLTP vs OLAP)
- Insertion Anomaly: Inability to add data about an entity without artificially creating an unrelated entity.
- Update Anomaly: Modifying a repeated value in one row leaves contradictory data in other rows.
- Deletion Anomaly: Deleting one record inadvertently deletes valuable metadata about another entity.
- When to Denormalize: While transactional databases (OLTP) require 3NF, analytical data warehouses (OLAP, Snowflake, BigQuery) intentionally denormalize into Star and Snowflake schemas to avoid multi-table JOIN latency.
🎯 Topic 28 Practice Quiz
Q1. What requirement must a table satisfy to conform to First Normal Form (1NF)?
✅ Correct Answer: Option D
Explanation: (1NF requires that each column contains only atomic (single) values (e.g. no comma-separated phone numbers: '9876543210, 8765432109') and each row is uniquely identifiable.)
Explanation: (1NF requires that each column contains only atomic (single) values (e.g. no comma-separated phone numbers: '9876543210, 8765432109') and each row is uniquely identifiable.)
Q2. A table is in 1NF. Which type of dependency must be eliminated for it to achieve Second Normal Form (2NF)?
✅ Correct Answer: Option B
Explanation: (2NF eliminates partial dependencies: every non-prime attribute must depend on the whole candidate key, not just a subset of a composite key.)
Explanation: (2NF eliminates partial dependencies: every non-prime attribute must depend on the whole candidate key, not just a subset of a composite key.)
Q3. In Third Normal Form (3NF), what type of functional dependency is strictly forbidden?
✅ Correct Answer: Option C
Explanation: (3NF forbids transitive dependencies: non-key columns must depend strictly and directly on the primary key, and nothing but the key.)
Explanation: (3NF forbids transitive dependencies: non-key columns must depend strictly and directly on the primary key, and nothing but the key.)
Q4. Why do enterprise Data Warehouses (OLAP) frequently use DENORMALIZED schemas (such as Star Schemas)?
✅ Correct Answer: Option A
Explanation: (In analytical systems (OLAP), read speed is paramount. Denormalizing tables reduces the number of JOINs required to answer complex business intelligence questions.)
Explanation: (In analytical systems (OLAP), read speed is paramount. Denormalizing tables reduces the number of JOINs required to answer complex business intelligence questions.)
Topic 28 Interview Questions & Answers
Q1: Explain Insertion, Update, and Deletion Anomalies with a concrete unnormalized table example.
Answer: Consider an unnormalized table:
Student_Course(StudentID, StudentName, CourseID, CourseName, Instructor).- Insertion Anomaly: You cannot add a newly created Course if no students have enrolled yet, because
StudentID(Primary Key) cannot be null. - Update Anomaly: If an Instructor's name changes, you must update hundreds of student rows. If one row is missed, data becomes inconsistent.
- Deletion Anomaly: If the only student enrolled in a course drops out and is deleted, all records of that Course and Instructor are accidentally wiped from the database!
Students, Courses, and Enrollments tables solves all three anomalies.
Q2: What is the difference between Third Normal Form (3NF) and Boyce-Codd Normal Form (BCNF)?
Answer: BCNF is a stricter version of 3NF. In 3NF, for any functional dependency
X → Y, either X is a super key OR Y is a prime attribute (part of a candidate key). In BCNF, the second relaxation is removed: for every non-trivial dependency X → Y, X must strictly be a super key.
Q3: Compare OLTP (Online Transaction Processing) schemas with OLAP (Online Analytical Processing) schemas.
Answer:
- OLTP: Highly normalized (3NF), optimized for rapid
INSERT/UPDATE/DELETEtransactions, minimizes redundancy, used in banking and e-commerce order management. - OLAP: Denormalized (Star or Snowflake schemas), optimized for massive analytical
SELECTqueries, reporting dashboards, and business intelligence (BI) data warehouses.
Q4: What is a Functional Dependency, and how do you determine Candidate Keys from dependencies?
Answer: A functional dependency
X → Y means that the value of column set X uniquely determines the value of column set Y. A Candidate Key is a minimal set of attributes whose attribute closure (all attributes it can determine) equals the entire relation, with no redundant attributes.
29. Query Execution Plans & Advanced Performance Tuning (EXPLAIN ANALYZE, SARGability)
Senior DBA / Performance
Fast queries save money and keep apps snappy! Learn how to use
EXPLAIN ANALYZE to see how the database engine reads your data, how indexes work, and how to make slow queries run in lightning-fast milliseconds.
💡 IN SIMPLE WORDS / REAL-LIFE ANALOGY
Think of
EXPLAIN ANALYZE like an X-ray machine for database queries, showing which query steps took 2 milliseconds and which ones got stuck in traffic!
📌 1. Reading EXPLAIN Plans: Scans & Cost Estimations
EXPLAIN querydisplays the database optimizer's execution plan and estimated costs without actually running the query.EXPLAIN ANALYZE queryactually executes the query in the engine and outputs real measured execution times, row counts, and memory buffer usage.- Sequential Scan (Table Scan): Reads every single block on disk sequentially — terrible for large tables without indexes.
- Index Scan vs Index Range Scan: Traverses a B-Tree index directly to matching rows; Index Range Scan retrieves a range between lower and upper bounds.
📌 2. SARGability & Composite Index Leftmost Prefix Rule
- SARGable (Search ARGument Able): A query predicate that allows the database engine to use an index seek rather than scanning the entire table.
- Non-SARGable Trap: Wrapping indexed columns inside functions (e.g.
WHERE YEAR(hire_date) = 2022) disables B-Tree indexes! Rewrite as a range:WHERE hire_date >= '2022-01-01' AND hire_date < '2023-01-01'. - Leftmost Prefix Rule: A composite index on
(A, B, C)can accelerate queries filtering on(A),(A, B), or(A, B, C), but cannot be used if filtering only on(B)or(C)alone. - Leading Wildcard Trap:
WHERE name LIKE '%Sharma'cannot use B-Tree indexes;WHERE name LIKE 'Aarav%'uses index range scans efficiently.
🎯 Topic 29 Practice Quiz
Q1. What is the critical operational difference between 'EXPLAIN' and 'EXPLAIN ANALYZE'?
✅ Correct Answer: Option A
Explanation: (EXPLAIN generates an execution plan based on statistical estimates. EXPLAIN ANALYZE actually runs the query, providing real runtimes, actual row counts, and buffer hits.)
Explanation: (EXPLAIN generates an execution plan based on statistical estimates. EXPLAIN ANALYZE actually runs the query, providing real runtimes, actual row counts, and buffer hits.)
Q2. Why is 'WHERE YEAR(hire_date) = 2022' considered a non-SARGable query anti-pattern?
✅ Correct Answer: Option C
Explanation: (Functions applied to columns must be evaluated on every single row individually, blinding the B-Tree index and forcing a slow full table scan. Rewriting as a range comparison restores index usage.)
Explanation: (Functions applied to columns must be evaluated on every single row individually, blinding the B-Tree index and forcing a slow full table scan. Rewriting as a range comparison restores index usage.)
Q3. If an index is created on columns (City, Department, Salary), which WHERE clause CANNOT use this index?
✅ Correct Answer: Option B
Explanation: (Due to the Leftmost Prefix Rule, a composite index must be queried starting with its leading column (City). Filtering on (Department, Salary) without City skips the root of the B-Tree index.)
Explanation: (Due to the Leftmost Prefix Rule, a composite index must be queried starting with its leading column (City). Filtering on (Department, Salary) without City skips the root of the B-Tree index.)
Q4. What is a 'Covering Index' (also called an Index-Only Scan)?
✅ Correct Answer: Option D
Explanation: (When an index contains all columns requested by a query (both WHERE and SELECT clauses), the engine satisfies the query entirely from RAM/index pages without touching the table data file.)
Explanation: (When an index contains all columns requested by a query (both WHERE and SELECT clauses), the engine satisfies the query entirely from RAM/index pages without touching the table data file.)
Topic 29 Interview Questions & Answers
Q1: What are SARGable queries, and what are 3 common examples of non-SARGable patterns you frequently fix?
Answer: SARGable stands for Search ARGument Able — queries structured so the database optimizer can use an index seek.
Common Non-SARGable Fixes:
1. Function wrapping:
2. Math on columns:
3. Leading wildcards:
Common Non-SARGable Fixes:
1. Function wrapping:
WHERE SUBSTRING(name, 1, 3) = 'Aar' → Fix: WHERE name LIKE 'Aar%'.2. Math on columns:
WHERE salary * 1.1 > 100000 → Fix: WHERE salary > 100000 / 1.1.3. Leading wildcards:
WHERE email LIKE '%gmail.com' → cannot use standard B-Tree index (requires reverse index, trigram index, or full-text search).
Q2: How does the database optimizer decide between Nested Loop Join, Hash Join, and Merge Join?
Answer:
- Nested Loop Join: Best when one table is very small and the inner table has an index on the join key (for each outer row, an index seek is performed).
- Hash Join: Best for joining large, unsorted datasets. The engine builds an in-memory hash table of the smaller relation, then streams the larger table against it.
- Merge Join (Sort-Merge): Best when both tables are already sorted on the join key (e.g. by index) or need to be sorted anyway. It scans both sorted inputs in lockstep.
Q3: What is the difference between Cardinality and Selectivity in database indexing?
Answer: Cardinality is the count of distinct values in a column (e.g.
user_id has high cardinality; gender has low cardinality). Selectivity is the percentage of rows filtered by a predicate (Distinct Values / Total Rows). Indexes on high-cardinality, high-selectivity columns are vastly more effective.
Q4: What causes an 'Index Fragmentation' problem, and how do you resolve it?
Answer: Frequent
INSERT, UPDATE, and DELETE operations cause B-Tree leaf pages to split unevenly and leave empty space, fragmenting data across non-contiguous disk sectors. This is resolved by rebuilding or reorganizing the index: OPTIMIZE TABLE table_name; (MySQL) or REINDEX TABLE table_name; (PostgreSQL).
30. Database Security, Access Control (DCL) & SQL Injection Prevention
Security & Enterprise RBACA single data breach can bankrupt a company. Master Data Control Language (DCL) commands (GRANT, REVOKE), Role-Based Access Control (RBAC), the internal mechanics of SQL Injection vulnerabilities, Parameterized Prepared Statements, Row-Level Security (RLS), and soft delete audit compliance.
💡 IN SIMPLE WORDS / REAL-LIFE ANALOGY
Think of SQL Injection Prevention like using a secure drive-through window with an intercom instead of letting strangers walk into the bank vault with their own keys!
📌 1. Data Control Language (DCL) & Role-Based Access Control (RBAC)
GRANT privilege ON object TO user/roleconfers specific permissions (SELECT, INSERT, UPDATE, DELETE).REVOKE privilege ON object FROM user/rolewithdraws permissions safely.- Principle of Least Privilege: Web applications must NEVER connect to a database using the
rootorpostgressuperuser account; they should use a dedicated application user with restricted rights. - Create reusable roles:
CREATE ROLE analyst_team; GRANT SELECT ON sales.* TO analyst_team;.
📌 2. SQL Injection Anatomy & Prepared Statements Defense
- SQL Injection: Occurs when untrusted user input is directly concatenated into a dynamic SQL string, allowing attackers to modify the SQL abstract syntax tree (AST).
- Classic Attack: Inputting
admin' OR '1'='1changesWHERE user = '$input'into a universal true condition, bypassing password authentication. - Prepared Statements (Parameterized Queries): The database compiles the SQL query structure FIRST; user input is passed separately as pure data parameters, making SQL injection 100% mathematically impossible.
- Row-Level Security (RLS): PostgreSQL/MySQL feature restricting multi-tenant SaaS users to seeing only their own company's rows.
🎯 Topic 30 Practice Quiz
Q1. Which two SQL commands belong to Data Control Language (DCL)?
✅ Correct Answer: Option C
Explanation: (GRANT confers database permissions to users or roles; REVOKE removes them. Both are DCL commands.)
Explanation: (GRANT confers database permissions to users or roles; REVOKE removes them. Both are DCL commands.)
Q2. Why are Parameterized Queries (Prepared Statements) 100% immune to SQL Injection attacks?
✅ Correct Answer: Option D
Explanation: (In prepared statements, query compilation and parameter passing are decoupled. Even if a user enters ' OR '1'='1, the engine treats it as a literal string parameter.)
Explanation: (In prepared statements, query compilation and parameter passing are decoupled. Even if a user enters ' OR '1'='1, the engine treats it as a literal string parameter.)
Q3. What is the security Principle of Least Privilege in database administration?
✅ Correct Answer: Option B
Explanation: (The Principle of Least Privilege mandates that applications only receive minimum necessary permissions (e.g. SELECT, INSERT on specific tables; no DROP or ALTER permissions).)
Explanation: (The Principle of Least Privilege mandates that applications only receive minimum necessary permissions (e.g. SELECT, INSERT on specific tables; no DROP or ALTER permissions).)
Q4. What is the purpose of Row-Level Security (RLS) in databases like PostgreSQL?
✅ Correct Answer: Option A
Explanation: (Row-Level Security allows database engines to enforce security policies at the database layer (e.g. 'tenants can only view rows where tenant_id = current_tenant').)
Explanation: (Row-Level Security allows database engines to enforce security policies at the database layer (e.g. 'tenants can only view rows where tenant_id = current_tenant').)
Topic 30 Interview Questions & Answers
Q1: Walk through the exact mechanism of an 'OR 1=1' SQL Injection attack, and explain why string sanitization often fails.
Answer: Consider vulnerable backend code:
If an attacker inputs
The double-dash
query = 'SELECT * FROM Users WHERE user="' + inputUser + '" AND pass="' + inputPass + '"';.If an attacker inputs
admin" -- into the username field, the query becomes:SELECT * FROM Users WHERE user="admin" -- AND pass="...".The double-dash
-- comments out the password verification entirely! String sanitization (like stripping quotes) often fails due to alternate character encodings. Only Prepared Statements prevent this because parameters are never parsed as SQL tokens.
Q2: What is the difference between a Hard Delete and a Soft Delete, and what are the best practices for implementing soft deletes?
Answer:
- Hard Delete: Permanently deletes the row via
DELETE FROM Table. Cannot be undone without restoring from backups. - Soft Delete: Flags the record as deleted using an audit column:
deleted_at TIMESTAMP NULLoris_active BOOLEAN DEFAULT TRUE. - Best Practice: Use views (e.g.
ActiveUsers) withWHERE deleted_at IS NULL, or use partial unique indexes (e.g.CREATE UNIQUE INDEX ON users(email) WHERE deleted_at IS NULL;) so a user can re-register after deleting an old account.
Q3: What security measures should be implemented to protect database credentials and connection pools?
Answer: 1. Store credentials in Environment Variables or Secrets Managers (AWS Secrets Manager, HashiCorp Vault), never in code repositories. 2. Enforce TLS/SSL encryption for all database connections in transit. 3. Configure IP allowlisting so the DB accepts connections only from application servers within the private VPC.
Q4: What is SQL Query Obfuscation / Masking in compliance regulations (GDPR, HIPAA, PCI-DSS)?
Answer: Dynamic Data Masking prevents unauthorized users (such as customer support or staging environments) from viewing sensitive PII (Personally Identifiable Information). For example, masking credit card numbers as
XXXX-XXXX-XXXX-1234 or emails as a***v@example.com directly at the database query layer.
31. Advanced Modern SQL: JSON Semi-Structured Queries, UPSERT (MERGE) & NULL Logic
Modern PostgreSQL/MySQL 8+Modern relational databases (PostgreSQL, MySQL 8+, SQLite) are hybrid document-relational engines capable of querying structured relational tables and unstructured JSON documents within the same query. Master JSON extraction operators, high-throughput UPSERT operations (INSERT ... ON DUPLICATE KEY UPDATE / ON CONFLICT DO UPDATE / MERGE), and the subtle traps of SQL's Three-Valued Logic (TRUE, FALSE, UNKNOWN).
💡 IN SIMPLE WORDS / REAL-LIFE ANALOGY
Think of UPSERT like a smart hotel guest check-in: if the guest already exists, update their room key; if they are new, create a fresh guest profile!
📌 1. Querying Semi-Structured JSON Documents in SQL
- Modern databases support native
JSONandJSONBdata types with schema validation and indexing. - Extract JSON fields using standard operators:
->(extracts as JSON object/value) and->>(extracts as unquoted text/string). - Functions like
JSON_EXTRACT(),JSON_ARRAYAGG(), andJSON_OBJECT()allow converting relational rows into JSON APIs directly inside the database. - GIN (Generalized Inverted Index) indexes allow instant indexing of nested JSON keys for lightning-fast sub-document lookups.
📌 2. UPSERT Operations & Navigating SQL Three-Valued Logic
- UPSERT (Insert or Update): Atomically inserts a new row, or updates the existing row if a primary key or unique constraint conflict occurs.
- MySQL Syntax:
INSERT INTO t (...) VALUES (...) ON DUPLICATE KEY UPDATE col = VALUES(col); - PostgreSQL Syntax:
INSERT INTO t (...) VALUES (...) ON CONFLICT (id) DO UPDATE SET ...; - ANSI Standard:
MERGE INTO target USING source ON (...) WHEN MATCHED THEN UPDATE ... WHEN NOT MATCHED THEN INSERT ...; - Three-Valued Logic (3VL): In SQL, boolean expressions evaluate to
TRUE,FALSE, orUNKNOWN.NULL = NULLevaluates to UNKNOWN! Always useIS NULL,COALESCE(), orNULLIF().
🎯 Topic 31 Practice Quiz
Q1. What does the comparison expression 'WHERE col = NULL' evaluate to in SQL?
✅ Correct Answer: Option B
Explanation: (In SQL Three-Valued Logic, NULL represents 'unknown'. Comparing anything with NULL using '=' produces UNKNOWN, which WHERE treats as false. You must use 'IS NULL'.)
Explanation: (In SQL Three-Valued Logic, NULL represents 'unknown'. Comparing anything with NULL using '=' produces UNKNOWN, which WHERE treats as false. You must use 'IS NULL'.)
Q2. What does the function COALESCE(val1, val2, val3) return?
✅ Correct Answer: Option A
Explanation: (COALESCE returns the very first argument that is not NULL. If all arguments are NULL, it returns NULL.)
Explanation: (COALESCE returns the very first argument that is not NULL. If all arguments are NULL, it returns NULL.)
Q3. In PostgreSQL, what is the syntax for performing an atomic UPSERT operation?
✅ Correct Answer: Option C
Explanation: (PostgreSQL uses the ON CONFLICT clause: INSERT INTO t VALUES (...) ON CONFLICT (id) DO UPDATE SET name = EXCLUDED.name;.)
Explanation: (PostgreSQL uses the ON CONFLICT clause: INSERT INTO t VALUES (...) ON CONFLICT (id) DO UPDATE SET name = EXCLUDED.name;.)
Q4. What is the difference between JSON operator '->' and '->>' in modern SQL databases?
✅ Correct Answer: Option D
Explanation: (-> extracts the element as a JSON value (e.g. "Aarav"). ->> extracts the element as a raw text string without JSON quotes (e.g. Aarav).)
Explanation: (-> extracts the element as a JSON value (e.g. "Aarav"). ->> extracts the element as a raw text string without JSON quotes (e.g. Aarav).)
Topic 31 Interview Questions & Answers
Q1: Why does 'SELECT * FROM Table WHERE col = NULL' fail, and what is SQL Three-Valued Logic (3VL)?
Answer: In relational algebra,
Any comparison with
NULL represents the absence of a value or an unknown state, not a zero or empty string. Therefore, SQL uses Three-Valued Logic (3VL) with truth values: TRUE, FALSE, and UNKNOWN.Any comparison with
NULL (e.g. col = NULL or NULL = NULL) yields UNKNOWN. Because a WHERE clause only outputs rows where the predicate is strictly TRUE, WHERE col = NULL will never match any row! Always use col IS NULL or col IS NOT NULL.
Q2: What is the difference between COALESCE() and NULLIF()?
Answer:
COALESCE(val1, val2, ...)returns the first non-null expression from the list (used for default values).NULLIF(val1, val2)compares two values: ifval1 == val2, it returns NULL; otherwise it returnsval1. (Heavily used to prevent division-by-zero errors:total / NULLIF(count, 0)).
Q3: Compare UPSERT approaches across MySQL, PostgreSQL, and ANSI SQL.
Answer:
- MySQL:
INSERT INTO t (id, val) VALUES (1, 'A') ON DUPLICATE KEY UPDATE val = VALUES(val); - PostgreSQL:
INSERT INTO t (id, val) VALUES (1, 'A') ON CONFLICT (id) DO UPDATE SET val = EXCLUDED.val; - ANSI SQL / Oracle / SQL Server:
MERGE INTO target USING source ON (target.id = source.id) WHEN MATCHED THEN UPDATE ... WHEN NOT MATCHED THEN INSERT ...;
Q4: When should you choose to store attributes in a JSON column versus creating traditional normalized relational tables?
Answer: Use a JSON column when: 1. Attributes are highly dynamic, polymorphic, or sparse (e.g. third-party webhook payloads, user UI preferences, e-commerce product custom specs). 2. Schema changes frequently and DDL migrations are too costly.
Use Relational Tables when: 1. Data requires strict foreign key integrity. 2. Fields are frequently filtered in
Use Relational Tables when: 1. Data requires strict foreign key integrity. 2. Fields are frequently filtered in
WHERE clauses and joined across tables. 3. Maximum query execution performance is required.
32. Real-World SQL Practice
Capstone PracticeMastery practice queries combining multi-table JOINs and aggregations.
💡 IN SIMPLE WORDS / REAL-LIFE ANALOGY
Think of this practice lab like running real analytics for an e-commerce giant like Amazon or Flipkart to find top-selling products!
📌 1. Geographic Student Enrollment Report
- Multi-clause query combining aggregation, grouping, and LEFT JOIN.
- Aggregate total students, total enrollments, and tuition fees grouped by city.
📌 2. Course Revenue & Student Portfolio
- Generate comprehensive executive analytics joining master and relational tables.
- Analyze course enrollment counts, average student age, and total tuition revenue.
🧠 Topic 25 Practice Quiz
Q1. Which clause is used to filter aggregated data generated by GROUP BY?
✅ Correct Answer: Option D
Explanation: (
Explanation: (
HAVING filters grouped aggregate results (e.g. HAVING COUNT(*) > 10).)
Q2. How can you retrieve the top 3 highest paid employees from an employees table?
✅ Correct Answer: Option C
Explanation: (
Explanation: (
ORDER BY salary DESC LIMIT 3; sorts highest first and takes the top 3.)
Q3. Which join should you use to find customers who have NEVER placed any orders?
✅ Correct Answer: Option A
Explanation: (A
Explanation: (A
LEFT JOIN combined with WHERE orders.id IS NULL finds records on the left that have no matching records on the right.)
Q4. What is the purpose of using window functions like ROW_NUMBER() in SQL?
✅ Correct Answer: Option B
Explanation: (Window functions perform calculations across related row sets while retaining each individual row in the output.)
Explanation: (Window functions perform calculations across related row sets while retaining each individual row in the output.)
Topic 32 Interview Questions & Answers
Q1: How do you find the 2nd highest salary from an Employees table?
Answer: A simple approach is:
SELECT MAX(salary) FROM Employees WHERE salary < (SELECT MAX(salary) FROM Employees); or using pagination: SELECT DISTINCT salary FROM Employees ORDER BY salary DESC LIMIT 1 OFFSET 1;.
Q2: How do you identify and remove duplicate rows in SQL?
Answer: You can find duplicates by grouping by the duplicate columns:
SELECT email, COUNT(*) FROM Users GROUP BY email HAVING COUNT(*) > 1;. Duplicates can be removed using window functions like ROW_NUMBER().
Q3: What are 3 basic best practices for writing high-performance SQL queries?
Answer: 1. Select only needed columns (avoid
2. Use proper indexes on WHERE and JOIN columns.
3. Use
SELECT *).2. Use proper indexes on WHERE and JOIN columns.
3. Use
LIMIT for pagination instead of loading millions of rows into memory.
📥 Download SQL Complete Masterclass Notes (All 32 Topics)
Study Resource📑
SQL Database Engineering Handbook
🎓 SQL Course Certificate of Completion
100% Certified🏆
Official SQL Database Specialist Credential
✓ Includes Verification ID • Course Completion Seal • Instant Download