SlideShare a Scribd company logo
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

PDF
DBMS Unit - 6 - Transaction Management
PPTX
SQL(DDL & DML)
PPTX
Technopreneurship
PPTX
Er model ppt
PDF
PowerBI Training
PPT
Co pa power point
PDF
Introduction to Data Analysis Course Notes.pdf
PPTX
SAP CO-PA (Controlling-Profitability Analysis)
DBMS Unit - 6 - Transaction Management
SQL(DDL & DML)
Technopreneurship
Er model ppt
PowerBI Training
Co pa power point
Introduction to Data Analysis Course Notes.pdf
SAP CO-PA (Controlling-Profitability Analysis)

What's hot (20)

PPT
SQL subquery
PDF
Working with JSON Data in PostgreSQL vs. MongoDB
PPT
Retrieving data using the sql select statement
PDF
Python Variable Types, List, Tuple, Dictionary
PPTX
Sql injection
PPTX
Introduction to triggers
PPTX
Sql subquery
PPTX
Searching
PPTX
Trigger in mysql
PPTX
PPTX
Stack and its Applications : Data Structures ADT
PPTX
Java Stack Data Structure.pptx
PPTX
Part3 Explain the Explain Plan
PPTX
Sql injections - with example
PDF
PL/SQL TRIGGERS
PPTX
WAF Bypass Techniques - Using HTTP Standard and Web Servers’ Behaviour
PDF
Integrity constraints in dbms
PPT
Sql Server Security
PPTX
Attacking thru HTTP Host header
SQL subquery
Working with JSON Data in PostgreSQL vs. MongoDB
Retrieving data using the sql select statement
Python Variable Types, List, Tuple, Dictionary
Sql injection
Introduction to triggers
Sql subquery
Searching
Trigger in mysql
Stack and its Applications : Data Structures ADT
Java Stack Data Structure.pptx
Part3 Explain the Explain Plan
Sql injections - with example
PL/SQL TRIGGERS
WAF Bypass Techniques - Using HTTP Standard and Web Servers’ Behaviour
Integrity constraints in dbms
Sql Server Security
Attacking thru HTTP Host header
Ad

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

PPTX
SQL Query
PDF
1.Types of SQL Commands for mba students
PPT
Ms sql server ii
PPTX
Data Manipulation Language.pptx
PDF
SQL -Beginner To Intermediate Level.pdf
PPTX
2. DBMS Experiment - Lab 2 Made in SQL Used
PPTX
DATABASE MANAGMENT SYSTEM (DBMS) AND SQL
PDF
Interview Questions.pdf
PPTX
STRUCTURE OF SQL QUERIES
PPT
Advanced Sql Training
PPTX
SQLSERVERQUERIES.pptx
PPTX
DBMS and SQL(structured query language) .pptx
PDF
Database Architecture and Basic Concepts
PPTX
MULTIPLE TABLES
DOCX
DOCX
Unit-1 SQL fundamentals.docx SQL commands used to create table, insert values...
PPTX
SQL DATABASE MANAGAEMENT SYSTEM FOR CLASS 12 CBSE
PPTX
Sql commands
PPTX
Database COMPLETE
PDF
SQL – The Natural Language for Analysis - Oracle - Whitepaper - 2431343
SQL Query
1.Types of SQL Commands for mba students
Ms sql server ii
Data Manipulation Language.pptx
SQL -Beginner To Intermediate Level.pdf
2. DBMS Experiment - Lab 2 Made in SQL Used
DATABASE MANAGMENT SYSTEM (DBMS) AND SQL
Interview Questions.pdf
STRUCTURE OF SQL QUERIES
Advanced Sql Training
SQLSERVERQUERIES.pptx
DBMS and SQL(structured query language) .pptx
Database Architecture and Basic Concepts
MULTIPLE TABLES
Unit-1 SQL fundamentals.docx SQL commands used to create table, insert values...
SQL DATABASE MANAGAEMENT SYSTEM FOR CLASS 12 CBSE
Sql commands
Database COMPLETE
SQL – The Natural Language for Analysis - Oracle - Whitepaper - 2431343
Ad

Recently uploaded (20)

PPTX
oil_refinery_comprehensive_20250804084928 (1).pptx
PPTX
Introduction to Firewall Analytics - Interfirewall and Transfirewall.pptx
PPT
Quality review (1)_presentation of this 21
PPTX
Introduction-to-Cloud-ComputingFinal.pptx
PDF
Clinical guidelines as a resource for EBP(1).pdf
PPTX
STUDY DESIGN details- Lt Col Maksud (21).pptx
PPTX
MODULE 8 - DISASTER risk PREPAREDNESS.pptx
PDF
Galatica Smart Energy Infrastructure Startup Pitch Deck
PPT
Chapter 3 METAL JOINING.pptnnnnnnnnnnnnn
PPTX
Introduction to Basics of Ethical Hacking and Penetration Testing -Unit No. 1...
PPTX
Computer network topology notes for revision
PPTX
CEE 2 REPORT G7.pptxbdbshjdgsgjgsjfiuhsd
PPT
Chapter 2 METAL FORMINGhhhhhhhjjjjmmmmmmmmm
PPTX
The THESIS FINAL-DEFENSE-PRESENTATION.pptx
PDF
Recruitment and Placement PPT.pdfbjfibjdfbjfobj
PPTX
IBA_Chapter_11_Slides_Final_Accessible.pptx
PPTX
ALIMENTARY AND BILIARY CONDITIONS 3-1.pptx
PDF
Foundation of Data Science unit number two notes
PPT
Reliability_Chapter_ presentation 1221.5784
PPTX
mbdjdhjjodule 5-1 rhfhhfjtjjhafbrhfnfbbfnb
oil_refinery_comprehensive_20250804084928 (1).pptx
Introduction to Firewall Analytics - Interfirewall and Transfirewall.pptx
Quality review (1)_presentation of this 21
Introduction-to-Cloud-ComputingFinal.pptx
Clinical guidelines as a resource for EBP(1).pdf
STUDY DESIGN details- Lt Col Maksud (21).pptx
MODULE 8 - DISASTER risk PREPAREDNESS.pptx
Galatica Smart Energy Infrastructure Startup Pitch Deck
Chapter 3 METAL JOINING.pptnnnnnnnnnnnnn
Introduction to Basics of Ethical Hacking and Penetration Testing -Unit No. 1...
Computer network topology notes for revision
CEE 2 REPORT G7.pptxbdbshjdgsgjgsjfiuhsd
Chapter 2 METAL FORMINGhhhhhhhjjjjmmmmmmmmm
The THESIS FINAL-DEFENSE-PRESENTATION.pptx
Recruitment and Placement PPT.pdfbjfibjdfbjfobj
IBA_Chapter_11_Slides_Final_Accessible.pptx
ALIMENTARY AND BILIARY CONDITIONS 3-1.pptx
Foundation of Data Science unit number two notes
Reliability_Chapter_ presentation 1221.5784
mbdjdhjjodule 5-1 rhfhhfjtjjhafbrhfnfbbfnb

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;