Chapter 05
SQL Views, Indexes & Practice
4 topics · 1 sections · beginner-friendly study notes · Updated
A view is a saved query that works like a virtual table.
An index makes searching faster.
A transaction groups changes so they are saved together (COMMIT) or cancelled together (ROLLBACK).
This chapter ends with popular interview queries.
Views make queries simple and safe.
Indexes make big tables fast.
Transactions protect money and important data.
Interviews love these topics.
Banking transfers use transactions.
Reports use views.
Search boxes depend on indexes.
CREATE VIEW
A view is a virtual table based on a SELECT query. It stores the query, not the data.
In short: A view is a saved query with a name. We can use it like a table.
Think about it
Views simplify long queries, add security and keep applications working even if table design changes. The college shows a "public student list" with only name and department. The full register with phone numbers stays hidden.
CREATE VIEW view_name AS SELECT ....
After that, SELECT * FROM view_name runs the saved query each time.
Views can hide columns (for example salary), join many tables into one simple shape, and give users limited access.
A simple view on one table can often be updated with INSERT, UPDATE or DELETE and the base table changes.
Views with joins, GROUP BY or DISTINCT are usually read-only.
CREATE OR REPLACE VIEW changes the query of an existing view.
DROP VIEW removes the view only, not the real data.
A materialized view (PostgreSQL, Oracle) stores the result physically to make it faster.
Key points
Example
CodeCreate and use a view: CREATE VIEW student_public AS SELECT s.roll_no, s.name, d.dept_name FROM student s JOIN department d ON s.dept_id = d.dept_id; -- Use it like a table SELECT * FROM student_public WHERE dept_name = 'CSE'; -- Change the view CREATE OR REPLACE VIEW student_public AS SELECT s.roll_no, s.name, s.city, d.dept_name FROM student s JOIN department d ON s.dept_id = d.dept_id; -- Remove the view DROP VIEW student_public;
Indexes in SQL
An index is a special lookup structure that helps the database find rows faster without scanning the whole table.
In short: An index is like the index page of a book. You go straight to the right page instead of reading every page.
Think about it
A search on a table with millions of rows can drop from seconds to milliseconds with a good index. To find "Photosynthesis" in a textbook, you look at the index page instead of reading all 300 pages.
Without an index, the database does a full table scan and checks every row.
With an index on a column, it jumps to the matching rows quickly.
Most databases use a B-tree structure.
A PRIMARY KEY and a UNIQUE constraint create an index automatically.
CREATE INDEX makes a normal index.
CREATE UNIQUE INDEX also blocks duplicates.
A composite index uses more than one column and follows the left-most column rule.
Indexes make SELECT faster, but they take extra space and make INSERT, UPDATE and DELETE a little slower because the index must be updated too.
Index columns used often in WHERE, JOIN and ORDER BY.
Do not index every column.
Small tables and columns with very few different values (like gender) gain little.
Key points
- Full table scan: Reading every row to find a match.
- B-tree: Common balanced tree used by indexes.
- Composite index: Index on two or more columns.
- Unique index: Index that also stops duplicate values.
- Indexes speed up reading but slow down writing slightly.
- Primary key and unique columns already have indexes.
- Index columns used in WHERE, JOIN and ORDER BY.
Example
CodeCreating indexes: -- Normal index CREATE INDEX idx_student_city ON student(city); -- Unique index CREATE UNIQUE INDEX idx_student_email ON student(email); -- Composite index CREATE INDEX idx_city_marks ON student(city, marks); -- Check that the query uses the index EXPLAIN SELECT * FROM student WHERE city = "Delhi"; -- Remove an index (MySQL) DROP INDEX idx_student_city ON student;
Transactions (COMMIT, ROLLBACK)
A transaction is a group of SQL statements treated as one unit. COMMIT saves all changes. ROLLBACK cancels all changes made since the transaction began.
In short: Either everything happens or nothing happens.
Think about it
Without transactions, a crash in the middle of work can leave data half-changed and wrong. Transferring Rs 500 from Asha to Ravi. Both the debit and the credit must happen, or neither.
Classic example: transferring money.
We subtract from account A and add to account B. If the second step fails, the first must be cancelled, or money is lost.
Start a transaction with START TRANSACTION (or BEGIN).
Then run the statements.
If all is well, run COMMIT.
If something goes wrong, run ROLLBACK.
SAVEPOINT marks a point inside a transaction, and ROLLBACK TO savepoint_name goes back only to that point.
Transactions follow the ACID rules: Atomicity (all or nothing), Consistency (data stays valid), Isolation (users do not disturb each other) and Durability (committed data is never lost).
Many databases use auto-commit, so every single statement is saved immediately unless a transaction is started.
DDL commands like CREATE and DROP usually commit automatically in MySQL and Oracle.
Key points
- COMMIT: Saves the transaction permanently.
- ROLLBACK: Cancels the changes of the transaction.
- SAVEPOINT: A named point to roll back to.
- ACID: Atomicity, Consistency, Isolation, Durability.
- Auto-commit: Each statement is saved immediately.
- COMMIT = save. ROLLBACK = undo.
- After COMMIT you cannot ROLLBACK.
- Transactions work with transactional engines such as InnoDB.
Example
CodeTransaction examples: START TRANSACTION; UPDATE account SET balance = balance - 500 WHERE acc_no = 101; UPDATE account SET balance = balance + 500 WHERE acc_no = 102; -- Everything worked, so save it COMMIT; -- Using SAVEPOINT START TRANSACTION; INSERT INTO student (roll_no, name) VALUES (10, "Neha"); SAVEPOINT after_neha; INSERT INTO student (roll_no, name) VALUES (11, "Karan"); -- Undo only Karan ROLLBACK TO after_neha; COMMIT; -- Cancel everything START TRANSACTION; DELETE FROM student; ROLLBACK;
Common SQL Interview Queries
These are the queries most often asked in interviews: Nth highest salary, duplicate rows, rows without a match, department-wise top salary and counting by group.
In short: A small set of patterns repeats in almost every SQL interview. Learn the pattern and you can solve many questions.
Think about it
Practising these patterns builds confidence for interviews and for real reports. Finding the third highest marks in the class, or students who were entered twice in the register.
Nth highest salary: use ORDER BY with LIMIT and OFFSET, or a correlated subquery, or DENSE_RANK() in modern databases.
Find duplicates: GROUP BY the column and use HAVING COUNT(*) > 1.
Delete duplicates: keep the smallest id and delete the rest.
Employees without department: LEFT JOIN and IS NULL, or NOT EXISTS.
Highest salary per department: join with a grouped subquery or use a correlated subquery.
Count per group: GROUP BY with COUNT.
Top N per group: use ROW_NUMBER() OVER (PARTITION BY ...
).
Difference between WHERE and HAVING, DELETE and TRUNCATE, and UNION and UNION ALL are also frequent theory questions.
UNION removes duplicates, UNION ALL keeps them and is faster.
Key points
- LIMIT / OFFSET: Skip some rows and take the next ones.
DENSE_RANK(): Ranking function without gaps for ties.ROW_NUMBER(): Gives each row a unique number inside a window.- UNION vs UNION ALL: UNION removes duplicates. UNION ALL keeps all rows.
- Duplicates = GROUP BY + HAVING COUNT(*) > 1.
- Nth highest = LIMIT 1 OFFSET N-1 on distinct salaries.
- No match = LEFT JOIN ... IS NULL or NOT EXISTS.
Read more
Example
CodePopular interview queries:
-- 1. Second highest salary
SELECT DISTINCT salary FROM employees
ORDER BY salary DESC
LIMIT 1 OFFSET 1;
-- 2. Nth highest salary (N = 3) using DENSE_RANK
SELECT salary FROM (
SELECT salary, DENSE_RANK() OVER (ORDER BY salary DESC) AS rnk
FROM employees
) t
WHERE rnk = 3 LIMIT 1;
-- 3. Find duplicate emails
SELECT email, COUNT(*) AS times
FROM student
GROUP BY email
HAVING COUNT(*) > 1;
-- 4. Delete duplicates, keep the smallest roll_no (MySQL)
DELETE s1 FROM student s1
JOIN student s2
ON s1.email = s2.email AND s1.roll_no > s2.roll_no;
-- 5. Highest salary in every department
SELECT d.dept_name, MAX(e.salary) AS max_salary
FROM employees e
JOIN department d ON e.dept_id = d.dept_id
GROUP BY d.dept_name;
-- 6. Employees who earn more than their manager
SELECT e.name
FROM employees e
JOIN employees m ON e.manager_id = m.emp_id
WHERE e.salary > m.salary;
-- 7. Top 2 salaries in each department
SELECT * FROM (
SELECT name, dept_id, salary,
ROW_NUMBER() OVER (PARTITION BY dept_id ORDER BY salary DESC) AS rn
FROM employees
) t
WHERE rn <= 2;
-- 8. Students who have no marks entered
SELECT name FROM student WHERE marks IS NULL;Solved examples
Create a view that shows only name and department of employees (hide salary), then read from it.
- employees(emp_id, name, salary, dept_id)
- department(dept_id, dept_name)
CREATE VIEW and SELECT
Formula Applied:—Approach note: Give users access to the view instead of the base table to hide private columns.
Money transfer: move 1000 from account 1 to account 2 safely. If anything fails, nothing should change.
- account(acc_no, balance)
Transaction
Formula Applied:—Approach note: Atomicity means all steps happen together or none do.
Find all emails that appear more than once in the student table.
- student(roll_no, name, email)
List of duplicate emails with counts
Formula Applied:—Approach note: This is the standard "find duplicates" answer.
Find the 3rd highest distinct salary from employees.
- employees(emp_id, name, salary)
One salary value
Formula Applied:—Approach note: For Nth highest, use OFFSET N-1.
Real-world applications
Using SQL Views, Indexes and Practice in real projects
Banking transfers use transactions. Reports use views. Search boxes depend on indexes.
Common mistakes
❌ Myth: A view stores a separate copy of the data.
Why this is wrong: It looks and behaves like a table.
✅ Verified Truth: A normal view stores only the query. The data stays in the base tables and is read every time.
⚠️ Exam Tip: Only a materialized view stores results.
❌ Myth: More indexes always make the database faster.
Why this is wrong: Indexes speed up searches.
✅ Verified Truth: Every index uses space and slows INSERT, UPDATE and DELETE. Add indexes only for columns used often in WHERE, JOIN and ORDER BY.
⚠️ Exam Tip: Say "balance reads and writes".
❌ Myth: ROLLBACK can undo anything, even after COMMIT.
Why this is wrong: ROLLBACK sounds like a universal undo.
✅ Verified Truth: After COMMIT the changes are permanent. ROLLBACK only cancels uncommitted changes.
⚠️ Exam Tip: Check auto-commit mode before running risky commands.
Revision notes
A view is a saved query that works like a virtual table. An index makes searching faster. A transaction groups changes so they are saved together (COMMIT) or cancelled together (ROLLBACK). This chapter ends with popular interview queries.
High-Yield Quick Revision Points
- View = saved SELECT query. It stores no data. DROP VIEW does not delete table data.
- Views simplify queries and hide private columns.
- Index = fast lookup, like a book index. It speeds reads and slows writes a little.
- Index columns used in WHERE, JOIN and ORDER BY. Primary key and unique already have indexes.
- Transaction = group of statements. COMMIT saves. ROLLBACK cancels. SAVEPOINT marks a point.
- ACID: Atomicity, Consistency, Isolation, Durability.
- Duplicates: GROUP BY + HAVING COUNT(*) > 1.
- Nth highest salary: DISTINCT + ORDER BY DESC + LIMIT 1 OFFSET N-1.
Practice questions
What does a normal view store?
What is the main purpose of an index?
Which command cancels changes made in the current transaction?
Which query finds duplicate values in a column?
In ACID, the letter A stands for:
Which of these removes duplicates while combining two SELECT results?