SlideShare a Scribd company logo
1 of 27
COMMON TABLE
EXPRESSION
(CTE)
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.
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.
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.
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.
SUBQERIES
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.
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.
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.
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.
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.
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.
WINDOW FUNCTIONS
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.
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.
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.
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.
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.
SQL JOINS
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.
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
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.
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;
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;
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;
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;
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;

More Related Content

Similar to PPT of Common Table Expression (CTE), Window Functions, JOINS, SubQuery

Advanced Sql Training
Advanced Sql TrainingAdvanced Sql Training
Advanced Sql Trainingbixxman
 
SQLSERVERQUERIES.pptx
SQLSERVERQUERIES.pptxSQLSERVERQUERIES.pptx
SQLSERVERQUERIES.pptxssuser6bf2d1
 
DBMS and SQL(structured query language) .pptx
DBMS and SQL(structured query language) .pptxDBMS and SQL(structured query language) .pptx
DBMS and SQL(structured query language) .pptxjainendraKUMAR55
 
Database Architecture and Basic Concepts
Database Architecture and Basic ConceptsDatabase Architecture and Basic Concepts
Database Architecture and Basic ConceptsTony Wong
 
Unit-1 SQL fundamentals.docx SQL commands used to create table, insert values...
Unit-1 SQL fundamentals.docx SQL commands used to create table, insert values...Unit-1 SQL fundamentals.docx SQL commands used to create table, insert values...
Unit-1 SQL fundamentals.docx SQL commands used to create table, insert values...SakkaravarthiS1
 
Database COMPLETE
Database COMPLETEDatabase COMPLETE
Database COMPLETEAbrar ali
 
SQL – The Natural Language for Analysis - Oracle - Whitepaper - 2431343
SQL – The Natural Language for Analysis - Oracle - Whitepaper - 2431343SQL – The Natural Language for Analysis - Oracle - Whitepaper - 2431343
SQL – The Natural Language for Analysis - Oracle - Whitepaper - 2431343Edgar Alejandro Villegas
 
Assg2 b 19121033-converted
Assg2 b 19121033-convertedAssg2 b 19121033-converted
Assg2 b 19121033-convertedSUSHANTPHALKE2
 
SQL Server Learning Drive
SQL Server Learning Drive SQL Server Learning Drive
SQL Server Learning Drive TechandMate
 
Its about a sql topic for basic structured query language
Its about a sql topic for basic structured query languageIts about a sql topic for basic structured query language
Its about a sql topic for basic structured query languageIMsKanchanaI
 
Sql overview-1232931296681161-1
Sql overview-1232931296681161-1Sql overview-1232931296681161-1
Sql overview-1232931296681161-1sagaroceanic11
 
SQL Fundamentals
SQL FundamentalsSQL Fundamentals
SQL FundamentalsBrian Foote
 

Similar to PPT of Common Table Expression (CTE), Window Functions, JOINS, SubQuery (20)

Advanced Sql Training
Advanced Sql TrainingAdvanced Sql Training
Advanced Sql Training
 
SQLSERVERQUERIES.pptx
SQLSERVERQUERIES.pptxSQLSERVERQUERIES.pptx
SQLSERVERQUERIES.pptx
 
DBMS and SQL(structured query language) .pptx
DBMS and SQL(structured query language) .pptxDBMS and SQL(structured query language) .pptx
DBMS and SQL(structured query language) .pptx
 
Database Architecture and Basic Concepts
Database Architecture and Basic ConceptsDatabase Architecture and Basic Concepts
Database Architecture and Basic Concepts
 
MULTIPLE TABLES
MULTIPLE TABLES MULTIPLE TABLES
MULTIPLE TABLES
 
Query
QueryQuery
Query
 
Unit-1 SQL fundamentals.docx SQL commands used to create table, insert values...
Unit-1 SQL fundamentals.docx SQL commands used to create table, insert values...Unit-1 SQL fundamentals.docx SQL commands used to create table, insert values...
Unit-1 SQL fundamentals.docx SQL commands used to create table, insert values...
 
Sql commands
Sql commandsSql commands
Sql commands
 
Database COMPLETE
Database COMPLETEDatabase COMPLETE
Database COMPLETE
 
SQL – The Natural Language for Analysis - Oracle - Whitepaper - 2431343
SQL – The Natural Language for Analysis - Oracle - Whitepaper - 2431343SQL – The Natural Language for Analysis - Oracle - Whitepaper - 2431343
SQL – The Natural Language for Analysis - Oracle - Whitepaper - 2431343
 
Adbms
AdbmsAdbms
Adbms
 
Assg2 b 19121033-converted
Assg2 b 19121033-convertedAssg2 b 19121033-converted
Assg2 b 19121033-converted
 
SQL Server Learning Drive
SQL Server Learning Drive SQL Server Learning Drive
SQL Server Learning Drive
 
Its about a sql topic for basic structured query language
Its about a sql topic for basic structured query languageIts about a sql topic for basic structured query language
Its about a sql topic for basic structured query language
 
Sql overview-1232931296681161-1
Sql overview-1232931296681161-1Sql overview-1232931296681161-1
Sql overview-1232931296681161-1
 
Sql slid
Sql slidSql slid
Sql slid
 
Review of SQL
Review of SQLReview of SQL
Review of SQL
 
Oracle SQL Part 3
Oracle SQL Part 3Oracle SQL Part 3
Oracle SQL Part 3
 
SQL Fundamentals
SQL FundamentalsSQL Fundamentals
SQL Fundamentals
 
SQL
SQLSQL
SQL
 

Recently uploaded

Invezz.com - Grow your wealth with trading signals
Invezz.com - Grow your wealth with trading signalsInvezz.com - Grow your wealth with trading signals
Invezz.com - Grow your wealth with trading signalsInvezz1
 
Best VIP Call Girls Noida Sector 22 Call Me: 8448380779
Best VIP Call Girls Noida Sector 22 Call Me: 8448380779Best VIP Call Girls Noida Sector 22 Call Me: 8448380779
Best VIP Call Girls Noida Sector 22 Call Me: 8448380779Delhi Call girls
 
ALSO dropshipping via API with DroFx.pptx
ALSO dropshipping via API with DroFx.pptxALSO dropshipping via API with DroFx.pptx
ALSO dropshipping via API with DroFx.pptxolyaivanovalion
 
Junnasandra Call Girls: 🍓 7737669865 🍓 High Profile Model Escorts | Bangalore...
Junnasandra Call Girls: 🍓 7737669865 🍓 High Profile Model Escorts | Bangalore...Junnasandra Call Girls: 🍓 7737669865 🍓 High Profile Model Escorts | Bangalore...
Junnasandra Call Girls: 🍓 7737669865 🍓 High Profile Model Escorts | Bangalore...amitlee9823
 
VIP Call Girls Service Miyapur Hyderabad Call +91-8250192130
VIP Call Girls Service Miyapur Hyderabad Call +91-8250192130VIP Call Girls Service Miyapur Hyderabad Call +91-8250192130
VIP Call Girls Service Miyapur Hyderabad Call +91-8250192130Suhani Kapoor
 
CebaBaby dropshipping via API with DroFX.pptx
CebaBaby dropshipping via API with DroFX.pptxCebaBaby dropshipping via API with DroFX.pptx
CebaBaby dropshipping via API with DroFX.pptxolyaivanovalion
 
Carero dropshipping via API with DroFx.pptx
Carero dropshipping via API with DroFx.pptxCarero dropshipping via API with DroFx.pptx
Carero dropshipping via API with DroFx.pptxolyaivanovalion
 
{Pooja: 9892124323 } Call Girl in Mumbai | Jas Kaur Rate 4500 Free Hotel Del...
{Pooja:  9892124323 } Call Girl in Mumbai | Jas Kaur Rate 4500 Free Hotel Del...{Pooja:  9892124323 } Call Girl in Mumbai | Jas Kaur Rate 4500 Free Hotel Del...
{Pooja: 9892124323 } Call Girl in Mumbai | Jas Kaur Rate 4500 Free Hotel Del...Pooja Nehwal
 
Halmar dropshipping via API with DroFx
Halmar  dropshipping  via API with DroFxHalmar  dropshipping  via API with DroFx
Halmar dropshipping via API with DroFxolyaivanovalion
 
100-Concepts-of-AI by Anupama Kate .pptx
100-Concepts-of-AI by Anupama Kate .pptx100-Concepts-of-AI by Anupama Kate .pptx
100-Concepts-of-AI by Anupama Kate .pptxAnupama Kate
 
Schema on read is obsolete. Welcome metaprogramming..pdf
Schema on read is obsolete. Welcome metaprogramming..pdfSchema on read is obsolete. Welcome metaprogramming..pdf
Schema on read is obsolete. Welcome metaprogramming..pdfLars Albertsson
 
FESE Capital Markets Fact Sheet 2024 Q1.pdf
FESE Capital Markets Fact Sheet 2024 Q1.pdfFESE Capital Markets Fact Sheet 2024 Q1.pdf
FESE Capital Markets Fact Sheet 2024 Q1.pdfMarinCaroMartnezBerg
 
VidaXL dropshipping via API with DroFx.pptx
VidaXL dropshipping via API with DroFx.pptxVidaXL dropshipping via API with DroFx.pptx
VidaXL dropshipping via API with DroFx.pptxolyaivanovalion
 
Ravak dropshipping via API with DroFx.pptx
Ravak dropshipping via API with DroFx.pptxRavak dropshipping via API with DroFx.pptx
Ravak dropshipping via API with DroFx.pptxolyaivanovalion
 
Week-01-2.ppt BBB human Computer interaction
Week-01-2.ppt BBB human Computer interactionWeek-01-2.ppt BBB human Computer interaction
Week-01-2.ppt BBB human Computer interactionfulawalesam
 
Log Analysis using OSSEC sasoasasasas.pptx
Log Analysis using OSSEC sasoasasasas.pptxLog Analysis using OSSEC sasoasasasas.pptx
Log Analysis using OSSEC sasoasasasas.pptxJohnnyPlasten
 
Edukaciniai dropshipping via API with DroFx
Edukaciniai dropshipping via API with DroFxEdukaciniai dropshipping via API with DroFx
Edukaciniai dropshipping via API with DroFxolyaivanovalion
 
BabyOno dropshipping via API with DroFx.pptx
BabyOno dropshipping via API with DroFx.pptxBabyOno dropshipping via API with DroFx.pptx
BabyOno dropshipping via API with DroFx.pptxolyaivanovalion
 
Data-Analysis for Chicago Crime Data 2023
Data-Analysis for Chicago Crime Data  2023Data-Analysis for Chicago Crime Data  2023
Data-Analysis for Chicago Crime Data 2023ymrp368
 

Recently uploaded (20)

Invezz.com - Grow your wealth with trading signals
Invezz.com - Grow your wealth with trading signalsInvezz.com - Grow your wealth with trading signals
Invezz.com - Grow your wealth with trading signals
 
꧁❤ Aerocity Call Girls Service Aerocity Delhi ❤꧂ 9999965857 ☎️ Hard And Sexy ...
꧁❤ Aerocity Call Girls Service Aerocity Delhi ❤꧂ 9999965857 ☎️ Hard And Sexy ...꧁❤ Aerocity Call Girls Service Aerocity Delhi ❤꧂ 9999965857 ☎️ Hard And Sexy ...
꧁❤ Aerocity Call Girls Service Aerocity Delhi ❤꧂ 9999965857 ☎️ Hard And Sexy ...
 
Best VIP Call Girls Noida Sector 22 Call Me: 8448380779
Best VIP Call Girls Noida Sector 22 Call Me: 8448380779Best VIP Call Girls Noida Sector 22 Call Me: 8448380779
Best VIP Call Girls Noida Sector 22 Call Me: 8448380779
 
ALSO dropshipping via API with DroFx.pptx
ALSO dropshipping via API with DroFx.pptxALSO dropshipping via API with DroFx.pptx
ALSO dropshipping via API with DroFx.pptx
 
Junnasandra Call Girls: 🍓 7737669865 🍓 High Profile Model Escorts | Bangalore...
Junnasandra Call Girls: 🍓 7737669865 🍓 High Profile Model Escorts | Bangalore...Junnasandra Call Girls: 🍓 7737669865 🍓 High Profile Model Escorts | Bangalore...
Junnasandra Call Girls: 🍓 7737669865 🍓 High Profile Model Escorts | Bangalore...
 
VIP Call Girls Service Miyapur Hyderabad Call +91-8250192130
VIP Call Girls Service Miyapur Hyderabad Call +91-8250192130VIP Call Girls Service Miyapur Hyderabad Call +91-8250192130
VIP Call Girls Service Miyapur Hyderabad Call +91-8250192130
 
CebaBaby dropshipping via API with DroFX.pptx
CebaBaby dropshipping via API with DroFX.pptxCebaBaby dropshipping via API with DroFX.pptx
CebaBaby dropshipping via API with DroFX.pptx
 
Carero dropshipping via API with DroFx.pptx
Carero dropshipping via API with DroFx.pptxCarero dropshipping via API with DroFx.pptx
Carero dropshipping via API with DroFx.pptx
 
{Pooja: 9892124323 } Call Girl in Mumbai | Jas Kaur Rate 4500 Free Hotel Del...
{Pooja:  9892124323 } Call Girl in Mumbai | Jas Kaur Rate 4500 Free Hotel Del...{Pooja:  9892124323 } Call Girl in Mumbai | Jas Kaur Rate 4500 Free Hotel Del...
{Pooja: 9892124323 } Call Girl in Mumbai | Jas Kaur Rate 4500 Free Hotel Del...
 
Halmar dropshipping via API with DroFx
Halmar  dropshipping  via API with DroFxHalmar  dropshipping  via API with DroFx
Halmar dropshipping via API with DroFx
 
100-Concepts-of-AI by Anupama Kate .pptx
100-Concepts-of-AI by Anupama Kate .pptx100-Concepts-of-AI by Anupama Kate .pptx
100-Concepts-of-AI by Anupama Kate .pptx
 
Schema on read is obsolete. Welcome metaprogramming..pdf
Schema on read is obsolete. Welcome metaprogramming..pdfSchema on read is obsolete. Welcome metaprogramming..pdf
Schema on read is obsolete. Welcome metaprogramming..pdf
 
FESE Capital Markets Fact Sheet 2024 Q1.pdf
FESE Capital Markets Fact Sheet 2024 Q1.pdfFESE Capital Markets Fact Sheet 2024 Q1.pdf
FESE Capital Markets Fact Sheet 2024 Q1.pdf
 
VidaXL dropshipping via API with DroFx.pptx
VidaXL dropshipping via API with DroFx.pptxVidaXL dropshipping via API with DroFx.pptx
VidaXL dropshipping via API with DroFx.pptx
 
Ravak dropshipping via API with DroFx.pptx
Ravak dropshipping via API with DroFx.pptxRavak dropshipping via API with DroFx.pptx
Ravak dropshipping via API with DroFx.pptx
 
Week-01-2.ppt BBB human Computer interaction
Week-01-2.ppt BBB human Computer interactionWeek-01-2.ppt BBB human Computer interaction
Week-01-2.ppt BBB human Computer interaction
 
Log Analysis using OSSEC sasoasasasas.pptx
Log Analysis using OSSEC sasoasasasas.pptxLog Analysis using OSSEC sasoasasasas.pptx
Log Analysis using OSSEC sasoasasasas.pptx
 
Edukaciniai dropshipping via API with DroFx
Edukaciniai dropshipping via API with DroFxEdukaciniai dropshipping via API with DroFx
Edukaciniai dropshipping via API with DroFx
 
BabyOno dropshipping via API with DroFx.pptx
BabyOno dropshipping via API with DroFx.pptxBabyOno dropshipping via API with DroFx.pptx
BabyOno dropshipping via API with DroFx.pptx
 
Data-Analysis for Chicago Crime Data 2023
Data-Analysis for Chicago Crime Data  2023Data-Analysis for Chicago Crime Data  2023
Data-Analysis for Chicago Crime Data 2023
 

PPT of Common Table Expression (CTE), Window Functions, JOINS, SubQuery

  • 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;