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.
1 _________________
___________________
___________________
___________________
___________________
___________________
___________________
___________________
___________________
___________________
___________________
___________________
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
3 __________________
___________________
___________________
___________________
___________________
___________________
___________________
___________________
___________________
___________________
___________________
___________________
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 )
2 _________________
___________________
___________________
___________________
___________________
___________________
___________________
___________________
___________________
___________________
___________________
___________________
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 )
4 __________________
___________________
___________________
___________________
___________________
___________________
___________________
___________________
___________________
___________________
___________________
___________________
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.
5 _________________
___________________
___________________
___________________
___________________
___________________
___________________
___________________
___________________
___________________
___________________
___________________
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.
7 __________________
___________________
___________________
___________________
___________________
___________________
___________________
___________________
___________________
___________________
___________________
___________________
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.
6 _________________
___________________
___________________
___________________
___________________
___________________
___________________
___________________
___________________
___________________
___________________
___________________
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
8 __________________
___________________
___________________
___________________
___________________
___________________
___________________
___________________
___________________
___________________
___________________
___________________
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.
9 _________________
___________________
___________________
___________________
___________________
___________________
___________________
___________________
___________________
___________________
___________________
___________________
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.
11 _________________
___________________
___________________
___________________
___________________
___________________
___________________
___________________
___________________
___________________
___________________
___________________
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.
10 ________________
___________________
___________________
___________________
___________________
___________________
___________________
___________________
___________________
___________________
___________________
___________________

More Related Content

PDF
Igcse biology concepts revision chapter 1 to 8
DOCX
Year 13 sports studies fatigue technical-exam
DOC
Why Do Sociologists Conduct Research
DOC
Social approach work book
PDF
UPSR 2017 - Compilation English 014 (Section B)
PDF
Assessment notes
PDF
Collaborative Learning in Online Learning
DOCX
Paper 2
Igcse biology concepts revision chapter 1 to 8
Year 13 sports studies fatigue technical-exam
Why Do Sociologists Conduct Research
Social approach work book
UPSR 2017 - Compilation English 014 (Section B)
Assessment notes
Collaborative Learning in Online Learning
Paper 2

What's hot (19)

DOC
Employment opportunities
DOC
Bi year 4 paper 2
PDF
The Jacket Graphic Organizer (Mr. Schroeder's Class)
DOCX
BAHASA INGGERIS TAHUN 4 2017 KERTAS 2
DOC
Sjkc eng paper 2 set 2
DOC
Sjkc eng paper 2 set 1
DOC
Presentation handout edtc 640
DOCX
Martin luther king jr
DOCX
DOC
Kssr English Yr 4 Mid term exam
PDF
ADDIE Model
DOCX
English exam for 2015 (Mid year 5)
PDF
Nift 2010 cat sample question papers
DOC
Set 1 kertas 2(English UPSR)
DOCX
(Baru) kertas soalan bi tahun 1
DOCX
Change 4 to its simplest form
PPT
Fractions shapes amounts
DOC
Bi paper pat kp
PDF
Transformative Learning
Employment opportunities
Bi year 4 paper 2
The Jacket Graphic Organizer (Mr. Schroeder's Class)
BAHASA INGGERIS TAHUN 4 2017 KERTAS 2
Sjkc eng paper 2 set 2
Sjkc eng paper 2 set 1
Presentation handout edtc 640
Martin luther king jr
Kssr English Yr 4 Mid term exam
ADDIE Model
English exam for 2015 (Mid year 5)
Nift 2010 cat sample question papers
Set 1 kertas 2(English UPSR)
(Baru) kertas soalan bi tahun 1
Change 4 to its simplest form
Fractions shapes amounts
Bi paper pat kp
Transformative Learning
Ad

Viewers also liked (9)

PPTX
Monitor PS Sardegna
PDF
Public Parks and Fitness Groups
PPT
O flautista
PDF
The Balanced Care Method Flyer
DOCX
Proyecto valle
PPSX
05 lcd slides 1 - CPU SCHEDULING (Powerpoint)
PPTX
Strategic Communications and National Security
PDF
El párrafo: introducción, desarrollo y cierre
DOC
Organizadores de bodas
Monitor PS Sardegna
Public Parks and Fitness Groups
O flautista
The Balanced Care Method Flyer
Proyecto valle
05 lcd slides 1 - CPU SCHEDULING (Powerpoint)
Strategic Communications and National Security
El párrafo: introducción, desarrollo y cierre
Organizadores de bodas
Ad

Similar to 03 ohp slide handout 1 (20)

PDF
03 ohp slides 1
PPT
Common table expressions
PDF
03 laboratory exercise 1
PDF
03 laboratory exercise 1 - WORKING WITH CTE
PPTX
T sql語法之 cte 20140214
PPTX
Set operators - derived tables and CTEs
PPTX
Set Operators, Derived Tables and CTEs
PPTX
PPT of Common Table Expression (CTE), Window Functions, JOINS, SubQuery
PDF
MySQL 8.0: Common Table Expressions
PDF
MySQL 8.0: Common Table Expressions
PDF
04 quiz 1 answer key
PDF
Common Table Expressions (CTE) & Window Functions in MySQL 8.0
PDF
Ctes percona live_2017
PPTX
New SQL features in latest MySQL releases
PPTX
PDF
M|18 Taking Advantage of Common Table Expressions
PPT
PDF
MySQL Optimizer: What’s New in 8.0
PDF
Tech Jam 01 - Database Querying
PPTX
Subqueries, Backups, Users and Privileges
03 ohp slides 1
Common table expressions
03 laboratory exercise 1
03 laboratory exercise 1 - WORKING WITH CTE
T sql語法之 cte 20140214
Set operators - derived tables and CTEs
Set Operators, Derived Tables and CTEs
PPT of Common Table Expression (CTE), Window Functions, JOINS, SubQuery
MySQL 8.0: Common Table Expressions
MySQL 8.0: Common Table Expressions
04 quiz 1 answer key
Common Table Expressions (CTE) & Window Functions in MySQL 8.0
Ctes percona live_2017
New SQL features in latest MySQL releases
M|18 Taking Advantage of Common Table Expressions
MySQL Optimizer: What’s New in 8.0
Tech Jam 01 - Database Querying
Subqueries, Backups, Users and Privileges

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 Handout
PDF
Database Security - IG
PDF
02 laboratory exercise 1 - RETRIEVING DATA FROM SEVERAL TABLES
PDF
01 laboratory exercise 1 - DESIGN A SIMPLE DATABASE APPLICATION
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
07 lcd slides 1 - DEADLOCKS 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 Handout
Database Security - IG
02 laboratory exercise 1 - RETRIEVING DATA FROM SEVERAL TABLES
01 laboratory exercise 1 - DESIGN A SIMPLE DATABASE APPLICATION
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
07 lcd slides 1 - DEADLOCKS POWERPOINT

Recently uploaded (20)

PPTX
Introduction to Windows Operating System
PDF
Ableton Live Suite for MacOS Crack Full Download (Latest 2025)
PPTX
How to Odoo 19 Installation on Ubuntu - CandidRoot
PDF
Wondershare Recoverit Full Crack New Version (Latest 2025)
PDF
CCleaner 6.39.11548 Crack 2025 License Key
PPTX
MLforCyber_MLDataSetsandFeatures_Presentation.pptx
PDF
Introduction to Ragic - #1 No Code Tool For Digitalizing Your Business Proces...
PPTX
Python is a high-level, interpreted programming language
PPTX
4Seller: The All-in-One Multi-Channel E-Commerce Management Platform for Glob...
PDF
How Tridens DevSecOps Ensures Compliance, Security, and Agility
DOC
UTEP毕业证学历认证,宾夕法尼亚克拉里恩大学毕业证未毕业
PPTX
CNN LeNet5 Architecture: Neural Networks
DOCX
How to Use SharePoint as an ISO-Compliant Document Management System
PDF
AI Guide for Business Growth - Arna Softech
PPTX
Cybersecurity: Protecting the Digital World
PPTX
Full-Stack Developer Courses That Actually Land You Jobs
PDF
Guide to Food Delivery App Development.pdf
PPTX
GSA Content Generator Crack (2025 Latest)
PDF
DNT Brochure 2025 – ISV Solutions @ D365
PPTX
Computer Software - Technology and Livelihood Education
Introduction to Windows Operating System
Ableton Live Suite for MacOS Crack Full Download (Latest 2025)
How to Odoo 19 Installation on Ubuntu - CandidRoot
Wondershare Recoverit Full Crack New Version (Latest 2025)
CCleaner 6.39.11548 Crack 2025 License Key
MLforCyber_MLDataSetsandFeatures_Presentation.pptx
Introduction to Ragic - #1 No Code Tool For Digitalizing Your Business Proces...
Python is a high-level, interpreted programming language
4Seller: The All-in-One Multi-Channel E-Commerce Management Platform for Glob...
How Tridens DevSecOps Ensures Compliance, Security, and Agility
UTEP毕业证学历认证,宾夕法尼亚克拉里恩大学毕业证未毕业
CNN LeNet5 Architecture: Neural Networks
How to Use SharePoint as an ISO-Compliant Document Management System
AI Guide for Business Growth - Arna Softech
Cybersecurity: Protecting the Digital World
Full-Stack Developer Courses That Actually Land You Jobs
Guide to Food Delivery App Development.pdf
GSA Content Generator Crack (2025 Latest)
DNT Brochure 2025 – ISV Solutions @ D365
Computer Software - Technology and Livelihood Education

03 ohp slide handout 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. 1 _________________ ___________________ ___________________ ___________________ ___________________ ___________________ ___________________ ___________________ ___________________ ___________________ ___________________ ___________________ 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 3 __________________ ___________________ ___________________ ___________________ ___________________ ___________________ ___________________ ___________________ ___________________ ___________________ ___________________ ___________________ 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 ) 2 _________________ ___________________ ___________________ ___________________ ___________________ ___________________ ___________________ ___________________ ___________________ ___________________ ___________________ ___________________ 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 ) 4 __________________ ___________________ ___________________ ___________________ ___________________ ___________________ ___________________ ___________________ ___________________ ___________________ ___________________ ___________________
  • 2. 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. 5 _________________ ___________________ ___________________ ___________________ ___________________ ___________________ ___________________ ___________________ ___________________ ___________________ ___________________ ___________________ 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. 7 __________________ ___________________ ___________________ ___________________ ___________________ ___________________ ___________________ ___________________ ___________________ ___________________ ___________________ ___________________ 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. 6 _________________ ___________________ ___________________ ___________________ ___________________ ___________________ ___________________ ___________________ ___________________ ___________________ ___________________ ___________________ 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 8 __________________ ___________________ ___________________ ___________________ ___________________ ___________________ ___________________ ___________________ ___________________ ___________________ ___________________ ___________________
  • 3. 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. 9 _________________ ___________________ ___________________ ___________________ ___________________ ___________________ ___________________ ___________________ ___________________ ___________________ ___________________ ___________________ 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. 11 _________________ ___________________ ___________________ ___________________ ___________________ ___________________ ___________________ ___________________ ___________________ ___________________ ___________________ ___________________ 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. 10 ________________ ___________________ ___________________ ___________________ ___________________ ___________________ ___________________ ___________________ ___________________ ___________________ ___________________ ___________________