Day 10 1729086189
Day 10 1729086189
𝐢𝐧𝐭𝐞𝐫𝐯𝐢𝐞𝐰 𝐬𝐞𝐫𝐢𝐞𝐬
Day 10: Advanced Advanced SQL scenarios like window
functions, CTEs, and handling performance issues.
Created By Devikrishna R
Window Functions
1. OVER() Clause
2. ROW_NUMBER()
3. RANK()
4. DENSE_RANK()
5. PARTITION BY
1.OVER() Clause
The OVER() clause is fundamental in SQL window functions.
It defines a window (or subset of rows) for each row in the result set.
This enables the calculation of aggregate values like totals or rankings without collapsing the rows like
traditional GROUP BY does.
•Syntax:
1. Indexing
Explanation: Indexes act like a roadmap that helps the database find data faster. Without an index, the database must scan the entire
table to locate the relevant rows.
2. Query Refactoring
Explanation: Complex queries can often be split into simpler, more manageable parts. This makes them easier to optimize and debug.
3. Avoid SELECT *
Explanation: Selecting all columns (SELECT *) can retrieve more data than necessary, slowing down the query. Specifying only the
required columns reduces the workload on the database.
4. Efficient Joins
Explanation: The way tables are joined can significantly impact performance, especially with large datasets. The order of joins and the
type of join used matter.
5. Use WHERE Instead of HAVING
Explanation: The “WHERE” clause filters rows before grouping them, while “HAVING” filters rows after grouping. Filtering early with
“WHERE” is more efficient.
8. Optimize Aggregations
Explanation: Aggregating data (SUM, COUNT, etc.) can be slow, especially on large tables. Indexing the columns used in aggregations
can speed up these operations.
9. Consider Query Execution Plans
Explanation: Execution plans show how the database intends to execute your query. Understanding this can help identify bottlenecks
like full table scans.
11. Caching
Explanation: Query caching can store the results of expensive queries, so they don’t have to be recalculated each time.
UNION ALL
-- Recursive member
SELECT column_list
FROM table
JOIN cte_name ON table.column = cte_name.column
)
SELECT * FROM cte_name;
------------------------------
Example: Organizational Hierarchy
Imagine a table employees where each employee has a manager_id referring to their manager
(or is NULL if they have no manager).
sql
WITH RECURSIVE EmployeeHierarchy AS ( -- Anchor member: Get top-level employees (those with no manager)
SELECT employee_id, employee_name, manager_id FROM employees
WHERE manager_id IS NULL UNION ALL -- Recursive member: Get employees reporting to those already found