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!
Ad

More Related Content

What's hot (20)

Jdbc
JdbcJdbc
Jdbc
UmaMaheswariBHCInfor
 
Become a super modeler
Become a super modelerBecome a super modeler
Become a super modeler
Patrick McFadin
 
Unit 3
Unit 3Unit 3
Unit 3
Abha Damani
 
Oracle Course
Oracle CourseOracle Course
Oracle Course
rspaike
 
Unit 1 LINEAR DATA STRUCTURES
Unit 1  LINEAR DATA STRUCTURESUnit 1  LINEAR DATA STRUCTURES
Unit 1 LINEAR DATA STRUCTURES
Usha Mahalingam
 
MySQL 8.0.18 latest updates: Hash join and EXPLAIN ANALYZE
MySQL 8.0.18 latest updates: Hash join and EXPLAIN ANALYZEMySQL 8.0.18 latest updates: Hash join and EXPLAIN ANALYZE
MySQL 8.0.18 latest updates: Hash join and EXPLAIN ANALYZE
Norvald Ryeng
 
Dbms
DbmsDbms
Dbms
Maria Stella Solon
 
Executing Sql Commands
Executing Sql CommandsExecuting Sql Commands
Executing Sql Commands
phanleson
 
Chapter 3 stored procedures
Chapter 3 stored proceduresChapter 3 stored procedures
Chapter 3 stored procedures
baabtra.com - No. 1 supplier of quality freshers
 
Dbms
DbmsDbms
Dbms
philipsinter
 
Window functions with SQL Server 2016
Window functions with SQL Server 2016Window functions with SQL Server 2016
Window functions with SQL Server 2016
Mark Tabladillo
 
Function
FunctionFunction
Function
Durgaprasad Yadav
 
statement interface
statement interface statement interface
statement interface
khush_boo31
 
Semi join
Semi joinSemi join
Semi join
Alokeparna Choudhury
 
Stored procedure in sql server
Stored procedure in sql serverStored procedure in sql server
Stored procedure in sql server
baabtra.com - No. 1 supplier of quality freshers
 
R factors
R   factorsR   factors
R factors
Learnbay Datascience
 
Aaa ped-8- Data manipulation: Data wrangling, aggregation, and group operations
Aaa ped-8- Data manipulation: Data wrangling, aggregation, and group operationsAaa ped-8- Data manipulation: Data wrangling, aggregation, and group operations
Aaa ped-8- Data manipulation: Data wrangling, aggregation, and group operations
AminaRepo
 
1 ddl
1 ddl1 ddl
1 ddl
Mr Patrick NIYISHAKA
 
Dynamic memory allocation
Dynamic memory allocationDynamic memory allocation
Dynamic memory allocation
Moniruzzaman _
 
Adbms 21 sql 99 schema definition constraints and queries
Adbms 21 sql 99 schema definition constraints and queriesAdbms 21 sql 99 schema definition constraints and queries
Adbms 21 sql 99 schema definition constraints and queries
Vaibhav Khanna
 

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

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

More from MariaDB plc (20)

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

Recently uploaded (20)

Top 12 Most Useful AngularJS Development Tools to Use in 2025
Top 12 Most Useful AngularJS Development Tools to Use in 2025Top 12 Most Useful AngularJS Development Tools to Use in 2025
Top 12 Most Useful AngularJS Development Tools to Use in 2025
GrapesTech Solutions
 
AEM User Group DACH - 2025 Inaugural Meeting
AEM User Group DACH - 2025 Inaugural MeetingAEM User Group DACH - 2025 Inaugural Meeting
AEM User Group DACH - 2025 Inaugural Meeting
jennaf3
 
Autodesk Inventor Crack (2025) Latest
Autodesk Inventor    Crack (2025) LatestAutodesk Inventor    Crack (2025) Latest
Autodesk Inventor Crack (2025) Latest
Google
 
S3 + AWS Athena how to integrate s3 aws plus athena
S3 + AWS Athena how to integrate s3 aws plus athenaS3 + AWS Athena how to integrate s3 aws plus athena
S3 + AWS Athena how to integrate s3 aws plus athena
aianand98
 
Digital Twins Software Service in Belfast
Digital Twins Software Service in BelfastDigital Twins Software Service in Belfast
Digital Twins Software Service in Belfast
julia smits
 
Orion Context Broker introduction 20250509
Orion Context Broker introduction 20250509Orion Context Broker introduction 20250509
Orion Context Broker introduction 20250509
Fermin Galan
 
Welcome to QA Summit 2025.
Welcome to QA Summit 2025.Welcome to QA Summit 2025.
Welcome to QA Summit 2025.
QA Summit
 
Let's Do Bad Things to Unsecured Containers
Let's Do Bad Things to Unsecured ContainersLet's Do Bad Things to Unsecured Containers
Let's Do Bad Things to Unsecured Containers
Gene Gotimer
 
Mobile Application Developer Dubai | Custom App Solutions by Ajath
Mobile Application Developer Dubai | Custom App Solutions by AjathMobile Application Developer Dubai | Custom App Solutions by Ajath
Mobile Application Developer Dubai | Custom App Solutions by Ajath
Ajath Infotech Technologies LLC
 
!%& IDM Crack with Internet Download Manager 6.42 Build 32 >
!%& IDM Crack with Internet Download Manager 6.42 Build 32 >!%& IDM Crack with Internet Download Manager 6.42 Build 32 >
!%& IDM Crack with Internet Download Manager 6.42 Build 32 >
Ranking Google
 
Unit Two - Java Architecture and OOPS
Unit Two  -   Java Architecture and OOPSUnit Two  -   Java Architecture and OOPS
Unit Two - Java Architecture and OOPS
Nabin Dhakal
 
Robotic Process Automation (RPA) Software Development Services.pptx
Robotic Process Automation (RPA) Software Development Services.pptxRobotic Process Automation (RPA) Software Development Services.pptx
Robotic Process Automation (RPA) Software Development Services.pptx
julia smits
 
Deploying & Testing Agentforce - End-to-end with Copado - Ewenb Clark
Deploying & Testing Agentforce - End-to-end with Copado - Ewenb ClarkDeploying & Testing Agentforce - End-to-end with Copado - Ewenb Clark
Deploying & Testing Agentforce - End-to-end with Copado - Ewenb Clark
Peter Caitens
 
Do not let staffing shortages and limited fiscal view hamper your cause
Do not let staffing shortages and limited fiscal view hamper your causeDo not let staffing shortages and limited fiscal view hamper your cause
Do not let staffing shortages and limited fiscal view hamper your cause
Fexle Services Pvt. Ltd.
 
User interface and User experience Modernization.pptx
User interface and User experience  Modernization.pptxUser interface and User experience  Modernization.pptx
User interface and User experience Modernization.pptx
MustafaAlshekly1
 
Time Estimation: Expert Tips & Proven Project Techniques
Time Estimation: Expert Tips & Proven Project TechniquesTime Estimation: Expert Tips & Proven Project Techniques
Time Estimation: Expert Tips & Proven Project Techniques
Livetecs LLC
 
Troubleshooting JVM Outages – 3 Fortune 500 case studies
Troubleshooting JVM Outages – 3 Fortune 500 case studiesTroubleshooting JVM Outages – 3 Fortune 500 case studies
Troubleshooting JVM Outages – 3 Fortune 500 case studies
Tier1 app
 
Reinventing Microservices Efficiency and Innovation with Single-Runtime
Reinventing Microservices Efficiency and Innovation with Single-RuntimeReinventing Microservices Efficiency and Innovation with Single-Runtime
Reinventing Microservices Efficiency and Innovation with Single-Runtime
Natan Silnitsky
 
Download MathType Crack Version 2025???
Download MathType Crack  Version 2025???Download MathType Crack  Version 2025???
Download MathType Crack Version 2025???
Google
 
Comprehensive Incident Management System for Enhanced Safety Reporting
Comprehensive Incident Management System for Enhanced Safety ReportingComprehensive Incident Management System for Enhanced Safety Reporting
Comprehensive Incident Management System for Enhanced Safety Reporting
EHA Soft Solutions
 
Top 12 Most Useful AngularJS Development Tools to Use in 2025
Top 12 Most Useful AngularJS Development Tools to Use in 2025Top 12 Most Useful AngularJS Development Tools to Use in 2025
Top 12 Most Useful AngularJS Development Tools to Use in 2025
GrapesTech Solutions
 
AEM User Group DACH - 2025 Inaugural Meeting
AEM User Group DACH - 2025 Inaugural MeetingAEM User Group DACH - 2025 Inaugural Meeting
AEM User Group DACH - 2025 Inaugural Meeting
jennaf3
 
Autodesk Inventor Crack (2025) Latest
Autodesk Inventor    Crack (2025) LatestAutodesk Inventor    Crack (2025) Latest
Autodesk Inventor Crack (2025) Latest
Google
 
S3 + AWS Athena how to integrate s3 aws plus athena
S3 + AWS Athena how to integrate s3 aws plus athenaS3 + AWS Athena how to integrate s3 aws plus athena
S3 + AWS Athena how to integrate s3 aws plus athena
aianand98
 
Digital Twins Software Service in Belfast
Digital Twins Software Service in BelfastDigital Twins Software Service in Belfast
Digital Twins Software Service in Belfast
julia smits
 
Orion Context Broker introduction 20250509
Orion Context Broker introduction 20250509Orion Context Broker introduction 20250509
Orion Context Broker introduction 20250509
Fermin Galan
 
Welcome to QA Summit 2025.
Welcome to QA Summit 2025.Welcome to QA Summit 2025.
Welcome to QA Summit 2025.
QA Summit
 
Let's Do Bad Things to Unsecured Containers
Let's Do Bad Things to Unsecured ContainersLet's Do Bad Things to Unsecured Containers
Let's Do Bad Things to Unsecured Containers
Gene Gotimer
 
Mobile Application Developer Dubai | Custom App Solutions by Ajath
Mobile Application Developer Dubai | Custom App Solutions by AjathMobile Application Developer Dubai | Custom App Solutions by Ajath
Mobile Application Developer Dubai | Custom App Solutions by Ajath
Ajath Infotech Technologies LLC
 
!%& IDM Crack with Internet Download Manager 6.42 Build 32 >
!%& IDM Crack with Internet Download Manager 6.42 Build 32 >!%& IDM Crack with Internet Download Manager 6.42 Build 32 >
!%& IDM Crack with Internet Download Manager 6.42 Build 32 >
Ranking Google
 
Unit Two - Java Architecture and OOPS
Unit Two  -   Java Architecture and OOPSUnit Two  -   Java Architecture and OOPS
Unit Two - Java Architecture and OOPS
Nabin Dhakal
 
Robotic Process Automation (RPA) Software Development Services.pptx
Robotic Process Automation (RPA) Software Development Services.pptxRobotic Process Automation (RPA) Software Development Services.pptx
Robotic Process Automation (RPA) Software Development Services.pptx
julia smits
 
Deploying & Testing Agentforce - End-to-end with Copado - Ewenb Clark
Deploying & Testing Agentforce - End-to-end with Copado - Ewenb ClarkDeploying & Testing Agentforce - End-to-end with Copado - Ewenb Clark
Deploying & Testing Agentforce - End-to-end with Copado - Ewenb Clark
Peter Caitens
 
Do not let staffing shortages and limited fiscal view hamper your cause
Do not let staffing shortages and limited fiscal view hamper your causeDo not let staffing shortages and limited fiscal view hamper your cause
Do not let staffing shortages and limited fiscal view hamper your cause
Fexle Services Pvt. Ltd.
 
User interface and User experience Modernization.pptx
User interface and User experience  Modernization.pptxUser interface and User experience  Modernization.pptx
User interface and User experience Modernization.pptx
MustafaAlshekly1
 
Time Estimation: Expert Tips & Proven Project Techniques
Time Estimation: Expert Tips & Proven Project TechniquesTime Estimation: Expert Tips & Proven Project Techniques
Time Estimation: Expert Tips & Proven Project Techniques
Livetecs LLC
 
Troubleshooting JVM Outages – 3 Fortune 500 case studies
Troubleshooting JVM Outages – 3 Fortune 500 case studiesTroubleshooting JVM Outages – 3 Fortune 500 case studies
Troubleshooting JVM Outages – 3 Fortune 500 case studies
Tier1 app
 
Reinventing Microservices Efficiency and Innovation with Single-Runtime
Reinventing Microservices Efficiency and Innovation with Single-RuntimeReinventing Microservices Efficiency and Innovation with Single-Runtime
Reinventing Microservices Efficiency and Innovation with Single-Runtime
Natan Silnitsky
 
Download MathType Crack Version 2025???
Download MathType Crack  Version 2025???Download MathType Crack  Version 2025???
Download MathType Crack Version 2025???
Google
 
Comprehensive Incident Management System for Enhanced Safety Reporting
Comprehensive Incident Management System for Enhanced Safety ReportingComprehensive Incident Management System for Enhanced Safety Reporting
Comprehensive Incident Management System for Enhanced Safety Reporting
EHA Soft Solutions
 

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
  翻译: