SlideShare a Scribd company logo
F0004
* Property of STI
Page 1 of 11
Common Table Expressions
What is Common Table
Expressions?
 Common table expressions (CTE)
are temporary result set that are
known only within the scope of a
single SELECT, INSERT, UPDATE,
DELETE or CREATE VIEW statement.
 Common table expressions are
generally useful in a query that
involves multiple aggregate
functions.
F0004
* Property of STI
Page 2 of 11
Common Table Expressions
Using Common Table
Expressions
 The common table expressions are
defined using the WITH clause.
 Example 1:
WITH CountEmployees(dept_id, n)
AS
( SELECT dept_id, count(*) AS n
FROM employee GROUP BY dept_id )
SELECT dept_id, n
FROM CountEmployees
WHERE n = ( SELECT max(n)
FROM CountEmployees )
F0004
* Property of STI
Page 3 of 11
Common Table Expressions
Using Common Table
Expressions
 Example 2:
WITH CountEmployees(dept_id, n)
AS
( SELECT dept_id, count(*) AS n
FROM employee GROUP BY dept_id )
SELECT a.dept_id, a.n,
b.dept_id, b.n
FROM CountEmployees AS a JOIN
CountEmployees AS b
ON a.n = b.n AND a.dept_id <
b.dept_id
F0004
* Property of STI
Page 4 of 11
Common Table Expressions
Using Common Table
Expressions
 Example 3:
WITH
CountEmployees(dept_id, n) AS
( SELECT dept_id, count(*) AS n
FROM employee GROUP BY
dept_id ),
DeptPayroll( dept_id, amt ) AS
( SELECT dept_id, sum(salary)
AS amt
FROM employee GROUP BY dept_id )
SELECT count.dept_id, count.n,
pay.amt
FROM CountEmployees AS count
JOIN DeptPayroll AS pay
ON count.dept_id = pay.dept_id
WHERE count.n = ( SELECT max(n)
FROM CountEmployees )
OR pay.amt = ( SELECT min(amt)
FROM DeptPayroll )
F0004
* Property of STI
Page 5 of 11
Common Table Expressions
Exercise
 Assume that you need to
determine which class has the
most number of students. The
student table lists all the students
and specifies in which class each
belong. Using common table
expressions, find the following:
1. Extract the class with the most
students. Extract the class with
the fewest students.
2. List the class that has the highest
GPA of students.
F0004
* Property of STI
Page 6 of 11
Common Table Expressions
Applications of Common
Table Expressions
 Common table expressions are
useful whenever multiple levels of
aggregation must occur within a
single query.
 Views within a procedure that
must contain a reference to a
program variable.
 Queries that use temporary result
set to store a set of values.
F0004
* Property of STI
Page 7 of 11
Common Table Expressions
What is Recursive Common
Table Expressions
 Recursive common table
expressions allow you to query
tables that represent hierarchical
information.
 A recursive common table
expression is composed of an initial
subquery or seed and a recursive
subquery.
F0004
* Property of STI
Page 8 of 11
Common Table Expressions
Example
WITH RECURSIVE
manager ( emp_id, manager_id,
emp_fname, emp_lname, mgmt_level )
AS
( ( SELECT emp_id, manager_id, --
initial subquery
emp_fname, emp_lname, 0
FROM employee AS e
WHERE manager_id = emp_id )
UNION ALL
( SELECT e.emp_id, e.manager_id, -
- recursive subquery
e.emp_fname, e.emp_lname,
m.mgmt_level + 1
FROM employee AS e JOIN manager AS
m
ON e.manager_id = m.emp_id
AND e.manager_id <> e.emp_id
AND m.mgmt_level < 20 ) )
SELECT * FROM manager
ORDER BY mgmt_level, emp_lname,
emp_fname
F0004
* Property of STI
Page 9 of 11
Common Table Expressions
Restrictions on Recursive
Common Table Expression
 Recursive common table
expressions cannot be mutually
recursive.
 The only set operator permitted
between the initial subquery and
the recursive subquery is UNION
ALL.
 Within the definition of a recursive
subquery, a self-reference to the
recursive table expression can
appear only within the FROM
clause of the recursive subquery.
F0004
* Property of STI
Page 10 of 11
Common Table Expressions
Restrictions on Recursive
Common Table Expression
 The recursive subquery cannot
contain DISTINCT, or a GROUP BY
or an ORDER BY clause.
 The recursive subquery can not
make use of any aggregate
function.
 To prevent runaway recursive
queries, an error is generated if
the number of levels of recursion
exceeds the current setting of the
MAX_RECURSIVE_ITERATIONS
option.
F0004
* Property of STI
Page 11 of 11
Common Table Expressions
Exercise
 Using the recursive common table
expression, write a query that
displays the Fibonacci sequence.
TIP: The Fibonacci sequence is the sequence in
which each number is the sum of the two
preceding numbers such as 1, 1, 2, 3, 5, 8, 13,
21, 34, 55, 89, 144, 233, 377, 610, 987, 1597,
2584, 4181, ... (each number is the sum of
the previous two). The Fibonacci sequence,
generated by the rule f1 = f2 = 1 , fn+1 = fn +
fn-1, is well known in many different areas of
mathematics and science.

More Related Content

PPT
Common table expressions
PDF
04 quiz 1 answer key
PDF
7. Using Sub Queries
PPT
Dervy bis-155-week-2-quiz-new
DOCX
Clauses in sql server
PDF
Cis 336 final exam 2
PPT
SQL- Introduction to MySQL
PDF
Cis 336 final exam 2
Common table expressions
04 quiz 1 answer key
7. Using Sub Queries
Dervy bis-155-week-2-quiz-new
Clauses in sql server
Cis 336 final exam 2
SQL- Introduction to MySQL
Cis 336 final exam 2

What's hot (17)

PDF
Excel functions formulas
PDF
Sql subquery
PDF
CIS 336 Final Exam 2 (Devry)
DOCX
PDF
CIS 336 Final Exam 2 (Devry)s
PPT
Constraints In Sql
PPT
PPTX
Basic SQL Command
PDF
CIS 336 Final Exam 2 (Devry)p
PPTX
Mysql
PDF
On if,countif,countifs,sumif,countifs,lookup,v lookup,index,match
PPTX
Discriminant Analysis
PPTX
Ms excel 2003 intermediate
PDF
Sql integrity constraints
PPT
SQL Introduction to displaying data from multiple tables
Excel functions formulas
Sql subquery
CIS 336 Final Exam 2 (Devry)
CIS 336 Final Exam 2 (Devry)s
Constraints In Sql
Basic SQL Command
CIS 336 Final Exam 2 (Devry)p
Mysql
On if,countif,countifs,sumif,countifs,lookup,v lookup,index,match
Discriminant Analysis
Ms excel 2003 intermediate
Sql integrity constraints
SQL Introduction to displaying data from multiple tables
Ad

Viewers also liked (15)

PDF
03 laboratory exercise 1
PDF
04 sample resume 1
PDF
09 ohp slides 1
PDF
07 ohp slides 1
PDF
Strap Marketing Deck 2015
PDF
6. anexo-normas-apa-1
PDF
06 ohp slides 1
DOCX
CV - updated
PDF
Database Security Handout
PDF
01 laboratory exercise 1 - DESIGN A SIMPLE DATABASE APPLICATION
PPTX
Relevancy Wins. Everything Else is TL;DR.
PPT
Query processing and data analysis
PPT
Php forms
PDF
05 ohp slides 1
PPSX
07 lcd slides 1 - DEADLOCKS POWERPOINT
03 laboratory exercise 1
04 sample resume 1
09 ohp slides 1
07 ohp slides 1
Strap Marketing Deck 2015
6. anexo-normas-apa-1
06 ohp slides 1
CV - updated
Database Security Handout
01 laboratory exercise 1 - DESIGN A SIMPLE DATABASE APPLICATION
Relevancy Wins. Everything Else is TL;DR.
Query processing and data analysis
Php forms
05 ohp slides 1
07 lcd slides 1 - DEADLOCKS POWERPOINT
Ad

Similar to 03 ohp slides 1 (20)

PPTX
Case 9 and 10. SQL For Data Analysis 4.pptx
PPTX
SUBQUERIES.pptx
PPS
Sql xp 04
PPT
PPT
Modern Database Management chapetr 8 Advance SQL.ppt
PPT
Frequently asked questions in c
PPT
Frequently asked questions in c
PDF
Programming in c by pkv
PPT
IBM Informix Database SQL Set operators and ANSI Hash Join
PPS
Ds 3
PPT
The Database Environment Chapter 8
PDF
Chapter9 more on database and sql
PDF
Introduction to computer programming (C)-CSC1205_Lec5_Flow control
PDF
Database Architecture and Basic Concepts
PPT
e computer notes - Advanced subqueries
PPTX
sqyvvzdcfzZdfadfadafadfafafaZfdaBNsV1K.pptx
PPTX
DOC
CIS 336 Focus Dreams/newtonhelp.com
DOC
CIS 336 Imagine Your Future/newtonhelp.com   
PDF
CIS 336 Life of the Mind/newtonhelp.com   
Case 9 and 10. SQL For Data Analysis 4.pptx
SUBQUERIES.pptx
Sql xp 04
Modern Database Management chapetr 8 Advance SQL.ppt
Frequently asked questions in c
Frequently asked questions in c
Programming in c by pkv
IBM Informix Database SQL Set operators and ANSI Hash Join
Ds 3
The Database Environment Chapter 8
Chapter9 more on database and sql
Introduction to computer programming (C)-CSC1205_Lec5_Flow control
Database Architecture and Basic Concepts
e computer notes - Advanced subqueries
sqyvvzdcfzZdfadfadafadfafafaZfdaBNsV1K.pptx
CIS 336 Focus Dreams/newtonhelp.com
CIS 336 Imagine Your Future/newtonhelp.com   
CIS 336 Life of the Mind/newtonhelp.com   

More from Anne Lee (20)

PDF
Week 17 slides 1 7 multidimensional, parallel, and distributed database
PDF
Data mining
PDF
Data warehousing
PDF
Database backup and recovery
PDF
Database monitoring and performance management
PDF
transportation and assignment models
PDF
Database Security Slide Handout
PDF
Database Security - IG
PDF
03 laboratory exercise 1 - WORKING WITH CTE
PDF
02 laboratory exercise 1 - RETRIEVING DATA FROM SEVERAL TABLES
DOCX
Indexes - INSTRUCTOR'S GUIDE
PDF
07 ohp slides 1 - INDEXES
PDF
07 ohp slide handout 1 - INDEXES
PDF
Wk 16 ses 43 45 makrong kasanayan sa pagsusulat
PDF
Wk 15 ses 40 42 makrong kasanayan sa pagbabasa
PDF
Wk 13 ses 35 37 makrong kasanayan sa pagsasalita
PDF
Wk 12 ses 32 34 makrong kasanayan sa pakikinig
PDF
Wk 11 ses 29 31 konseptong pangkomunikasyon - FILIPINO 1
PPSX
06 lcd slides 1 - PROCESS SYNCHRONIZATION POWERPOINT
PPSX
05 lcd slides 1 - CPU SCHEDULING (Powerpoint)
Week 17 slides 1 7 multidimensional, parallel, and distributed database
Data mining
Data warehousing
Database backup and recovery
Database monitoring and performance management
transportation and assignment models
Database Security Slide Handout
Database Security - IG
03 laboratory exercise 1 - WORKING WITH CTE
02 laboratory exercise 1 - RETRIEVING DATA FROM SEVERAL TABLES
Indexes - INSTRUCTOR'S GUIDE
07 ohp slides 1 - INDEXES
07 ohp slide handout 1 - INDEXES
Wk 16 ses 43 45 makrong kasanayan sa pagsusulat
Wk 15 ses 40 42 makrong kasanayan sa pagbabasa
Wk 13 ses 35 37 makrong kasanayan sa pagsasalita
Wk 12 ses 32 34 makrong kasanayan sa pakikinig
Wk 11 ses 29 31 konseptong pangkomunikasyon - FILIPINO 1
06 lcd slides 1 - PROCESS SYNCHRONIZATION POWERPOINT
05 lcd slides 1 - CPU SCHEDULING (Powerpoint)

Recently uploaded (20)

PDF
Design an Analysis of Algorithms I-SECS-1021-03
PDF
Wondershare Filmora 15 Crack With Activation Key [2025
PDF
Cost to Outsource Software Development in 2025
PDF
Odoo Companies in India – Driving Business Transformation.pdf
PDF
AI-Powered Threat Modeling: The Future of Cybersecurity by Arun Kumar Elengov...
PDF
Salesforce Agentforce AI Implementation.pdf
PDF
CapCut Video Editor 6.8.1 Crack for PC Latest Download (Fully Activated) 2025
PDF
Navsoft: AI-Powered Business Solutions & Custom Software Development
PDF
Digital Systems & Binary Numbers (comprehensive )
PDF
Autodesk AutoCAD Crack Free Download 2025
PDF
Product Update: Alluxio AI 3.7 Now with Sub-Millisecond Latency
PPTX
Computer Software and OS of computer science of grade 11.pptx
PDF
EN-Survey-Report-SAP-LeanIX-EA-Insights-2025.pdf
PDF
Adobe Illustrator 28.6 Crack My Vision of Vector Design
PPTX
WiFi Honeypot Detecscfddssdffsedfseztor.pptx
PDF
wealthsignaloriginal-com-DS-text-... (1).pdf
PDF
How to Make Money in the Metaverse_ Top Strategies for Beginners.pdf
PDF
iTop VPN 6.5.0 Crack + License Key 2025 (Premium Version)
PDF
CCleaner Pro 6.38.11537 Crack Final Latest Version 2025
PDF
Tally Prime Crack Download New Version 5.1 [2025] (License Key Free
Design an Analysis of Algorithms I-SECS-1021-03
Wondershare Filmora 15 Crack With Activation Key [2025
Cost to Outsource Software Development in 2025
Odoo Companies in India – Driving Business Transformation.pdf
AI-Powered Threat Modeling: The Future of Cybersecurity by Arun Kumar Elengov...
Salesforce Agentforce AI Implementation.pdf
CapCut Video Editor 6.8.1 Crack for PC Latest Download (Fully Activated) 2025
Navsoft: AI-Powered Business Solutions & Custom Software Development
Digital Systems & Binary Numbers (comprehensive )
Autodesk AutoCAD Crack Free Download 2025
Product Update: Alluxio AI 3.7 Now with Sub-Millisecond Latency
Computer Software and OS of computer science of grade 11.pptx
EN-Survey-Report-SAP-LeanIX-EA-Insights-2025.pdf
Adobe Illustrator 28.6 Crack My Vision of Vector Design
WiFi Honeypot Detecscfddssdffsedfseztor.pptx
wealthsignaloriginal-com-DS-text-... (1).pdf
How to Make Money in the Metaverse_ Top Strategies for Beginners.pdf
iTop VPN 6.5.0 Crack + License Key 2025 (Premium Version)
CCleaner Pro 6.38.11537 Crack Final Latest Version 2025
Tally Prime Crack Download New Version 5.1 [2025] (License Key Free

03 ohp slides 1

  • 1. F0004 * Property of STI Page 1 of 11 Common Table Expressions What is Common Table Expressions?  Common table expressions (CTE) are temporary result set that are known only within the scope of a single SELECT, INSERT, UPDATE, DELETE or CREATE VIEW statement.  Common table expressions are generally useful in a query that involves multiple aggregate functions.
  • 2. F0004 * Property of STI Page 2 of 11 Common Table Expressions Using Common Table Expressions  The common table expressions are defined using the WITH clause.  Example 1: WITH CountEmployees(dept_id, n) AS ( SELECT dept_id, count(*) AS n FROM employee GROUP BY dept_id ) SELECT dept_id, n FROM CountEmployees WHERE n = ( SELECT max(n) FROM CountEmployees )
  • 3. F0004 * Property of STI Page 3 of 11 Common Table Expressions Using Common Table Expressions  Example 2: WITH CountEmployees(dept_id, n) AS ( SELECT dept_id, count(*) AS n FROM employee GROUP BY dept_id ) SELECT a.dept_id, a.n, b.dept_id, b.n FROM CountEmployees AS a JOIN CountEmployees AS b ON a.n = b.n AND a.dept_id < b.dept_id
  • 4. F0004 * Property of STI Page 4 of 11 Common Table Expressions Using Common Table Expressions  Example 3: WITH CountEmployees(dept_id, n) AS ( SELECT dept_id, count(*) AS n FROM employee GROUP BY dept_id ), DeptPayroll( dept_id, amt ) AS ( SELECT dept_id, sum(salary) AS amt FROM employee GROUP BY dept_id ) SELECT count.dept_id, count.n, pay.amt FROM CountEmployees AS count JOIN DeptPayroll AS pay ON count.dept_id = pay.dept_id WHERE count.n = ( SELECT max(n) FROM CountEmployees ) OR pay.amt = ( SELECT min(amt) FROM DeptPayroll )
  • 5. F0004 * Property of STI Page 5 of 11 Common Table Expressions Exercise  Assume that you need to determine which class has the most number of students. The student table lists all the students and specifies in which class each belong. Using common table expressions, find the following: 1. Extract the class with the most students. Extract the class with the fewest students. 2. List the class that has the highest GPA of students.
  • 6. F0004 * Property of STI Page 6 of 11 Common Table Expressions Applications of Common Table Expressions  Common table expressions are useful whenever multiple levels of aggregation must occur within a single query.  Views within a procedure that must contain a reference to a program variable.  Queries that use temporary result set to store a set of values.
  • 7. F0004 * Property of STI Page 7 of 11 Common Table Expressions What is Recursive Common Table Expressions  Recursive common table expressions allow you to query tables that represent hierarchical information.  A recursive common table expression is composed of an initial subquery or seed and a recursive subquery.
  • 8. F0004 * Property of STI Page 8 of 11 Common Table Expressions Example WITH RECURSIVE manager ( emp_id, manager_id, emp_fname, emp_lname, mgmt_level ) AS ( ( SELECT emp_id, manager_id, -- initial subquery emp_fname, emp_lname, 0 FROM employee AS e WHERE manager_id = emp_id ) UNION ALL ( SELECT e.emp_id, e.manager_id, - - recursive subquery e.emp_fname, e.emp_lname, m.mgmt_level + 1 FROM employee AS e JOIN manager AS m ON e.manager_id = m.emp_id AND e.manager_id <> e.emp_id AND m.mgmt_level < 20 ) ) SELECT * FROM manager ORDER BY mgmt_level, emp_lname, emp_fname
  • 9. F0004 * Property of STI Page 9 of 11 Common Table Expressions Restrictions on Recursive Common Table Expression  Recursive common table expressions cannot be mutually recursive.  The only set operator permitted between the initial subquery and the recursive subquery is UNION ALL.  Within the definition of a recursive subquery, a self-reference to the recursive table expression can appear only within the FROM clause of the recursive subquery.
  • 10. F0004 * Property of STI Page 10 of 11 Common Table Expressions Restrictions on Recursive Common Table Expression  The recursive subquery cannot contain DISTINCT, or a GROUP BY or an ORDER BY clause.  The recursive subquery can not make use of any aggregate function.  To prevent runaway recursive queries, an error is generated if the number of levels of recursion exceeds the current setting of the MAX_RECURSIVE_ITERATIONS option.
  • 11. F0004 * Property of STI Page 11 of 11 Common Table Expressions Exercise  Using the recursive common table expression, write a query that displays the Fibonacci sequence. TIP: The Fibonacci sequence is the sequence in which each number is the sum of the two preceding numbers such as 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181, ... (each number is the sum of the previous two). The Fibonacci sequence, generated by the rule f1 = f2 = 1 , fn+1 = fn + fn-1, is well known in many different areas of mathematics and science.