2. Introduction to Common Table Expressions
(CTEs)
A CTE is a temporary result set that is defined within the execution scope of a single SQL statement,
such as SELECT, INSERT, UPDATE, or DELETE.
Purpose:
The primary purpose of a CTE is to simplify complex SQL queries by breaking them down into simpler,
more readable components. This is particularly useful in cases where a query involves multiple steps
or stages and can benefit from being organized into more manageable parts.
Scope:
CTEs are not stored as objects in the database; they exist only during the execution of the query in
which they are defined. This temporary nature means they are created on the fly when the query runs
and are disposed of once the query completes.
They can be recursive, allowing them to reference themselves, which is especially powerful for
hierarchical or tree-structured data queries, such as organizational charts, category trees, or any form
of hierarchical data representation.
3. Advantages of Using CTEs
Readability: Makes complex queries easier to read and
maintain.
Reusability: Allows the reuse of the same subset of data in
multiple places within a query.
Recursion: Facilitates recursive queries, useful for
hierarchical data exploration like organizational charts or
folder structures.
4. Basic Syntax of CTEs
WITH CTE_Name AS (
SELECT column1, column2, ...
FROM table_name
WHERE condition
)
SELECT * FROM CTE_Name;
Explanation: Begins with the WITH clause, followed by the CTE
name, the AS keyword, and the CTE body inside parentheses. The
CTE is then utilized in a SELECT statement.
5. Simple CTE Example
Scenario: Selecting the top 10 most expensive products.
Code:
WITH TopProducts AS (
SELECT ProductName, Price
FROM Products
ORDER BY Price DESC
LIMIT 10
)
SELECT * FROM TopProducts;
Explanation: The CTE TopProducts selects the top 10 most expensive products from
the Products table. The main SELECT query then retrieves this result.
7. Introduction to Subqueries
Definition: A subquery, also known as a nested query, is a query
within another SQL query and embedded within the WHERE clause.
- Purpose: Subqueries are used to return data that will be used in
the main query as a condition to further restrict the data to be
retrieved.
- Characteristics: Can return individual values or a list and can be
used in SELECT, INSERT, UPDATE, and DELETE statements.
8. Types of Subqueries
Single-Row Subquery: Returns zero or one row.
Multiple-Row Subquery: Returns one or more rows.
Correlated Subquery: References one or more columns in
the outer SQL statement.
Scalar Subquery: Returns a single value and can be used
wherever a single value is acceptable.
9. Single-Row Subquery Example
Objective: To find employees who earn more than the average salary.
SQL Query:
SELECT employee_name
FROM employees
WHERE salary > (SELECT AVG(salary) FROM employees);
Explanation: The subquery calculates the average salary of all employees. The main query
then selects employees who earn more than this average salary.
10. Multiple-Row Subquery
Objective: To find employees who work in the same department as 'John Doe’.
SQL Query:
SELECT employee_name
FROM employees
WHERE department_id IN (SELECT department_id FROM employees WHERE
employee_name = 'John Doe');
Explanation: The subquery finds the department ID of 'John Doe'. The main query
selects all employees working in this department.
11. Correlated Subquery
Objective: To find employees whose salary is above the average salary in their department.
SQL Query:
SELECT employee_name, salary
FROM employees e1
WHERE salary > (SELECT AVG(salary) FROM employees e2 WHERE e1.department_id =
e2.department_id);
Explanation: The subquery calculates the average salary for each department. The
main query compares each employee's salary against this average.
12. Scalar Subquery
Objective: To display the total number of employees alongside each employee's details.
SQL Query:
SELECT employee_name, (SELECT COUNT(*) FROM employees) AS total_employees
FROM employees;
Explanation: The scalar subquery returns the total number of employees, which is
displayed alongside each employee's name.
14. Introduction to Window
Functions
Definition of window functions in SQL. Explanation of how they
allow us to perform calculations across a set of rows that are related
to the current row in a way that is more efficient and cleaner than
traditional SQL syntax.
15. The PARTITION BY Clause
Content: Detailed explanation of the `PARTITION BY` clause, which is used to divide
the result set into partitions. The window function is applied to each partition
independently.
Example: Showing a basic example of how `PARTITION BY` can be used
to calculate the total sales per department.
16. The ORDER BY Clause
Content: Overview of how the `ORDER BY` clause is used within window functions
to determine the order of rows in each partition.
Example: Demonstrating how to use `ORDER BY` to calculate running
totals or cumulative sums.
17. ROWS and RANGE Specifiers
Content: Explanation of the `ROWS` and `RANGE` specifiers, which define the set
of rows used to perform the calculations for the current row.
Example: Contrast between `ROWS` and `RANGE` with practical use
cases.
18. Common Window Functions
Content: Introduction to common window functions like `ROW_NUMBER()`,
`RANK()`, `DENSE_RANK()`, `SUM()`, `AVG()`, and `LEAD()`, `LAG()`.
Example: Simple examples showing how each function can be used.
20. Understanding SQL Joins
Content: SQL Joins are a powerful feature of SQL that allow you
to combine rows from two or more tables based on a related
column between them. They are essential for querying data from
multiple tables to produce a result that includes information
from each table.
21. Types Of JOINS
INNER JOIN
LEFT JOIN (or LEFT OUTER JOIN)
RIGHT JOIN (or RIGHT OUTER JOIN)
FULL JOIN (or FULL OUTER JOIN)
CROSS JOIN
22. EXAMPLES OF JOINS
Imagine we have two tables, `Employees` and `Departments`.
`Employees` contains employee names and their department IDs, while
`Departments` contains department IDs and names.
To find the department name for each employee, we would use an INNER JOIN on
the department ID columns of the two tables.
23. INNER JOIN
Content: The INNER JOIN keyword selects records that have matching values in both
tables. It is the most common type of join.
Syntax:
SELECT columns
FROM table1
INNER JOIN table2
ON table1.common_column = table2.common_column;
Example:
To find the department name for each employee:
SELECT Employees.EmployeeName, Departments.DepartmentName
FROM Employees
INNER JOIN Departments ON Employees.DepartmentID = Departments.DepartmentID;
24. LEFT JOIN
Content: The LEFT JOIN (or LEFT OUTER JOIN) returns all records from the left table
(table1), and the matched records from the right table (table2). The result is NULL
from the right side if there is no match.
Syntax:
SELECT columns
FROM table1
LEFT JOIN table2
ON table1.common_column = table2.common_column;
Example:
To list all employees and their department names, with employees who do not
belong to a department:
SELECT Employees.EmployeeName, Departments.DepartmentName
FROM Employees
LEFT JOIN Departments ON Employees.DepartmentID = Departments.DepartmentID;
25. RIGHT JOIN
Content: The RIGHT JOIN (or RIGHT OUTER JOIN) returns all records from the right
table (table2), and the matched records from the left table (table1). The result is NULL
from the left side if there is no match.
Syntax:
SELECT columns
FROM table1
RIGHT JOIN table2
ON table1.common_column = table2.common_column;
Example:
To list all departments and any employees in them:
SELECT Employees.EmployeeName, Departments.DepartmentName
FROM Employees
RIGHT JOIN Departments ON Employees.DepartmentID = Departments.DepartmentID;
26. FULL JOIN
Content: The FULL JOIN (or FULL OUTER JOIN) returns all records when there is a match in
either left (table1) or right (table2) table records. It combines the result of both LEFT JOIN and
RIGHT JOIN.
Syntax:
SELECT columns
FROM table1
FULL JOIN table2
ON table1.common_column = table2.common_column;
Example:
To list all employees and all departments, with any possible association:
SELECT Employees.EmployeeName, Departments.DepartmentName
FROM Employees
FULL JOIN Departments ON Employees.DepartmentID = Departments.DepartmentID;
27. CROSS JOIN
Content: The CROSS JOIN returns a Cartesian product of the two tables, i.e., it joins every
row of the first table with every row of the second table.
Syntax:
SELECT columns
FROM table1
CROSS JOIN table2;
Example:
To create a combination of every row from `TableA` with every row from `TableB`:
SELECT TableA.A, TableB.B
FROM TableA
CROSS JOIN TableB;