SUBQUERY
Prof.manoj kumar padhi
SUBQUERY
WHY USE SUBQUERIES
Subqueries help when you need to:
SYNTAX
SELECT column_name
FROM table_name
WHERE column_name OPERATOR
(SELECT column_name
FROM table_name
WHERE condition);
SUBQUERIES USING WHERE CLAUSE
SELECT student_name
FROM students
WHERE department_id = (SELECT department_id
FROM department
WHERE department_name='CSE');
SUBQUERY USING FROM CLAUSE
SELECT dept_id, AVG(marks)
FROM (SELECT department_id AS dept_id, marks FROM students) AS temp
GROUP BY dept_id;
TYPES OF SUBQUERIES�
1. Single-Row Subquery
SELECT CustomerName, City
FROM Customer
WHERE ProductID = (
SELECT ProductID
FROM Product
ORDER BY Price DESC
LIMIT 1
);
2. Multi-Row Subquery
Example:
SELECT ProductName, Price
FROM Product
WHERE ProductID IN (
SELECT ProductID
FROM Customer
WHERE City = 'Delhi'
);
3. Subquery with Aggregation
SELECT CustomerName, Email FROM Customer
WHERE ProductID IN (
SELECT ProductID FROM Product
WHERE Price > (
SELECT AVG(Price) FROM Product
)
);
INDEXING
Without Index | With Index |
MySQL checks every row | MySQL directly jumps to matching row |
Slow searching | Faster searching |
Table is like a messy heap | Table is like a well-organized catalog |
KEY BENEFITS OF INDEXING
✔ Faster searching�✔ Better performance during WHERE, JOIN, ORDER BY, GROUP BY�✔ Useful for columns frequently searched
HOW TO CREATE INDEX
CREATE INDEX index_name
ON table_name(column_name);
TYPES OF INDEXING METHODS
CLUSTERED INDEXING
PRIMARY INDEXING
NON-CLUSTERED OR SECONDARY INDEXING
CLUSTERED VS NON-CLUSTERED INDEX
Feature | Clustered Index | Non-Clustered Index |
Data storage | Physically sorted | Stored separately |
No. of indexes | Only 1 per table | Many allowed |
Speed | Faster for range queries | Slightly slower |
Structure | Data + index together | Index + row pointers |
Typical creation | On Primary Key | On frequently searched columns |
VIEWS
✔ Data security (hide confidential columns)�✔ Simplify complex queries�✔ Easy reusability�✔ Shows updated data automatically
EXAMPLE
CREATE VIEW CustomerProductView AS
SELECT
Customer.CustomerID,
Customer.CustomerName,
Product.ProductName,
Product.Price
FROM
Customer
JOIN
Product ON Customer.ProductID = Product.ProductID;