SlideShare a Scribd company logo
1 of 29
Download to read offline
WRITING RECURSIVE QUERIES
RETRIEVING HIERARCHY DATA FROM RELATIONAL TABLES
BEN LIS
POSTGRESCONF US 2019
IS THIS TALK RIGHT FOR YOU?
What we will cover
• Why we need recursive queries
• How they work
• How to write them
What you should know
• Basic knowledge of SQL through outer joins
• General programming concepts
• Slides and SQL:
https://github.com/benjlis/talk-writing-recursive-
queries
2
ABOUT ME
• Data Engineer at LEI Smart
• Writes recursive queries on corporate hierarchy data
• Initially found recursive SQL a bit confusing
• Using PostgreSQL since 2015
• Started working with Oracle databases in 1988!
• Adjunct Associate Faculty in Applied Analytics at Columbia University
• Held various technical, product, and management roles on Wall Street
• LinkedIn and Twitter
3
AGENDA
• Motivation
• Understanding Recursive SQL
• Writing Recursive Queries
• Next Steps
• Questions & Discussion
4
MOTIVATION
WHY WE NEED RECURSIVE SQL
5
HR DATABASE
hrex-create.sql
6
LET’S QUERY EMPLOYEES, THEIR BOSS & THE BOSS'S BOSS
boss-queries.sql
7
LET’S QUERY
EMPLOYEES’
ENTIRE
REPORTING LINE
HMMM… HOW DO WE DO THAT?
8
IDEA 1: EXTEND
CURRENT
APPROACH
“Add a few more JOINs”
Need to know the number of hierarchy levels
in advance
Not realistic or robust!
9
IDEA 2: WRITE A
PROGRAM
Use Python, Java, PL/pgSQL, etc.
Query all employees
For each employee get their boss’s record
and then their boss’s boss’s record, etc.
until you get a NULL
Complex and resource consumptive!
10
SHOULDN’T WE BE
ABLE TO WRITE
THIS QUERY IN
SQL?
11
WE SHOULD BE ABLE TO WRITE THIS QUERY IN SQL
• In the early days (decades) of SQL & relational databases we couldn’t
• Writing a program (Idea 2) was the only solution
• Other names for the hierarchy problem:
• Transitive Closure
• Bill of Materials
• Parts Explosion
• Good news: We can write this query in modern SQL using recursive SQL!
12
UNDERSTANDING RECURSIVE SQL
KEY IDEAS, CTE, SYNTAX, STRUCTURE & EVALUATION
13
RECURSIVE SQL SUPPORT
Part of ISO Standard SQL
Introduced in SQL:1999 (aka SQL 3)
Supported in
PostgreSQL
Oracle
SQL Server
DB2
14
KEY IDEAS
• re·cur·sive /rəˈkərsiv/: a program or routine of which a part
requires the application of the whole, so that its explicit
interpretation requires in general many successive executions
• Self-referencing
• Your Bosses = Your Manager + Your Manager’s Bosses
• Recursive SQL is an iterative process
• Think while loops
• But SQL is declarative!!!!
• Tip: Put aside knowledge of recursion in programming
• Recursive SQL uses Common Table Expressions (CTEs)
15
COMMON TABLE EXPRESSION (CTE) EXAMPLE
cte.sql
• Primarily used to simplify queries
• Think of as inline view(s)
16
RECURSIVE CTE
STRUCTURE
• Keyword: recursive
• Always a UNION or UNION ALL of
• Non-recursive select
• Recursive select
17
NON-RECURSIVE
SELECT
• Evaluated 1st - where we start
• FROM clause:
• Must not refer to <cte-name>
• Refers to table containing hierarchy
18
RECURSIVE SELECT
• Evaluated 2..N times
• FROM clause:
• Must reference <cte-name>
• Join of the <cte-name> and table
containing hierarchy
• N is a function of the data and the
recursive select’s where clause
19
RECURSIVE CTE
EVALUATION
QR = Query Results; WT = Working Table
Both initially empty
1. Execute <non-recursive select>
2. Add results to QR and WT
3. Repeat until WT is empty
a. Execute <recursive select> using WT
data for <cte-name>
b. Add results to QR
c. Replace WT with results
20
WRITING RECURSIVE QUERIES
LET’S GET DOWN TO IT!
21
WHAT IS ADAMS REPORTING LINE?
rl.sql
22
ALL EMPLOYEES FROM CEO TO ENTRY LEVEL
oc.sql
23
INCLUDE A LEVEL
oc-level.sql
24
INCLUDE A PATH
oc-path.sql
25
NEXT STEPS
RECOMMENDED READINGS & BEYOND HIERARCHY
26
RECOMMENDED READINGS
• PostgreSQL documentation
• Fun with SQL: Recursive CTEs in Postgres – Craig Kerstiens
• Modern SQL in Open Source and Commercial Databases (slides 45-60) – Markus Winand
• Exporting a Hierarchy in JSON: with recursive queries - Dmitri Fontaine
• Joe Celko’s Trees and Hierarchies in SQL for Smarties (Book)
27
BEYOND HIERARCHY
• Hierarchy queries are the most common application of recursive SQL, but not the only application!
• Pretty wild recursive SQL queries:
• Solving the Traveling Salesman Problem with Postgres Recursive CTEs - Periscope Data
• Mandelbrot Set
• tic-tac-toe
• My views:
• Can doesn’t mean should
• Worth studying for learning advanced techniques
28
QUESTIONS
29

More Related Content

What's hot

Overview of Apache Spark 2.3: What’s New? with Sameer Agarwal
 Overview of Apache Spark 2.3: What’s New? with Sameer Agarwal Overview of Apache Spark 2.3: What’s New? with Sameer Agarwal
Overview of Apache Spark 2.3: What’s New? with Sameer AgarwalDatabricks
 
Structured Streaming Use-Cases at Apple
Structured Streaming Use-Cases at AppleStructured Streaming Use-Cases at Apple
Structured Streaming Use-Cases at AppleDatabricks
 
WebCamp: Developer Day: Оптимизация Lift Framework для работы с большими пото...
WebCamp: Developer Day: Оптимизация Lift Framework для работы с большими пото...WebCamp: Developer Day: Оптимизация Lift Framework для работы с большими пото...
WebCamp: Developer Day: Оптимизация Lift Framework для работы с большими пото...GeeksLab Odessa
 
Lessons Learned with Spark at the US Patent & Trademark Office-(Christopher B...
Lessons Learned with Spark at the US Patent & Trademark Office-(Christopher B...Lessons Learned with Spark at the US Patent & Trademark Office-(Christopher B...
Lessons Learned with Spark at the US Patent & Trademark Office-(Christopher B...Spark Summit
 
Migrating to Spark 2.0 - Part 2
Migrating to Spark 2.0 - Part 2Migrating to Spark 2.0 - Part 2
Migrating to Spark 2.0 - Part 2datamantra
 
Introduction to spark 2.0
Introduction to spark 2.0Introduction to spark 2.0
Introduction to spark 2.0datamantra
 
Enabling Scalable Data Science Pipeline with Mlflow at Thermo Fisher Scientific
Enabling Scalable Data Science Pipeline with Mlflow at Thermo Fisher ScientificEnabling Scalable Data Science Pipeline with Mlflow at Thermo Fisher Scientific
Enabling Scalable Data Science Pipeline with Mlflow at Thermo Fisher ScientificDatabricks
 
Workflow Engines for Hadoop
Workflow Engines for HadoopWorkflow Engines for Hadoop
Workflow Engines for HadoopJoe Crobak
 
Introduction to Spark 2.0 Dataset API
Introduction to Spark 2.0 Dataset APIIntroduction to Spark 2.0 Dataset API
Introduction to Spark 2.0 Dataset APIdatamantra
 
Scaling Security Threat Detection with Apache Spark and Databricks
Scaling Security Threat Detection with Apache Spark and DatabricksScaling Security Threat Detection with Apache Spark and Databricks
Scaling Security Threat Detection with Apache Spark and DatabricksDatabricks
 
Grokking TechTalk #20: PostgreSQL Internals 101
Grokking TechTalk #20: PostgreSQL Internals 101Grokking TechTalk #20: PostgreSQL Internals 101
Grokking TechTalk #20: PostgreSQL Internals 101Grokking VN
 
How Totango uses Apache Spark
How Totango uses Apache SparkHow Totango uses Apache Spark
How Totango uses Apache SparkOren Raboy
 
Galene - LinkedIn's Search Architecture: Presented by Diego Buthay & Sriram S...
Galene - LinkedIn's Search Architecture: Presented by Diego Buthay & Sriram S...Galene - LinkedIn's Search Architecture: Presented by Diego Buthay & Sriram S...
Galene - LinkedIn's Search Architecture: Presented by Diego Buthay & Sriram S...Lucidworks
 
Migrating to spark 2.0
Migrating to spark 2.0Migrating to spark 2.0
Migrating to spark 2.0datamantra
 
Spark Summit EU talk by Oscar Castaneda
Spark Summit EU talk by Oscar CastanedaSpark Summit EU talk by Oscar Castaneda
Spark Summit EU talk by Oscar CastanedaSpark Summit
 
Introduction to Apache Spark 2.0
Introduction to Apache Spark 2.0Introduction to Apache Spark 2.0
Introduction to Apache Spark 2.0Knoldus Inc.
 
Spark Summit EU talk by Kent Buenaventura and Willaim Lau
Spark Summit EU talk by Kent Buenaventura and Willaim LauSpark Summit EU talk by Kent Buenaventura and Willaim Lau
Spark Summit EU talk by Kent Buenaventura and Willaim LauSpark Summit
 

What's hot (17)

Overview of Apache Spark 2.3: What’s New? with Sameer Agarwal
 Overview of Apache Spark 2.3: What’s New? with Sameer Agarwal Overview of Apache Spark 2.3: What’s New? with Sameer Agarwal
Overview of Apache Spark 2.3: What’s New? with Sameer Agarwal
 
Structured Streaming Use-Cases at Apple
Structured Streaming Use-Cases at AppleStructured Streaming Use-Cases at Apple
Structured Streaming Use-Cases at Apple
 
WebCamp: Developer Day: Оптимизация Lift Framework для работы с большими пото...
WebCamp: Developer Day: Оптимизация Lift Framework для работы с большими пото...WebCamp: Developer Day: Оптимизация Lift Framework для работы с большими пото...
WebCamp: Developer Day: Оптимизация Lift Framework для работы с большими пото...
 
Lessons Learned with Spark at the US Patent & Trademark Office-(Christopher B...
Lessons Learned with Spark at the US Patent & Trademark Office-(Christopher B...Lessons Learned with Spark at the US Patent & Trademark Office-(Christopher B...
Lessons Learned with Spark at the US Patent & Trademark Office-(Christopher B...
 
Migrating to Spark 2.0 - Part 2
Migrating to Spark 2.0 - Part 2Migrating to Spark 2.0 - Part 2
Migrating to Spark 2.0 - Part 2
 
Introduction to spark 2.0
Introduction to spark 2.0Introduction to spark 2.0
Introduction to spark 2.0
 
Enabling Scalable Data Science Pipeline with Mlflow at Thermo Fisher Scientific
Enabling Scalable Data Science Pipeline with Mlflow at Thermo Fisher ScientificEnabling Scalable Data Science Pipeline with Mlflow at Thermo Fisher Scientific
Enabling Scalable Data Science Pipeline with Mlflow at Thermo Fisher Scientific
 
Workflow Engines for Hadoop
Workflow Engines for HadoopWorkflow Engines for Hadoop
Workflow Engines for Hadoop
 
Introduction to Spark 2.0 Dataset API
Introduction to Spark 2.0 Dataset APIIntroduction to Spark 2.0 Dataset API
Introduction to Spark 2.0 Dataset API
 
Scaling Security Threat Detection with Apache Spark and Databricks
Scaling Security Threat Detection with Apache Spark and DatabricksScaling Security Threat Detection with Apache Spark and Databricks
Scaling Security Threat Detection with Apache Spark and Databricks
 
Grokking TechTalk #20: PostgreSQL Internals 101
Grokking TechTalk #20: PostgreSQL Internals 101Grokking TechTalk #20: PostgreSQL Internals 101
Grokking TechTalk #20: PostgreSQL Internals 101
 
How Totango uses Apache Spark
How Totango uses Apache SparkHow Totango uses Apache Spark
How Totango uses Apache Spark
 
Galene - LinkedIn's Search Architecture: Presented by Diego Buthay & Sriram S...
Galene - LinkedIn's Search Architecture: Presented by Diego Buthay & Sriram S...Galene - LinkedIn's Search Architecture: Presented by Diego Buthay & Sriram S...
Galene - LinkedIn's Search Architecture: Presented by Diego Buthay & Sriram S...
 
Migrating to spark 2.0
Migrating to spark 2.0Migrating to spark 2.0
Migrating to spark 2.0
 
Spark Summit EU talk by Oscar Castaneda
Spark Summit EU talk by Oscar CastanedaSpark Summit EU talk by Oscar Castaneda
Spark Summit EU talk by Oscar Castaneda
 
Introduction to Apache Spark 2.0
Introduction to Apache Spark 2.0Introduction to Apache Spark 2.0
Introduction to Apache Spark 2.0
 
Spark Summit EU talk by Kent Buenaventura and Willaim Lau
Spark Summit EU talk by Kent Buenaventura and Willaim LauSpark Summit EU talk by Kent Buenaventura and Willaim Lau
Spark Summit EU talk by Kent Buenaventura and Willaim Lau
 

Similar to Writing Recursive Queries

Oracle SQL Tuning for Day-to-Day Data Warehouse Support
Oracle SQL Tuning for Day-to-Day Data Warehouse SupportOracle SQL Tuning for Day-to-Day Data Warehouse Support
Oracle SQL Tuning for Day-to-Day Data Warehouse Supportnkarag
 
Introduction to SQL++ for Big Data: Same Language, More Power
Introduction to SQL++ for Big Data: Same Language, More PowerIntroduction to SQL++ for Big Data: Same Language, More Power
Introduction to SQL++ for Big Data: Same Language, More PowerAll Things Open
 
Ten query tuning techniques every SQL Server programmer should know
Ten query tuning techniques every SQL Server programmer should knowTen query tuning techniques every SQL Server programmer should know
Ten query tuning techniques every SQL Server programmer should knowKevin Kline
 
20180929 jssug 10_a5_sql_mk2
20180929 jssug 10_a5_sql_mk220180929 jssug 10_a5_sql_mk2
20180929 jssug 10_a5_sql_mk2Kunihisa Abukawa
 
Performance Stability, Tips and Tricks and Underscores
Performance Stability, Tips and Tricks and UnderscoresPerformance Stability, Tips and Tricks and Underscores
Performance Stability, Tips and Tricks and UnderscoresJitendra Singh
 
Jean-René Roy : The Modern DBA
Jean-René Roy : The Modern DBAJean-René Roy : The Modern DBA
Jean-René Roy : The Modern DBAMSDEVMTL
 
Understanding Query Plans and Spark UIs
Understanding Query Plans and Spark UIsUnderstanding Query Plans and Spark UIs
Understanding Query Plans and Spark UIsDatabricks
 
Deep Dive into Spark SQL with Advanced Performance Tuning with Xiao Li & Wenc...
Deep Dive into Spark SQL with Advanced Performance Tuning with Xiao Li & Wenc...Deep Dive into Spark SQL with Advanced Performance Tuning with Xiao Li & Wenc...
Deep Dive into Spark SQL with Advanced Performance Tuning with Xiao Li & Wenc...Databricks
 
ETL for the masses with Power Query and M
ETL for the masses with Power Query and METL for the masses with Power Query and M
ETL for the masses with Power Query and MRégis Baccaro
 
oracle plsql training | oracle online training | oracle plsql demo | oracle p...
oracle plsql training | oracle online training | oracle plsql demo | oracle p...oracle plsql training | oracle online training | oracle plsql demo | oracle p...
oracle plsql training | oracle online training | oracle plsql demo | oracle p...Nancy Thomas
 
SQLServerDays2012_SSIS_CDC
SQLServerDays2012_SSIS_CDCSQLServerDays2012_SSIS_CDC
SQLServerDays2012_SSIS_CDCKoenVerbeeck
 
122 sql for-beginners
122 sql for-beginners122 sql for-beginners
122 sql for-beginnerssuzzanj1990
 
The Polyglot Data Scientist - Exploring R, Python, and SQL Server
The Polyglot Data Scientist - Exploring R, Python, and SQL ServerThe Polyglot Data Scientist - Exploring R, Python, and SQL Server
The Polyglot Data Scientist - Exploring R, Python, and SQL ServerSarah Dutkiewicz
 
ГАННА КАПЛУН «noSQL vs SQL: порівняння використання реляційних та нереляційни...
ГАННА КАПЛУН «noSQL vs SQL: порівняння використання реляційних та нереляційни...ГАННА КАПЛУН «noSQL vs SQL: порівняння використання реляційних та нереляційни...
ГАННА КАПЛУН «noSQL vs SQL: порівняння використання реляційних та нереляційни...GoQA
 
Webinar: Migrating from RDBMS to MongoDB
Webinar: Migrating from RDBMS to MongoDBWebinar: Migrating from RDBMS to MongoDB
Webinar: Migrating from RDBMS to MongoDBMongoDB
 
Relational data modeling trends for transactional applications
Relational data modeling trends for transactional applicationsRelational data modeling trends for transactional applications
Relational data modeling trends for transactional applicationsIke Ellis
 
An Approach to Sql tuning - Part 1
An Approach to Sql tuning - Part 1An Approach to Sql tuning - Part 1
An Approach to Sql tuning - Part 1Navneet Upneja
 

Similar to Writing Recursive Queries (20)

SQL Tuning 101
SQL Tuning 101SQL Tuning 101
SQL Tuning 101
 
sqltuning101-170419021007-2.pdf
sqltuning101-170419021007-2.pdfsqltuning101-170419021007-2.pdf
sqltuning101-170419021007-2.pdf
 
Oracle SQL Tuning for Day-to-Day Data Warehouse Support
Oracle SQL Tuning for Day-to-Day Data Warehouse SupportOracle SQL Tuning for Day-to-Day Data Warehouse Support
Oracle SQL Tuning for Day-to-Day Data Warehouse Support
 
Introduction to SQL++ for Big Data: Same Language, More Power
Introduction to SQL++ for Big Data: Same Language, More PowerIntroduction to SQL++ for Big Data: Same Language, More Power
Introduction to SQL++ for Big Data: Same Language, More Power
 
Ten query tuning techniques every SQL Server programmer should know
Ten query tuning techniques every SQL Server programmer should knowTen query tuning techniques every SQL Server programmer should know
Ten query tuning techniques every SQL Server programmer should know
 
20180929 jssug 10_a5_sql_mk2
20180929 jssug 10_a5_sql_mk220180929 jssug 10_a5_sql_mk2
20180929 jssug 10_a5_sql_mk2
 
Performance Stability, Tips and Tricks and Underscores
Performance Stability, Tips and Tricks and UnderscoresPerformance Stability, Tips and Tricks and Underscores
Performance Stability, Tips and Tricks and Underscores
 
Jean-René Roy : The Modern DBA
Jean-René Roy : The Modern DBAJean-René Roy : The Modern DBA
Jean-René Roy : The Modern DBA
 
Understanding Query Plans and Spark UIs
Understanding Query Plans and Spark UIsUnderstanding Query Plans and Spark UIs
Understanding Query Plans and Spark UIs
 
Deep Dive into Spark SQL with Advanced Performance Tuning with Xiao Li & Wenc...
Deep Dive into Spark SQL with Advanced Performance Tuning with Xiao Li & Wenc...Deep Dive into Spark SQL with Advanced Performance Tuning with Xiao Li & Wenc...
Deep Dive into Spark SQL with Advanced Performance Tuning with Xiao Li & Wenc...
 
ETL for the masses with Power Query and M
ETL for the masses with Power Query and METL for the masses with Power Query and M
ETL for the masses with Power Query and M
 
oracle plsql training | oracle online training | oracle plsql demo | oracle p...
oracle plsql training | oracle online training | oracle plsql demo | oracle p...oracle plsql training | oracle online training | oracle plsql demo | oracle p...
oracle plsql training | oracle online training | oracle plsql demo | oracle p...
 
SQLServerDays2012_SSIS_CDC
SQLServerDays2012_SSIS_CDCSQLServerDays2012_SSIS_CDC
SQLServerDays2012_SSIS_CDC
 
122 sql for-beginners
122 sql for-beginners122 sql for-beginners
122 sql for-beginners
 
JSSUG: SQL Sever Index Tuning
JSSUG: SQL Sever Index TuningJSSUG: SQL Sever Index Tuning
JSSUG: SQL Sever Index Tuning
 
The Polyglot Data Scientist - Exploring R, Python, and SQL Server
The Polyglot Data Scientist - Exploring R, Python, and SQL ServerThe Polyglot Data Scientist - Exploring R, Python, and SQL Server
The Polyglot Data Scientist - Exploring R, Python, and SQL Server
 
ГАННА КАПЛУН «noSQL vs SQL: порівняння використання реляційних та нереляційни...
ГАННА КАПЛУН «noSQL vs SQL: порівняння використання реляційних та нереляційни...ГАННА КАПЛУН «noSQL vs SQL: порівняння використання реляційних та нереляційни...
ГАННА КАПЛУН «noSQL vs SQL: порівняння використання реляційних та нереляційни...
 
Webinar: Migrating from RDBMS to MongoDB
Webinar: Migrating from RDBMS to MongoDBWebinar: Migrating from RDBMS to MongoDB
Webinar: Migrating from RDBMS to MongoDB
 
Relational data modeling trends for transactional applications
Relational data modeling trends for transactional applicationsRelational data modeling trends for transactional applications
Relational data modeling trends for transactional applications
 
An Approach to Sql tuning - Part 1
An Approach to Sql tuning - Part 1An Approach to Sql tuning - Part 1
An Approach to Sql tuning - Part 1
 

Recently uploaded

Indian Call Girls in Abu Dhabi O5286O24O8 Call Girls in Abu Dhabi By Independ...
Indian Call Girls in Abu Dhabi O5286O24O8 Call Girls in Abu Dhabi By Independ...Indian Call Girls in Abu Dhabi O5286O24O8 Call Girls in Abu Dhabi By Independ...
Indian Call Girls in Abu Dhabi O5286O24O8 Call Girls in Abu Dhabi By Independ...dajasot375
 
꧁❤ Greater Noida Call Girls Delhi ❤꧂ 9711199171 ☎️ Hard And Sexy Vip Call
꧁❤ Greater Noida Call Girls Delhi ❤꧂ 9711199171 ☎️ Hard And Sexy Vip Call꧁❤ Greater Noida Call Girls Delhi ❤꧂ 9711199171 ☎️ Hard And Sexy Vip Call
꧁❤ Greater Noida Call Girls Delhi ❤꧂ 9711199171 ☎️ Hard And Sexy Vip Callshivangimorya083
 
Ukraine War presentation: KNOW THE BASICS
Ukraine War presentation: KNOW THE BASICSUkraine War presentation: KNOW THE BASICS
Ukraine War presentation: KNOW THE BASICSAishani27
 
Market Analysis in the 5 Largest Economic Countries in Southeast Asia.pdf
Market Analysis in the 5 Largest Economic Countries in Southeast Asia.pdfMarket Analysis in the 5 Largest Economic Countries in Southeast Asia.pdf
Market Analysis in the 5 Largest Economic Countries in Southeast Asia.pdfRachmat Ramadhan H
 
EMERCE - 2024 - AMSTERDAM - CROSS-PLATFORM TRACKING WITH GOOGLE ANALYTICS.pptx
EMERCE - 2024 - AMSTERDAM - CROSS-PLATFORM  TRACKING WITH GOOGLE ANALYTICS.pptxEMERCE - 2024 - AMSTERDAM - CROSS-PLATFORM  TRACKING WITH GOOGLE ANALYTICS.pptx
EMERCE - 2024 - AMSTERDAM - CROSS-PLATFORM TRACKING WITH GOOGLE ANALYTICS.pptxthyngster
 
Delhi Call Girls Punjabi Bagh 9711199171 ☎✔👌✔ Whatsapp Hard And Sexy Vip Call
Delhi Call Girls Punjabi Bagh 9711199171 ☎✔👌✔ Whatsapp Hard And Sexy Vip CallDelhi Call Girls Punjabi Bagh 9711199171 ☎✔👌✔ Whatsapp Hard And Sexy Vip Call
Delhi Call Girls Punjabi Bagh 9711199171 ☎✔👌✔ Whatsapp Hard And Sexy Vip Callshivangimorya083
 
Delhi Call Girls CP 9711199171 ☎✔👌✔ Whatsapp Hard And Sexy Vip Call
Delhi Call Girls CP 9711199171 ☎✔👌✔ Whatsapp Hard And Sexy Vip CallDelhi Call Girls CP 9711199171 ☎✔👌✔ Whatsapp Hard And Sexy Vip Call
Delhi Call Girls CP 9711199171 ☎✔👌✔ Whatsapp Hard And Sexy Vip Callshivangimorya083
 
High Class Call Girls Noida Sector 39 Aarushi 🔝8264348440🔝 Independent Escort...
High Class Call Girls Noida Sector 39 Aarushi 🔝8264348440🔝 Independent Escort...High Class Call Girls Noida Sector 39 Aarushi 🔝8264348440🔝 Independent Escort...
High Class Call Girls Noida Sector 39 Aarushi 🔝8264348440🔝 Independent Escort...soniya singh
 
Full night 🥵 Call Girls Delhi New Friends Colony {9711199171} Sanya Reddy ✌️o...
Full night 🥵 Call Girls Delhi New Friends Colony {9711199171} Sanya Reddy ✌️o...Full night 🥵 Call Girls Delhi New Friends Colony {9711199171} Sanya Reddy ✌️o...
Full night 🥵 Call Girls Delhi New Friends Colony {9711199171} Sanya Reddy ✌️o...shivangimorya083
 
代办国外大学文凭《原版美国UCLA文凭证书》加州大学洛杉矶分校毕业证制作成绩单修改
代办国外大学文凭《原版美国UCLA文凭证书》加州大学洛杉矶分校毕业证制作成绩单修改代办国外大学文凭《原版美国UCLA文凭证书》加州大学洛杉矶分校毕业证制作成绩单修改
代办国外大学文凭《原版美国UCLA文凭证书》加州大学洛杉矶分校毕业证制作成绩单修改atducpo
 
VIP Call Girls in Amravati Aarohi 8250192130 Independent Escort Service Amravati
VIP Call Girls in Amravati Aarohi 8250192130 Independent Escort Service AmravatiVIP Call Girls in Amravati Aarohi 8250192130 Independent Escort Service Amravati
VIP Call Girls in Amravati Aarohi 8250192130 Independent Escort Service AmravatiSuhani Kapoor
 
Industrialised data - the key to AI success.pdf
Industrialised data - the key to AI success.pdfIndustrialised data - the key to AI success.pdf
Industrialised data - the key to AI success.pdfLars Albertsson
 
RA-11058_IRR-COMPRESS Do 198 series of 1998
RA-11058_IRR-COMPRESS Do 198 series of 1998RA-11058_IRR-COMPRESS Do 198 series of 1998
RA-11058_IRR-COMPRESS Do 198 series of 1998YohFuh
 
FESE Capital Markets Fact Sheet 2024 Q1.pdf
FESE Capital Markets Fact Sheet 2024 Q1.pdfFESE Capital Markets Fact Sheet 2024 Q1.pdf
FESE Capital Markets Fact Sheet 2024 Q1.pdfMarinCaroMartnezBerg
 
VIP Call Girls Service Miyapur Hyderabad Call +91-8250192130
VIP Call Girls Service Miyapur Hyderabad Call +91-8250192130VIP Call Girls Service Miyapur Hyderabad Call +91-8250192130
VIP Call Girls Service Miyapur Hyderabad Call +91-8250192130Suhani Kapoor
 
Schema on read is obsolete. Welcome metaprogramming..pdf
Schema on read is obsolete. Welcome metaprogramming..pdfSchema on read is obsolete. Welcome metaprogramming..pdf
Schema on read is obsolete. Welcome metaprogramming..pdfLars Albertsson
 
Log Analysis using OSSEC sasoasasasas.pptx
Log Analysis using OSSEC sasoasasasas.pptxLog Analysis using OSSEC sasoasasasas.pptx
Log Analysis using OSSEC sasoasasasas.pptxJohnnyPlasten
 
Unveiling Insights: The Role of a Data Analyst
Unveiling Insights: The Role of a Data AnalystUnveiling Insights: The Role of a Data Analyst
Unveiling Insights: The Role of a Data AnalystSamantha Rae Coolbeth
 
Aminabad Call Girl Agent 9548273370 , Call Girls Service Lucknow
Aminabad Call Girl Agent 9548273370 , Call Girls Service LucknowAminabad Call Girl Agent 9548273370 , Call Girls Service Lucknow
Aminabad Call Girl Agent 9548273370 , Call Girls Service Lucknowmakika9823
 

Recently uploaded (20)

Indian Call Girls in Abu Dhabi O5286O24O8 Call Girls in Abu Dhabi By Independ...
Indian Call Girls in Abu Dhabi O5286O24O8 Call Girls in Abu Dhabi By Independ...Indian Call Girls in Abu Dhabi O5286O24O8 Call Girls in Abu Dhabi By Independ...
Indian Call Girls in Abu Dhabi O5286O24O8 Call Girls in Abu Dhabi By Independ...
 
꧁❤ Greater Noida Call Girls Delhi ❤꧂ 9711199171 ☎️ Hard And Sexy Vip Call
꧁❤ Greater Noida Call Girls Delhi ❤꧂ 9711199171 ☎️ Hard And Sexy Vip Call꧁❤ Greater Noida Call Girls Delhi ❤꧂ 9711199171 ☎️ Hard And Sexy Vip Call
꧁❤ Greater Noida Call Girls Delhi ❤꧂ 9711199171 ☎️ Hard And Sexy Vip Call
 
Ukraine War presentation: KNOW THE BASICS
Ukraine War presentation: KNOW THE BASICSUkraine War presentation: KNOW THE BASICS
Ukraine War presentation: KNOW THE BASICS
 
Market Analysis in the 5 Largest Economic Countries in Southeast Asia.pdf
Market Analysis in the 5 Largest Economic Countries in Southeast Asia.pdfMarket Analysis in the 5 Largest Economic Countries in Southeast Asia.pdf
Market Analysis in the 5 Largest Economic Countries in Southeast Asia.pdf
 
EMERCE - 2024 - AMSTERDAM - CROSS-PLATFORM TRACKING WITH GOOGLE ANALYTICS.pptx
EMERCE - 2024 - AMSTERDAM - CROSS-PLATFORM  TRACKING WITH GOOGLE ANALYTICS.pptxEMERCE - 2024 - AMSTERDAM - CROSS-PLATFORM  TRACKING WITH GOOGLE ANALYTICS.pptx
EMERCE - 2024 - AMSTERDAM - CROSS-PLATFORM TRACKING WITH GOOGLE ANALYTICS.pptx
 
Delhi Call Girls Punjabi Bagh 9711199171 ☎✔👌✔ Whatsapp Hard And Sexy Vip Call
Delhi Call Girls Punjabi Bagh 9711199171 ☎✔👌✔ Whatsapp Hard And Sexy Vip CallDelhi Call Girls Punjabi Bagh 9711199171 ☎✔👌✔ Whatsapp Hard And Sexy Vip Call
Delhi Call Girls Punjabi Bagh 9711199171 ☎✔👌✔ Whatsapp Hard And Sexy Vip Call
 
Delhi Call Girls CP 9711199171 ☎✔👌✔ Whatsapp Hard And Sexy Vip Call
Delhi Call Girls CP 9711199171 ☎✔👌✔ Whatsapp Hard And Sexy Vip CallDelhi Call Girls CP 9711199171 ☎✔👌✔ Whatsapp Hard And Sexy Vip Call
Delhi Call Girls CP 9711199171 ☎✔👌✔ Whatsapp Hard And Sexy Vip Call
 
High Class Call Girls Noida Sector 39 Aarushi 🔝8264348440🔝 Independent Escort...
High Class Call Girls Noida Sector 39 Aarushi 🔝8264348440🔝 Independent Escort...High Class Call Girls Noida Sector 39 Aarushi 🔝8264348440🔝 Independent Escort...
High Class Call Girls Noida Sector 39 Aarushi 🔝8264348440🔝 Independent Escort...
 
Full night 🥵 Call Girls Delhi New Friends Colony {9711199171} Sanya Reddy ✌️o...
Full night 🥵 Call Girls Delhi New Friends Colony {9711199171} Sanya Reddy ✌️o...Full night 🥵 Call Girls Delhi New Friends Colony {9711199171} Sanya Reddy ✌️o...
Full night 🥵 Call Girls Delhi New Friends Colony {9711199171} Sanya Reddy ✌️o...
 
代办国外大学文凭《原版美国UCLA文凭证书》加州大学洛杉矶分校毕业证制作成绩单修改
代办国外大学文凭《原版美国UCLA文凭证书》加州大学洛杉矶分校毕业证制作成绩单修改代办国外大学文凭《原版美国UCLA文凭证书》加州大学洛杉矶分校毕业证制作成绩单修改
代办国外大学文凭《原版美国UCLA文凭证书》加州大学洛杉矶分校毕业证制作成绩单修改
 
VIP Call Girls in Amravati Aarohi 8250192130 Independent Escort Service Amravati
VIP Call Girls in Amravati Aarohi 8250192130 Independent Escort Service AmravatiVIP Call Girls in Amravati Aarohi 8250192130 Independent Escort Service Amravati
VIP Call Girls in Amravati Aarohi 8250192130 Independent Escort Service Amravati
 
Industrialised data - the key to AI success.pdf
Industrialised data - the key to AI success.pdfIndustrialised data - the key to AI success.pdf
Industrialised data - the key to AI success.pdf
 
RA-11058_IRR-COMPRESS Do 198 series of 1998
RA-11058_IRR-COMPRESS Do 198 series of 1998RA-11058_IRR-COMPRESS Do 198 series of 1998
RA-11058_IRR-COMPRESS Do 198 series of 1998
 
FESE Capital Markets Fact Sheet 2024 Q1.pdf
FESE Capital Markets Fact Sheet 2024 Q1.pdfFESE Capital Markets Fact Sheet 2024 Q1.pdf
FESE Capital Markets Fact Sheet 2024 Q1.pdf
 
VIP Call Girls Service Miyapur Hyderabad Call +91-8250192130
VIP Call Girls Service Miyapur Hyderabad Call +91-8250192130VIP Call Girls Service Miyapur Hyderabad Call +91-8250192130
VIP Call Girls Service Miyapur Hyderabad Call +91-8250192130
 
Schema on read is obsolete. Welcome metaprogramming..pdf
Schema on read is obsolete. Welcome metaprogramming..pdfSchema on read is obsolete. Welcome metaprogramming..pdf
Schema on read is obsolete. Welcome metaprogramming..pdf
 
Log Analysis using OSSEC sasoasasasas.pptx
Log Analysis using OSSEC sasoasasasas.pptxLog Analysis using OSSEC sasoasasasas.pptx
Log Analysis using OSSEC sasoasasasas.pptx
 
Unveiling Insights: The Role of a Data Analyst
Unveiling Insights: The Role of a Data AnalystUnveiling Insights: The Role of a Data Analyst
Unveiling Insights: The Role of a Data Analyst
 
Delhi 99530 vip 56974 Genuine Escort Service Call Girls in Kishangarh
Delhi 99530 vip 56974 Genuine Escort Service Call Girls in  KishangarhDelhi 99530 vip 56974 Genuine Escort Service Call Girls in  Kishangarh
Delhi 99530 vip 56974 Genuine Escort Service Call Girls in Kishangarh
 
Aminabad Call Girl Agent 9548273370 , Call Girls Service Lucknow
Aminabad Call Girl Agent 9548273370 , Call Girls Service LucknowAminabad Call Girl Agent 9548273370 , Call Girls Service Lucknow
Aminabad Call Girl Agent 9548273370 , Call Girls Service Lucknow
 

Writing Recursive Queries

  • 1. WRITING RECURSIVE QUERIES RETRIEVING HIERARCHY DATA FROM RELATIONAL TABLES BEN LIS POSTGRESCONF US 2019
  • 2. IS THIS TALK RIGHT FOR YOU? What we will cover • Why we need recursive queries • How they work • How to write them What you should know • Basic knowledge of SQL through outer joins • General programming concepts • Slides and SQL: https://github.com/benjlis/talk-writing-recursive- queries 2
  • 3. ABOUT ME • Data Engineer at LEI Smart • Writes recursive queries on corporate hierarchy data • Initially found recursive SQL a bit confusing • Using PostgreSQL since 2015 • Started working with Oracle databases in 1988! • Adjunct Associate Faculty in Applied Analytics at Columbia University • Held various technical, product, and management roles on Wall Street • LinkedIn and Twitter 3
  • 4. AGENDA • Motivation • Understanding Recursive SQL • Writing Recursive Queries • Next Steps • Questions & Discussion 4
  • 5. MOTIVATION WHY WE NEED RECURSIVE SQL 5
  • 7. LET’S QUERY EMPLOYEES, THEIR BOSS & THE BOSS'S BOSS boss-queries.sql 7
  • 9. IDEA 1: EXTEND CURRENT APPROACH “Add a few more JOINs” Need to know the number of hierarchy levels in advance Not realistic or robust! 9
  • 10. IDEA 2: WRITE A PROGRAM Use Python, Java, PL/pgSQL, etc. Query all employees For each employee get their boss’s record and then their boss’s boss’s record, etc. until you get a NULL Complex and resource consumptive! 10
  • 11. SHOULDN’T WE BE ABLE TO WRITE THIS QUERY IN SQL? 11
  • 12. WE SHOULD BE ABLE TO WRITE THIS QUERY IN SQL • In the early days (decades) of SQL & relational databases we couldn’t • Writing a program (Idea 2) was the only solution • Other names for the hierarchy problem: • Transitive Closure • Bill of Materials • Parts Explosion • Good news: We can write this query in modern SQL using recursive SQL! 12
  • 13. UNDERSTANDING RECURSIVE SQL KEY IDEAS, CTE, SYNTAX, STRUCTURE & EVALUATION 13
  • 14. RECURSIVE SQL SUPPORT Part of ISO Standard SQL Introduced in SQL:1999 (aka SQL 3) Supported in PostgreSQL Oracle SQL Server DB2 14
  • 15. KEY IDEAS • re·cur·sive /rəˈkərsiv/: a program or routine of which a part requires the application of the whole, so that its explicit interpretation requires in general many successive executions • Self-referencing • Your Bosses = Your Manager + Your Manager’s Bosses • Recursive SQL is an iterative process • Think while loops • But SQL is declarative!!!! • Tip: Put aside knowledge of recursion in programming • Recursive SQL uses Common Table Expressions (CTEs) 15
  • 16. COMMON TABLE EXPRESSION (CTE) EXAMPLE cte.sql • Primarily used to simplify queries • Think of as inline view(s) 16
  • 17. RECURSIVE CTE STRUCTURE • Keyword: recursive • Always a UNION or UNION ALL of • Non-recursive select • Recursive select 17
  • 18. NON-RECURSIVE SELECT • Evaluated 1st - where we start • FROM clause: • Must not refer to <cte-name> • Refers to table containing hierarchy 18
  • 19. RECURSIVE SELECT • Evaluated 2..N times • FROM clause: • Must reference <cte-name> • Join of the <cte-name> and table containing hierarchy • N is a function of the data and the recursive select’s where clause 19
  • 20. RECURSIVE CTE EVALUATION QR = Query Results; WT = Working Table Both initially empty 1. Execute <non-recursive select> 2. Add results to QR and WT 3. Repeat until WT is empty a. Execute <recursive select> using WT data for <cte-name> b. Add results to QR c. Replace WT with results 20
  • 21. WRITING RECURSIVE QUERIES LET’S GET DOWN TO IT! 21
  • 22. WHAT IS ADAMS REPORTING LINE? rl.sql 22
  • 23. ALL EMPLOYEES FROM CEO TO ENTRY LEVEL oc.sql 23
  • 26. NEXT STEPS RECOMMENDED READINGS & BEYOND HIERARCHY 26
  • 27. RECOMMENDED READINGS • PostgreSQL documentation • Fun with SQL: Recursive CTEs in Postgres – Craig Kerstiens • Modern SQL in Open Source and Commercial Databases (slides 45-60) – Markus Winand • Exporting a Hierarchy in JSON: with recursive queries - Dmitri Fontaine • Joe Celko’s Trees and Hierarchies in SQL for Smarties (Book) 27
  • 28. BEYOND HIERARCHY • Hierarchy queries are the most common application of recursive SQL, but not the only application! • Pretty wild recursive SQL queries: • Solving the Traveling Salesman Problem with Postgres Recursive CTEs - Periscope Data • Mandelbrot Set • tic-tac-toe • My views: • Can doesn’t mean should • Worth studying for learning advanced techniques 28