Advanced_SQL_Training_Phase2 (1)
Advanced_SQL_Training_Phase2 (1)
Table of Contents
1. Subqueries
- Definition
- Types
- Practical Examples
2. Correlated Subqueries
- Definition
- Practical Examples
3. Recursive Queries
- Definition
- Practical Examples
4. Indexing
- Types of Indexes
- Best Practices
- Practical Examples
5. Query Execution Plans
- Understanding Execution Plans
- Tools to Analyze Plans
6. Performance Tuning
- Tips and Best Practices
- Common Pitfalls
7. Partial Query Selection
- Definition
- Practical Examples
1. Subqueries
Definition
A subquery is a query nested inside another query. It provides results to the outer query
and is often used in WHERE, FROM, or SELECT clauses.
Types
1. Single-row Subqueries: Returns a single row and is used with operators like =, <, >.
2. Multi-row Subqueries: Returns multiple rows and is used with operators like IN, ANY,
ALL.
3. Scalar Subqueries: Returns a single value and is used in the SELECT clause.
Example
Find employees earning more than the average salary.
2. Correlated Subqueries
Definition
A correlated subquery depends on the outer query for its values. It is executed once for
every row processed by the outer query.
Example
Find customers who have placed orders exceeding their average order amount.
3. Recursive Queries
Definition
Recursive queries are used to query hierarchical data, such as organizational structures or
category trees. It uses a Common Table Expression (CTE) with recursive logic.
Example
Fetch all employees reporting (directly or indirectly) to a specific manager.
4. Indexing
Types of Indexes
1. Clustered Index: Sorts the data in the table based on key values.
2. Non-Clustered Index: Creates a separate structure for quick lookups.
3. Composite Index: Combines multiple columns into a single index.
4. Unique Index: Ensures all values in a column are unique.
Best Practices
- Use indexes on columns frequently used in WHERE, JOIN, and GROUP BY.
- Avoid indexing small tables.
- Limit the number of indexes on write-heavy tables to minimize overhead.
Example
Create an index to optimize searches by customer_id.
Example
Analyze the execution plan for a query.
EXPLAIN SELECT * FROM Orders WHERE amount > 1000;
6. Performance Tuning
Common Pitfalls
Definition
Partial query selection retrieves a subset of data based on specific conditions, often used
with LIMIT, OFFSET, or window functions.
Example
Fetch the top 5 highest-paying customers.