SlideShare a Scribd company logo
Querying Hierarchical
Data with CTE
ALEXANDER ALDEV
DBaaS Architect
MariaDB Corporation
Common Table Expressions
● SQL:1999 standard
● Temporary named result set
● Supported by: Oracle, MS SQL, PostgreSQL, SQLLite, MySQL, …
● Available in MariaDB since 10.2
● Two types:
○ Non-recursive
○ Recursive
CTE Syntax
WITH engineers AS (
SELECT *
FROM employees
WHERE dept = ‘engineering’
)
SELECT * FROM engineers ...
CTE nameWITH keyword
CTE body
use in query
Similar to Derived Queries
WITH engineers AS (
SELECT *
FROM employees
WHERE dept =
‘engineering’
)
SELECT * FROM engineers ...
SELECT * FROM (
SELECT *
FROM employees
WHERE dept =
‘engineering’
) engineers
...
Use Case: Readability
WITH engineers AS (
SELECT *
FROM employees
WHERE dept = ‘engineering’
),
WITH eu_engineers AS AS (
SELECT * FROM engineers
WHERE country IN (‘BG’,’FI’,’DE’)
)
SELECT COUNT(*) FROM eu_engineers
Use Case: Multiple References to CTE
WITH engineers AS (
SELECT *
FROM employees
WHERE dept = ‘engineering’
)
SELECT * FROM engineers e1
WHERE NOT EXISTS( SELECT 1 FROM engineers e2
WHERE e1.country = e2.country
AND e1.first = e2.first )
Use Case: Year-over-Year comparison
WITH annual_sales AS (
SELECT product, YEAR(invoice_date) AS year,
SUM( amount ) AS total
FROM invoices
GROUP BY 1, 2
)
SELECT y1.year, y1.product, y1.total, y2.total last_yr_total
FROM annual_sales y1
JOIN annual_sales y2
ON y1.year = y2.year + 1
AND y1.product = y2.product
Recursive CTE
● SQL does not handle hierarchical data well
● Trees in format (parent_id, child_id)
● Graphs in format (point 1, point 2)
● Recursive CTEs allow for hierarchical data to be handled
● Also useful for search algorithms where next iteration depends on previous
Recursive CTE Syntax
WITH RECURSIVE ancestors AS (
SELECT * FROM family
WHERE name = ‘Alex’
UNION ALL
SELECT f.* FROM family f, ancestors
WHERE f.parent_id = ancestors.id
) SELECT * FROM ancestors;
SELECT * FROM engineers ...
RECURSIVE keyword
CTE anchor
recursive use
How CTEs work?
● Base execution strategy is to materialize
● Optimizations possible for non-recursive CTE
● Recursive CTEs use this flow:
1. Evaluate anchor expression
2. Evaluate recursive expression -> new data
3. Append new data to result
4. If new data is not-empty goto 2
Example:
Sudoku Solver
Example:
ETL Job Scheduler
THANK YOU!

More Related Content

What's hot (20)

PDF
Become a super modeler
Patrick McFadin
 
PPTX
Unit 3
Abha Damani
 
PPT
Oracle Course
rspaike
 
PPTX
Unit 1 LINEAR DATA STRUCTURES
Usha Mahalingam
 
PDF
MySQL 8.0.18 latest updates: Hash join and EXPLAIN ANALYZE
Norvald Ryeng
 
PPT
Executing Sql Commands
phanleson
 
PPTX
Chapter 3 stored procedures
baabtra.com - No. 1 supplier of quality freshers
 
PPT
Dbms
philipsinter
 
PDF
Window functions with SQL Server 2016
Mark Tabladillo
 
DOCX
Function
Durgaprasad Yadav
 
PPT
statement interface
khush_boo31
 
PPTX
Semi join
Alokeparna Choudhury
 
PPTX
Stored procedure in sql server
baabtra.com - No. 1 supplier of quality freshers
 
PDF
R factors
Learnbay Datascience
 
PDF
Aaa ped-8- Data manipulation: Data wrangling, aggregation, and group operations
AminaRepo
 
PPSX
Dynamic memory allocation
Moniruzzaman _
 
PPTX
Adbms 21 sql 99 schema definition constraints and queries
Vaibhav Khanna
 
Become a super modeler
Patrick McFadin
 
Unit 3
Abha Damani
 
Oracle Course
rspaike
 
Unit 1 LINEAR DATA STRUCTURES
Usha Mahalingam
 
MySQL 8.0.18 latest updates: Hash join and EXPLAIN ANALYZE
Norvald Ryeng
 
Executing Sql Commands
phanleson
 
Window functions with SQL Server 2016
Mark Tabladillo
 
statement interface
khush_boo31
 
Stored procedure in sql server
baabtra.com - No. 1 supplier of quality freshers
 
Aaa ped-8- Data manipulation: Data wrangling, aggregation, and group operations
AminaRepo
 
Dynamic memory allocation
Moniruzzaman _
 
Adbms 21 sql 99 schema definition constraints and queries
Vaibhav Khanna
 

Similar to Query hierarchical data the easy way, with CTEs (20)

PDF
MySQL Query Optimisation 101
Federico Razzoli
 
PPTX
Introduction to the aerospike jdbc driver
Alexander Radzin
 
PPTX
Basics of SQL understanding the database.pptx
vikkylion302
 
PDF
MySQL Indexing : Improving Query Performance Using Index (Covering Index)
Hemant Kumar Singh
 
PDF
Common Table Expressions (CTE) & Window Functions in MySQL 8.0
oysteing
 
PPT
SQL Server 2000 Research Series - Transact SQL
Jerry Yang
 
ODP
Austen x talk
Matthew Goode
 
PPTX
Java Database Connectivity with JDBC.pptx
takomatiesucy
 
PDF
Designing Architecture-aware Library using Boost.Proto
Joel Falcou
 
PDF
CS-102 DS-class_01_02 Lectures Data .pdf
ssuser034ce1
 
PDF
MySQL: Indexing for Better Performance
jkeriaki
 
PPTX
Sql analytic queries tips
Vedran Bilopavlović
 
PPTX
Custom Star Creation for Ellucain's Enterprise Data Warehouse
Bryan L. Mack
 
PPTX
SQL Server Select Topics
Jay Coskey
 
PPTX
In Sync11 Presentation The Biggest Loser
paulguerin
 
PPT
Interm codegen
Anshul Sharma
 
PPTX
MySQL Optimizer Overview
Olav Sandstå
 
PDF
Relational Database and Relational Algebra
Pyingkodi Maran
 
PPT
Java Database Connectivity (JDBC) with Spring Framework is a powerful combina...
demomki4
 
PDF
Migration from mysql to elasticsearch
Ryosuke Nakamura
 
MySQL Query Optimisation 101
Federico Razzoli
 
Introduction to the aerospike jdbc driver
Alexander Radzin
 
Basics of SQL understanding the database.pptx
vikkylion302
 
MySQL Indexing : Improving Query Performance Using Index (Covering Index)
Hemant Kumar Singh
 
Common Table Expressions (CTE) & Window Functions in MySQL 8.0
oysteing
 
SQL Server 2000 Research Series - Transact SQL
Jerry Yang
 
Austen x talk
Matthew Goode
 
Java Database Connectivity with JDBC.pptx
takomatiesucy
 
Designing Architecture-aware Library using Boost.Proto
Joel Falcou
 
CS-102 DS-class_01_02 Lectures Data .pdf
ssuser034ce1
 
MySQL: Indexing for Better Performance
jkeriaki
 
Sql analytic queries tips
Vedran Bilopavlović
 
Custom Star Creation for Ellucain's Enterprise Data Warehouse
Bryan L. Mack
 
SQL Server Select Topics
Jay Coskey
 
In Sync11 Presentation The Biggest Loser
paulguerin
 
Interm codegen
Anshul Sharma
 
MySQL Optimizer Overview
Olav Sandstå
 
Relational Database and Relational Algebra
Pyingkodi Maran
 
Java Database Connectivity (JDBC) with Spring Framework is a powerful combina...
demomki4
 
Migration from mysql to elasticsearch
Ryosuke Nakamura
 
Ad

More from MariaDB plc (20)

PDF
MariaDB Berlin Roadshow Slides - 8 April 2025
MariaDB plc
 
PDF
MariaDB München Roadshow - 24 September, 2024
MariaDB plc
 
PDF
MariaDB Paris Roadshow - 19 September 2024
MariaDB plc
 
PDF
MariaDB Amsterdam Roadshow: 19 September, 2024
MariaDB plc
 
PDF
MariaDB Paris Workshop 2023 - MaxScale 23.02.x
MariaDB plc
 
PDF
MariaDB Paris Workshop 2023 - Newpharma
MariaDB plc
 
PDF
MariaDB Paris Workshop 2023 - Cloud
MariaDB plc
 
PDF
MariaDB Paris Workshop 2023 - MariaDB Enterprise
MariaDB plc
 
PDF
MariaDB Paris Workshop 2023 - Performance Optimization
MariaDB plc
 
PDF
MariaDB Paris Workshop 2023 - MaxScale
MariaDB plc
 
PDF
MariaDB Paris Workshop 2023 - novadys presentation
MariaDB plc
 
PDF
MariaDB Paris Workshop 2023 - DARVA presentation
MariaDB plc
 
PDF
MariaDB Tech und Business Update Hamburg 2023 - MariaDB Enterprise Server
MariaDB plc
 
PDF
MariaDB SkySQL Autonome Skalierung, Observability, Cloud-Backup
MariaDB plc
 
PDF
Einführung : MariaDB Tech und Business Update Hamburg 2023
MariaDB plc
 
PDF
Hochverfügbarkeitslösungen mit MariaDB
MariaDB plc
 
PDF
Die Neuheiten in MariaDB Enterprise Server
MariaDB plc
 
PDF
Global Data Replication with Galera for Ansell Guardian®
MariaDB plc
 
PDF
Introducing workload analysis
MariaDB plc
 
PDF
Under the hood: SkySQL monitoring
MariaDB plc
 
MariaDB Berlin Roadshow Slides - 8 April 2025
MariaDB plc
 
MariaDB München Roadshow - 24 September, 2024
MariaDB plc
 
MariaDB Paris Roadshow - 19 September 2024
MariaDB plc
 
MariaDB Amsterdam Roadshow: 19 September, 2024
MariaDB plc
 
MariaDB Paris Workshop 2023 - MaxScale 23.02.x
MariaDB plc
 
MariaDB Paris Workshop 2023 - Newpharma
MariaDB plc
 
MariaDB Paris Workshop 2023 - Cloud
MariaDB plc
 
MariaDB Paris Workshop 2023 - MariaDB Enterprise
MariaDB plc
 
MariaDB Paris Workshop 2023 - Performance Optimization
MariaDB plc
 
MariaDB Paris Workshop 2023 - MaxScale
MariaDB plc
 
MariaDB Paris Workshop 2023 - novadys presentation
MariaDB plc
 
MariaDB Paris Workshop 2023 - DARVA presentation
MariaDB plc
 
MariaDB Tech und Business Update Hamburg 2023 - MariaDB Enterprise Server
MariaDB plc
 
MariaDB SkySQL Autonome Skalierung, Observability, Cloud-Backup
MariaDB plc
 
Einführung : MariaDB Tech und Business Update Hamburg 2023
MariaDB plc
 
Hochverfügbarkeitslösungen mit MariaDB
MariaDB plc
 
Die Neuheiten in MariaDB Enterprise Server
MariaDB plc
 
Global Data Replication with Galera for Ansell Guardian®
MariaDB plc
 
Introducing workload analysis
MariaDB plc
 
Under the hood: SkySQL monitoring
MariaDB plc
 
Ad

Recently uploaded (20)

PDF
Unlock Efficiency with Insurance Policy Administration Systems
Insurance Tech Services
 
PDF
Generic or Specific? Making sensible software design decisions
Bert Jan Schrijver
 
PDF
MiniTool Partition Wizard 12.8 Crack License Key LATEST
hashhshs786
 
PPTX
Milwaukee Marketo User Group - Summer Road Trip: Mapping and Personalizing Yo...
bbedford2
 
PDF
Wondershare PDFelement Pro Crack for MacOS New Version Latest 2025
bashirkhan333g
 
PDF
Alexander Marshalov - How to use AI Assistants with your Monitoring system Q2...
VictoriaMetrics
 
PPTX
In From the Cold: Open Source as Part of Mainstream Software Asset Management
Shane Coughlan
 
PDF
HiHelloHR – Simplify HR Operations for Modern Workplaces
HiHelloHR
 
PDF
SciPy 2025 - Packaging a Scientific Python Project
Henry Schreiner
 
PPTX
Hardware(Central Processing Unit ) CU and ALU
RizwanaKalsoom2
 
PPTX
Why Businesses Are Switching to Open Source Alternatives to Crystal Reports.pptx
Varsha Nayak
 
PPTX
Help for Correlations in IBM SPSS Statistics.pptx
Version 1 Analytics
 
PDF
Linux Certificate of Completion - LabEx Certificate
VICTOR MAESTRE RAMIREZ
 
PPTX
Agentic Automation: Build & Deploy Your First UiPath Agent
klpathrudu
 
PDF
4K Video Downloader Plus Pro Crack for MacOS New Download 2025
bashirkhan333g
 
PDF
Automate Cybersecurity Tasks with Python
VICTOR MAESTRE RAMIREZ
 
PDF
The 5 Reasons for IT Maintenance - Arna Softech
Arna Softech
 
PDF
Empower Your Tech Vision- Why Businesses Prefer to Hire Remote Developers fro...
logixshapers59
 
PDF
Download Canva Pro 2025 PC Crack Full Latest Version
bashirkhan333g
 
PPTX
ChiSquare Procedure in IBM SPSS Statistics Version 31.pptx
Version 1 Analytics
 
Unlock Efficiency with Insurance Policy Administration Systems
Insurance Tech Services
 
Generic or Specific? Making sensible software design decisions
Bert Jan Schrijver
 
MiniTool Partition Wizard 12.8 Crack License Key LATEST
hashhshs786
 
Milwaukee Marketo User Group - Summer Road Trip: Mapping and Personalizing Yo...
bbedford2
 
Wondershare PDFelement Pro Crack for MacOS New Version Latest 2025
bashirkhan333g
 
Alexander Marshalov - How to use AI Assistants with your Monitoring system Q2...
VictoriaMetrics
 
In From the Cold: Open Source as Part of Mainstream Software Asset Management
Shane Coughlan
 
HiHelloHR – Simplify HR Operations for Modern Workplaces
HiHelloHR
 
SciPy 2025 - Packaging a Scientific Python Project
Henry Schreiner
 
Hardware(Central Processing Unit ) CU and ALU
RizwanaKalsoom2
 
Why Businesses Are Switching to Open Source Alternatives to Crystal Reports.pptx
Varsha Nayak
 
Help for Correlations in IBM SPSS Statistics.pptx
Version 1 Analytics
 
Linux Certificate of Completion - LabEx Certificate
VICTOR MAESTRE RAMIREZ
 
Agentic Automation: Build & Deploy Your First UiPath Agent
klpathrudu
 
4K Video Downloader Plus Pro Crack for MacOS New Download 2025
bashirkhan333g
 
Automate Cybersecurity Tasks with Python
VICTOR MAESTRE RAMIREZ
 
The 5 Reasons for IT Maintenance - Arna Softech
Arna Softech
 
Empower Your Tech Vision- Why Businesses Prefer to Hire Remote Developers fro...
logixshapers59
 
Download Canva Pro 2025 PC Crack Full Latest Version
bashirkhan333g
 
ChiSquare Procedure in IBM SPSS Statistics Version 31.pptx
Version 1 Analytics
 

Query hierarchical data the easy way, with CTEs

  • 1. Querying Hierarchical Data with CTE ALEXANDER ALDEV DBaaS Architect MariaDB Corporation
  • 2. Common Table Expressions ● SQL:1999 standard ● Temporary named result set ● Supported by: Oracle, MS SQL, PostgreSQL, SQLLite, MySQL, … ● Available in MariaDB since 10.2 ● Two types: ○ Non-recursive ○ Recursive
  • 3. CTE Syntax WITH engineers AS ( SELECT * FROM employees WHERE dept = ‘engineering’ ) SELECT * FROM engineers ... CTE nameWITH keyword CTE body use in query
  • 4. Similar to Derived Queries WITH engineers AS ( SELECT * FROM employees WHERE dept = ‘engineering’ ) SELECT * FROM engineers ... SELECT * FROM ( SELECT * FROM employees WHERE dept = ‘engineering’ ) engineers ...
  • 5. Use Case: Readability WITH engineers AS ( SELECT * FROM employees WHERE dept = ‘engineering’ ), WITH eu_engineers AS AS ( SELECT * FROM engineers WHERE country IN (‘BG’,’FI’,’DE’) ) SELECT COUNT(*) FROM eu_engineers
  • 6. Use Case: Multiple References to CTE WITH engineers AS ( SELECT * FROM employees WHERE dept = ‘engineering’ ) SELECT * FROM engineers e1 WHERE NOT EXISTS( SELECT 1 FROM engineers e2 WHERE e1.country = e2.country AND e1.first = e2.first )
  • 7. Use Case: Year-over-Year comparison WITH annual_sales AS ( SELECT product, YEAR(invoice_date) AS year, SUM( amount ) AS total FROM invoices GROUP BY 1, 2 ) SELECT y1.year, y1.product, y1.total, y2.total last_yr_total FROM annual_sales y1 JOIN annual_sales y2 ON y1.year = y2.year + 1 AND y1.product = y2.product
  • 8. Recursive CTE ● SQL does not handle hierarchical data well ● Trees in format (parent_id, child_id) ● Graphs in format (point 1, point 2) ● Recursive CTEs allow for hierarchical data to be handled ● Also useful for search algorithms where next iteration depends on previous
  • 9. Recursive CTE Syntax WITH RECURSIVE ancestors AS ( SELECT * FROM family WHERE name = ‘Alex’ UNION ALL SELECT f.* FROM family f, ancestors WHERE f.parent_id = ancestors.id ) SELECT * FROM ancestors; SELECT * FROM engineers ... RECURSIVE keyword CTE anchor recursive use
  • 10. How CTEs work? ● Base execution strategy is to materialize ● Optimizations possible for non-recursive CTE ● Recursive CTEs use this flow: 1. Evaluate anchor expression 2. Evaluate recursive expression -> new data 3. Append new data to result 4. If new data is not-empty goto 2

Editor's Notes

  • #2: Alex: 20 yrs experience in DWH, analytics and a couple of business functions, currently leading MariaDB’s DBaaS architecture.
  • #12: We’ll open two minikube consoles and do the following: Deploy a simple “Hello, world” NodeJS application. Use “docker build” and “kubectl create” Start a simple client that measures performance. Use “docker build” and “kubectl create” Scale the application from 1 to 3 and observe throughput. Use “kubectl get pods Fail a number of pods. Use “kubectl delete pod” Upgrade the application to v2.0. Use “kubectl set image”
  • #13: We’ll open two minikube consoles and do the following: Deploy a simple “Hello, world” NodeJS application. Use “docker build” and “kubectl create” Start a simple client that measures performance. Use “docker build” and “kubectl create” Scale the application from 1 to 3 and observe throughput. Use “kubectl get pods Fail a number of pods. Use “kubectl delete pod” Upgrade the application to v2.0. Use “kubectl set image”
  • #14: Last slide -- the remaining are backup and will be deleted