SlideShare uma empresa Scribd logo
1 de 34
Baixar para ler offline
Trees and More
            With PostgreSQL
   Common Table Expressions
   Percona Conference 2009


Copyright © 2009
David Fetter david.fetter@pgexperts.com
All Rights Reserved
Some Approaches

• External Processing
• Functions and Stored Procedures
• Materialized Path Enumeration
• Nested Set
External Processing

•   Pros:

    •   Lots of Language Choices

•   Cons:

    •   Scaling

    •   No Relational Operators
Functions and Stored
            Procedures
•   Pros:

    •   Easy to visualize

    •   Easy to write

•   Cons:

    •   Scaling

    •   Hard to do relational operators
Materialized Path Enumeration

  •   Pros:

      •   Easy to visualize

  •   Cons:

      •   DDL for each hierarchy

      •   Full-table changes on write

      •   Hard to do relational operators
Nested Sets
•   Pros:

    •   Easy to manipulate on SELECT

    •   Sounds cool

    •   Endorsed by a famous bald guy

•   Cons:

    •   DDL for each hierarchy

    •   Full-table changes on write

    •   Hard to do relational operators
Thanks to:
•   The ISO SQL Standards Committee

•   Yoshiyuki Asaba

•   Ishii Tatsuo

•   Jeff Davis

•   Gregory Stark

•   Tom Lane

•   etc., etc., etc.
SQL Standard


• Common Table Expressions
 (CTE)
Recursion
Recursion in General

•
Initial Condition
•
Recursion step
•
Termination
condition
E1 List Table
CREATE TABLE employee(
    id INTEGER NOT NULL,
    boss_id INTEGER,
    UNIQUE(id, boss_id)/*, etc., etc. */
);

INSERT INTO employee(id, boss_id)
VALUES(1,NULL), /* El capo di tutti capi */
(2,1),(3,1),(4,1),
(5,2),(6,2),(7,2),(8,3),(9,3),(10,4),
(11,5),(12,5),(13,6),(14,7),(15,8),
(1,9);
Tree Query Initiation
WITH RECURSIVE t(node, path) AS (
   SELECT id, ARRAY[id] FROM employee WHERE boss_id IS NULL
   /* Initiation Step */
UNION ALL
    SELECT e1.id, t.path || ARRAY[e1.id]
    FROM employee e1 JOIN t ON (e1.boss_id = t.node)
    WHERE id NOT IN (t.path)
)
SELECT
    CASE WHEN array_upper(path,1)>1 THEN '+-' ELSE '' END ||
    REPEAT('--', array_upper(path,1)-2) ||
    node AS quot;Branchquot;
FROM t
ORDER BY path;
Tree Query Recursion
WITH RECURSIVE t(node, path) AS (
   SELECT id, ARRAY[id] FROM employee WHERE boss_id IS NULL
UNION ALL
    SELECT e1.id, t.path || ARRAY[e1.id] /* Recursion */
    FROM employee e1 JOIN t ON (e1.boss_id = t.node)
    WHERE id NOT IN (t.path)
)
SELECT
    CASE WHEN array_upper(path,1)>1 THEN '+-' ELSE '' END ||
    REPEAT('--', array_upper(path,1)-2) ||
    node AS quot;Branchquot;
FROM t
ORDER BY path;
Tree Query
                 Termination
WITH RECURSIVE t(node, path) AS (
    SELECT id, ARRAY[id] FROM employee WHERE boss_id IS NULL
UNION ALL
    SELECT e1.id, t.path || ARRAY[e1.id]
    FROM employee e1 JOIN t ON (e1.boss_id = t.node)
    WHERE id NOT IN (t.path) /* Termination Condition */
)
SELECT
    CASE WHEN array_upper(path,1)>1 THEN '+-' ELSE '' END ||
    REPEAT('--', array_upper(path,1)-2) ||
    node AS quot;Branchquot;
FROM t
ORDER BY path;
Tree Query Display
WITH RECURSIVE t(node, path) AS (
   SELECT id, ARRAY[id] FROM employee WHERE boss_id IS NULL
UNION ALL
    SELECT e1.id, t.path || ARRAY[e1.id]
    FROM employee e1 JOIN t ON (e1.boss_id = t.node)
    WHERE id NOT IN (t.path)
)
SELECT
    CASE WHEN array_upper(path,1)>1 THEN '+-' ELSE '' END ||
    REPEAT('--', array_upper(path,1)-2) ||
    node AS quot;Branchquot; /* Display */
FROM t
ORDER BY path;
Tree Query Initiation
           Branch
        ----------
         1
         +-2
         +---5
         +-----11
         +-----12
         +---6
         +-----13
         +---7
         +-----14
         +-3
         +---8
         +-----15
         +---9
         +-4
         +---10
         +-9
        (16 rows)
Travelling Salesman Problem
Given a number of cities and the costs of travelling
from any city to any other city, what is the least-
cost round-trip route that visits each city exactly
once and then returns to the starting city?
TSP Schema
CREATE TABLE pairs (
    from_city TEXT NOT NULL,
    to_city TEXT NOT NULL,
    distance INTEGER NOT NULL,
    PRIMARY KEY(from_city, to_city),
    CHECK (from_city < to_city)
);
TSP Data
INSERT INTO pairs
VALUES
    ('Bari','Bologna',672),
    ('Bari','Bolzano',939),
    ('Bari','Firenze',723),
    ('Bari','Genova',944),
    ('Bari','Milan',881),
    ('Bari','Napoli',257),
    ('Bari','Palermo',708),
    ('Bari','Reggio Calabria',464),
    ....
TSP Program:
     Symmetric Setup

 WITH RECURSIVE both_ways(
      from_city,
      to_city,
      distance
 )           /* Working Table */
 AS (
      SELECT
           from_city,
           to_city,
           distance
      FROM
           pairs
 UNION ALL
      SELECT
           to_city AS quot;from_cityquot;,
           from_city AS quot;to_cityquot;,
           distance
      FROM
           pairs
 ),
TSP Program:
     Symmetric Setup

 WITH RECURSIVE both_ways(
     from_city,
     to_city,
     distance
 )
 AS (/* Distances One Way */
     SELECT
          from_city,
          to_city,
          distance
     FROM
          pairs
 UNION ALL
     SELECT
          to_city AS quot;from_cityquot;,
          from_city AS quot;to_cityquot;,
          distance
     FROM
          pairs
 ),
TSP Program:
    Symmetric Setup

 WITH RECURSIVE both_ways(
      from_city,
      to_city,
      distance
 )
 AS (
      SELECT
           from_city,
           to_city,
           distance
      FROM
           pairs
 UNION ALL /* Distances Other Way */
      SELECT
           to_city AS quot;from_cityquot;,
           from_city AS quot;to_cityquot;,
           distance
      FROM
           pairs
 ),
TSP Program:
      Path Initialization Step
paths (
     from_city,
     to_city,
     distance,
     path
)
AS (
     SELECT
          from_city,
          to_city,
          distance,
          ARRAY[from_city] AS quot;pathquot;
     FROM
          both_ways b1
     WHERE
          b1.from_city = 'Roma'
UNION ALL
TSP Program:
             Path Recursion Step

    SELECT
         b2.from_city,
         b2.to_city,
         p.distance + b2.distance,
         p.path || b2.from_city
    FROM
         both_ways b2
    JOIN
         paths p
         ON (
              p.to_city = b2.from_city
         AND
              b2.from_city <> ALL (p.path[
                  2:array_upper(p.path,1)
              ]) /* Prevent re-tracing */
         AND
              array_upper(p.path,1) < 6
         )
)
TSP Program:
          Timely Termination Step

    SELECT
         b2.from_city,
         b2.to_city,
         p.distance + b2.distance,
         p.path || b2.from_city
    FROM
         both_ways b2
    JOIN
         paths p
         ON (
              p.to_city = b2.from_city
         AND
              b2.from_city <> ALL (p.path[
                  2:array_upper(p.path,1)
              ]) /* Prevent re-tracing */
         AND
              array_upper(p.path,1) < 6 /* Timely Termination */
         )
)
TSP Program:
               Filter and Display

SELECT
     path || to_city AS quot;pathquot;,
     distance
FROM
     paths
WHERE
     to_city = 'Roma'
AND
     ARRAY['Milan','Firenze','Napoli'] <@ path
ORDER BY distance, path
LIMIT 1;
TSP Program:
                 Filter and Display



davidfetter@tsp=# i travelling_salesman.sql
               path               | distance
----------------------------------+----------
 {Roma,Firenze,Milan,Napoli,Roma} |     1553
(1 row)

Time: 11679.503 ms
Hausdorf-Besicovich-
          WTF Dimension
WITH RECURSIVE
Z(Ix, Iy, Cx, Cy, X, Y, I)
AS (
     SELECT Ix, Iy, X::float, Y::float, X::float, Y::float, 0
     FROM
          (SELECT -2.2 + 0.031 * i, i FROM generate_series(0,101) AS i) AS xgen(x,ix)
     CROSS JOIN
          (SELECT -1.5 + 0.031 * i, i FROM generate_series(0,101) AS i) AS ygen(y,iy)
     UNION ALL
     SELECT Ix, Iy, Cx, Cy, X * X - Y * Y + Cx AS X, Y * X * 2 + Cy, I + 1
     FROM Z
     WHERE X * X + Y * Y < 16::float
     AND I < 100
),
Filter
Zt (Ix, Iy, I) AS (
    SELECT Ix, Iy, MAX(I) AS I
    FROM Z
    GROUP BY Iy, Ix
    ORDER BY Iy, Ix
)
Display

SELECT array_to_string(
    array_agg(
         SUBSTRING(
             ' .,,,-----++++%%%%@@@@#### ',
             GREATEST(I,1)
    ),''
)
FROM Zt
GROUP BY Iy
ORDER BY Iy;
Return Map
Questions?
Comments?
Straitjackets?
Thanks!
Copyright © 2009
David Fetter david.fetter@pgexperts.com
All Rights Reserved

Mais conteúdo relacionado

Semelhante a Trees And More With Postgre S Q L

Go Says WAT?
Go Says WAT?Go Says WAT?
Go Says WAT?jonbodner
 
IAP presentation-1.pptx
IAP presentation-1.pptxIAP presentation-1.pptx
IAP presentation-1.pptxHirazNor
 
Taking Inspiration From The Functional World
Taking Inspiration From The Functional WorldTaking Inspiration From The Functional World
Taking Inspiration From The Functional WorldPiotr Solnica
 
-- Task 2- Debugging a program with stacks- queues- and doubly-linked.docx
-- Task 2- Debugging a program with stacks- queues- and doubly-linked.docx-- Task 2- Debugging a program with stacks- queues- and doubly-linked.docx
-- Task 2- Debugging a program with stacks- queues- and doubly-linked.docxAdamq0DJonese
 
Merge Sort implementation in C++ The implementation for Mergesort gi.pdf
Merge Sort implementation in C++ The implementation for Mergesort gi.pdfMerge Sort implementation in C++ The implementation for Mergesort gi.pdf
Merge Sort implementation in C++ The implementation for Mergesort gi.pdfmdameer02
 
From Javascript To Haskell
From Javascript To HaskellFrom Javascript To Haskell
From Javascript To Haskellujihisa
 
Nesting of for loops using C++
Nesting of for loops using C++Nesting of for loops using C++
Nesting of for loops using C++prashant_sainii
 
Company_X_Data_Analyst_Challenge
Company_X_Data_Analyst_ChallengeCompany_X_Data_Analyst_Challenge
Company_X_Data_Analyst_ChallengeMark Yashar
 
Using an Array include ltstdiohgt include ltmpih.pdf
Using an Array include ltstdiohgt include ltmpih.pdfUsing an Array include ltstdiohgt include ltmpih.pdf
Using an Array include ltstdiohgt include ltmpih.pdfgiriraj65
 
There are a number of errors in the following program- All errors are.docx
There are a number of errors in the following program- All errors are.docxThere are a number of errors in the following program- All errors are.docx
There are a number of errors in the following program- All errors are.docxclarkjanyce
 
Real-Time Analytics at Uber Scale
Real-Time Analytics at Uber ScaleReal-Time Analytics at Uber Scale
Real-Time Analytics at Uber ScaleSingleStore
 
Write a C++ program which generates and displays a random walk acros.pdf
Write a C++ program which generates and displays a random walk acros.pdfWrite a C++ program which generates and displays a random walk acros.pdf
Write a C++ program which generates and displays a random walk acros.pdfmckenziecast21211
 
IAP PPT-1.pptx
IAP PPT-1.pptxIAP PPT-1.pptx
IAP PPT-1.pptxHirazNor
 
Program In C You are required to write an interactive C program that.pdf
Program In C You are required to write an interactive C program that.pdfProgram In C You are required to write an interactive C program that.pdf
Program In C You are required to write an interactive C program that.pdfamitbagga0808
 
(Parent reference for BST) Redefine TreeNode by adding a reference to.pdf
(Parent reference for BST) Redefine TreeNode by adding a reference to.pdf(Parent reference for BST) Redefine TreeNode by adding a reference to.pdf
(Parent reference for BST) Redefine TreeNode by adding a reference to.pdfarihantelehyb
 
Migrating To Ruby1.9
Migrating To Ruby1.9Migrating To Ruby1.9
Migrating To Ruby1.9tomaspavelka
 

Semelhante a Trees And More With Postgre S Q L (20)

Go Says WAT?
Go Says WAT?Go Says WAT?
Go Says WAT?
 
Writeable CTEs: The Next Big Thing
Writeable CTEs: The Next Big ThingWriteable CTEs: The Next Big Thing
Writeable CTEs: The Next Big Thing
 
IAP presentation-1.pptx
IAP presentation-1.pptxIAP presentation-1.pptx
IAP presentation-1.pptx
 
Taking Inspiration From The Functional World
Taking Inspiration From The Functional WorldTaking Inspiration From The Functional World
Taking Inspiration From The Functional World
 
Quiz using C++
Quiz using C++Quiz using C++
Quiz using C++
 
-- Task 2- Debugging a program with stacks- queues- and doubly-linked.docx
-- Task 2- Debugging a program with stacks- queues- and doubly-linked.docx-- Task 2- Debugging a program with stacks- queues- and doubly-linked.docx
-- Task 2- Debugging a program with stacks- queues- and doubly-linked.docx
 
Merge Sort implementation in C++ The implementation for Mergesort gi.pdf
Merge Sort implementation in C++ The implementation for Mergesort gi.pdfMerge Sort implementation in C++ The implementation for Mergesort gi.pdf
Merge Sort implementation in C++ The implementation for Mergesort gi.pdf
 
From Javascript To Haskell
From Javascript To HaskellFrom Javascript To Haskell
From Javascript To Haskell
 
Nesting of for loops using C++
Nesting of for loops using C++Nesting of for loops using C++
Nesting of for loops using C++
 
Company_X_Data_Analyst_Challenge
Company_X_Data_Analyst_ChallengeCompany_X_Data_Analyst_Challenge
Company_X_Data_Analyst_Challenge
 
Using an Array include ltstdiohgt include ltmpih.pdf
Using an Array include ltstdiohgt include ltmpih.pdfUsing an Array include ltstdiohgt include ltmpih.pdf
Using an Array include ltstdiohgt include ltmpih.pdf
 
There are a number of errors in the following program- All errors are.docx
There are a number of errors in the following program- All errors are.docxThere are a number of errors in the following program- All errors are.docx
There are a number of errors in the following program- All errors are.docx
 
Real-Time Analytics at Uber Scale
Real-Time Analytics at Uber ScaleReal-Time Analytics at Uber Scale
Real-Time Analytics at Uber Scale
 
CPP Homework Help
CPP Homework HelpCPP Homework Help
CPP Homework Help
 
Write a C++ program which generates and displays a random walk acros.pdf
Write a C++ program which generates and displays a random walk acros.pdfWrite a C++ program which generates and displays a random walk acros.pdf
Write a C++ program which generates and displays a random walk acros.pdf
 
IAP PPT-1.pptx
IAP PPT-1.pptxIAP PPT-1.pptx
IAP PPT-1.pptx
 
Program In C You are required to write an interactive C program that.pdf
Program In C You are required to write an interactive C program that.pdfProgram In C You are required to write an interactive C program that.pdf
Program In C You are required to write an interactive C program that.pdf
 
(Parent reference for BST) Redefine TreeNode by adding a reference to.pdf
(Parent reference for BST) Redefine TreeNode by adding a reference to.pdf(Parent reference for BST) Redefine TreeNode by adding a reference to.pdf
(Parent reference for BST) Redefine TreeNode by adding a reference to.pdf
 
Groovy
GroovyGroovy
Groovy
 
Migrating To Ruby1.9
Migrating To Ruby1.9Migrating To Ruby1.9
Migrating To Ruby1.9
 

Mais de PerconaPerformance

Drizzles Approach To Improving Performance Of The Server
Drizzles  Approach To  Improving  Performance Of The  ServerDrizzles  Approach To  Improving  Performance Of The  Server
Drizzles Approach To Improving Performance Of The ServerPerconaPerformance
 
E M T Better Performance Monitoring
E M T  Better  Performance  MonitoringE M T  Better  Performance  Monitoring
E M T Better Performance MonitoringPerconaPerformance
 
Covering Indexes Ordersof Magnitude Improvements
Covering  Indexes  Ordersof Magnitude  ImprovementsCovering  Indexes  Ordersof Magnitude  Improvements
Covering Indexes Ordersof Magnitude ImprovementsPerconaPerformance
 
Automated Performance Testing With J Meter And Maven
Automated  Performance  Testing With  J Meter And  MavenAutomated  Performance  Testing With  J Meter And  Maven
Automated Performance Testing With J Meter And MavenPerconaPerformance
 
Galera Multi Master Synchronous My S Q L Replication Clusters
Galera  Multi Master  Synchronous  My S Q L  Replication  ClustersGalera  Multi Master  Synchronous  My S Q L  Replication  Clusters
Galera Multi Master Synchronous My S Q L Replication ClustersPerconaPerformance
 
My S Q L Replication Getting The Most From Slaves
My S Q L  Replication  Getting  The  Most  From  SlavesMy S Q L  Replication  Getting  The  Most  From  Slaves
My S Q L Replication Getting The Most From SlavesPerconaPerformance
 
Performance Instrumentation Beyond What You Do Now
Performance  Instrumentation  Beyond  What  You  Do  NowPerformance  Instrumentation  Beyond  What  You  Do  Now
Performance Instrumentation Beyond What You Do NowPerconaPerformance
 
Boost Performance With My S Q L 51 Partitions
Boost Performance With  My S Q L 51 PartitionsBoost Performance With  My S Q L 51 Partitions
Boost Performance With My S Q L 51 PartitionsPerconaPerformance
 
Database Performance With Proxy Architectures
Database  Performance With  Proxy  ArchitecturesDatabase  Performance With  Proxy  Architectures
Database Performance With Proxy ArchitecturesPerconaPerformance
 
Running A Realtime Stats Service On My Sql
Running A Realtime Stats Service On My SqlRunning A Realtime Stats Service On My Sql
Running A Realtime Stats Service On My SqlPerconaPerformance
 
How To Think About Performance
How To Think About PerformanceHow To Think About Performance
How To Think About PerformancePerconaPerformance
 
Object Oriented Css For High Performance Websites And Applications
Object Oriented Css For High Performance Websites And ApplicationsObject Oriented Css For High Performance Websites And Applications
Object Oriented Css For High Performance Websites And ApplicationsPerconaPerformance
 
Your Disk Array Is Slower Than It Should Be
Your Disk Array Is Slower Than It Should BeYour Disk Array Is Slower Than It Should Be
Your Disk Array Is Slower Than It Should BePerconaPerformance
 

Mais de PerconaPerformance (17)

Drizzles Approach To Improving Performance Of The Server
Drizzles  Approach To  Improving  Performance Of The  ServerDrizzles  Approach To  Improving  Performance Of The  Server
Drizzles Approach To Improving Performance Of The Server
 
E M T Better Performance Monitoring
E M T  Better  Performance  MonitoringE M T  Better  Performance  Monitoring
E M T Better Performance Monitoring
 
Covering Indexes Ordersof Magnitude Improvements
Covering  Indexes  Ordersof Magnitude  ImprovementsCovering  Indexes  Ordersof Magnitude  Improvements
Covering Indexes Ordersof Magnitude Improvements
 
Automated Performance Testing With J Meter And Maven
Automated  Performance  Testing With  J Meter And  MavenAutomated  Performance  Testing With  J Meter And  Maven
Automated Performance Testing With J Meter And Maven
 
Galera Multi Master Synchronous My S Q L Replication Clusters
Galera  Multi Master  Synchronous  My S Q L  Replication  ClustersGalera  Multi Master  Synchronous  My S Q L  Replication  Clusters
Galera Multi Master Synchronous My S Q L Replication Clusters
 
My S Q L Replication Getting The Most From Slaves
My S Q L  Replication  Getting  The  Most  From  SlavesMy S Q L  Replication  Getting  The  Most  From  Slaves
My S Q L Replication Getting The Most From Slaves
 
Performance Instrumentation Beyond What You Do Now
Performance  Instrumentation  Beyond  What  You  Do  NowPerformance  Instrumentation  Beyond  What  You  Do  Now
Performance Instrumentation Beyond What You Do Now
 
Boost Performance With My S Q L 51 Partitions
Boost Performance With  My S Q L 51 PartitionsBoost Performance With  My S Q L 51 Partitions
Boost Performance With My S Q L 51 Partitions
 
High Performance Erlang
High  Performance  ErlangHigh  Performance  Erlang
High Performance Erlang
 
Websites On Speed
Websites On  SpeedWebsites On  Speed
Websites On Speed
 
Database Performance With Proxy Architectures
Database  Performance With  Proxy  ArchitecturesDatabase  Performance With  Proxy  Architectures
Database Performance With Proxy Architectures
 
Using Storage Class Memory
Using Storage Class MemoryUsing Storage Class Memory
Using Storage Class Memory
 
Websites On Speed
Websites On SpeedWebsites On Speed
Websites On Speed
 
Running A Realtime Stats Service On My Sql
Running A Realtime Stats Service On My SqlRunning A Realtime Stats Service On My Sql
Running A Realtime Stats Service On My Sql
 
How To Think About Performance
How To Think About PerformanceHow To Think About Performance
How To Think About Performance
 
Object Oriented Css For High Performance Websites And Applications
Object Oriented Css For High Performance Websites And ApplicationsObject Oriented Css For High Performance Websites And Applications
Object Oriented Css For High Performance Websites And Applications
 
Your Disk Array Is Slower Than It Should Be
Your Disk Array Is Slower Than It Should BeYour Disk Array Is Slower Than It Should Be
Your Disk Array Is Slower Than It Should Be
 

Último

WhatsApp 📞 Call : 9892124323 ✅Call Girls In Chembur ( Mumbai ) secure service
WhatsApp 📞 Call : 9892124323  ✅Call Girls In Chembur ( Mumbai ) secure serviceWhatsApp 📞 Call : 9892124323  ✅Call Girls In Chembur ( Mumbai ) secure service
WhatsApp 📞 Call : 9892124323 ✅Call Girls In Chembur ( Mumbai ) secure servicePooja Nehwal
 
Top Rated Pune Call Girls Shikrapur ⟟ 6297143586 ⟟ Call Me For Genuine Sex S...
Top Rated  Pune Call Girls Shikrapur ⟟ 6297143586 ⟟ Call Me For Genuine Sex S...Top Rated  Pune Call Girls Shikrapur ⟟ 6297143586 ⟟ Call Me For Genuine Sex S...
Top Rated Pune Call Girls Shikrapur ⟟ 6297143586 ⟟ Call Me For Genuine Sex S...Call Girls in Nagpur High Profile
 
Kharghar Blowjob Housewife Call Girls NUmber-9833754194-CBD Belapur Internati...
Kharghar Blowjob Housewife Call Girls NUmber-9833754194-CBD Belapur Internati...Kharghar Blowjob Housewife Call Girls NUmber-9833754194-CBD Belapur Internati...
Kharghar Blowjob Housewife Call Girls NUmber-9833754194-CBD Belapur Internati...priyasharma62062
 
VIP Call Girl in Mumbai 💧 9920725232 ( Call Me ) Get A New Crush Everyday Wit...
VIP Call Girl in Mumbai 💧 9920725232 ( Call Me ) Get A New Crush Everyday Wit...VIP Call Girl in Mumbai 💧 9920725232 ( Call Me ) Get A New Crush Everyday Wit...
VIP Call Girl in Mumbai 💧 9920725232 ( Call Me ) Get A New Crush Everyday Wit...dipikadinghjn ( Why You Choose Us? ) Escorts
 
Mira Road Awesome 100% Independent Call Girls NUmber-9833754194-Dahisar Inter...
Mira Road Awesome 100% Independent Call Girls NUmber-9833754194-Dahisar Inter...Mira Road Awesome 100% Independent Call Girls NUmber-9833754194-Dahisar Inter...
Mira Road Awesome 100% Independent Call Girls NUmber-9833754194-Dahisar Inter...priyasharma62062
 
Stock Market Brief Deck (Under Pressure).pdf
Stock Market Brief Deck (Under Pressure).pdfStock Market Brief Deck (Under Pressure).pdf
Stock Market Brief Deck (Under Pressure).pdfMichael Silva
 
falcon-invoice-discounting-unlocking-prime-investment-opportunities
falcon-invoice-discounting-unlocking-prime-investment-opportunitiesfalcon-invoice-discounting-unlocking-prime-investment-opportunities
falcon-invoice-discounting-unlocking-prime-investment-opportunitiesFalcon Invoice Discounting
 
Top Rated Pune Call Girls Sinhagad Road ⟟ 6297143586 ⟟ Call Me For Genuine S...
Top Rated  Pune Call Girls Sinhagad Road ⟟ 6297143586 ⟟ Call Me For Genuine S...Top Rated  Pune Call Girls Sinhagad Road ⟟ 6297143586 ⟟ Call Me For Genuine S...
Top Rated Pune Call Girls Sinhagad Road ⟟ 6297143586 ⟟ Call Me For Genuine S...Call Girls in Nagpur High Profile
 
Top Rated Pune Call Girls Dighi ⟟ 6297143586 ⟟ Call Me For Genuine Sex Servi...
Top Rated  Pune Call Girls Dighi ⟟ 6297143586 ⟟ Call Me For Genuine Sex Servi...Top Rated  Pune Call Girls Dighi ⟟ 6297143586 ⟟ Call Me For Genuine Sex Servi...
Top Rated Pune Call Girls Dighi ⟟ 6297143586 ⟟ Call Me For Genuine Sex Servi...Call Girls in Nagpur High Profile
 
VIP Independent Call Girls in Bandra West 🌹 9920725232 ( Call Me ) Mumbai Esc...
VIP Independent Call Girls in Bandra West 🌹 9920725232 ( Call Me ) Mumbai Esc...VIP Independent Call Girls in Bandra West 🌹 9920725232 ( Call Me ) Mumbai Esc...
VIP Independent Call Girls in Bandra West 🌹 9920725232 ( Call Me ) Mumbai Esc...dipikadinghjn ( Why You Choose Us? ) Escorts
 
Call Girls Service Pune ₹7.5k Pick Up & Drop With Cash Payment 9352852248 Cal...
Call Girls Service Pune ₹7.5k Pick Up & Drop With Cash Payment 9352852248 Cal...Call Girls Service Pune ₹7.5k Pick Up & Drop With Cash Payment 9352852248 Cal...
Call Girls Service Pune ₹7.5k Pick Up & Drop With Cash Payment 9352852248 Cal...roshnidevijkn ( Why You Choose Us? ) Escorts
 
Enjoy Night⚡Call Girls Patel Nagar Delhi >༒8448380779 Escort Service
Enjoy Night⚡Call Girls Patel Nagar Delhi >༒8448380779 Escort ServiceEnjoy Night⚡Call Girls Patel Nagar Delhi >༒8448380779 Escort Service
Enjoy Night⚡Call Girls Patel Nagar Delhi >༒8448380779 Escort ServiceDelhi Call girls
 
call girls in Sant Nagar (DELHI) 🔝 >༒9953056974 🔝 genuine Escort Service 🔝✔️✔️
call girls in Sant Nagar (DELHI) 🔝 >༒9953056974 🔝 genuine Escort Service 🔝✔️✔️call girls in Sant Nagar (DELHI) 🔝 >༒9953056974 🔝 genuine Escort Service 🔝✔️✔️
call girls in Sant Nagar (DELHI) 🔝 >༒9953056974 🔝 genuine Escort Service 🔝✔️✔️9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
Vip Call US 📞 7738631006 ✅Call Girls In Sakinaka ( Mumbai )
Vip Call US 📞 7738631006 ✅Call Girls In Sakinaka ( Mumbai )Vip Call US 📞 7738631006 ✅Call Girls In Sakinaka ( Mumbai )
Vip Call US 📞 7738631006 ✅Call Girls In Sakinaka ( Mumbai )Pooja Nehwal
 
Call Girls in New Friends Colony Delhi 💯 Call Us 🔝9205541914 🔝( Delhi) Escort...
Call Girls in New Friends Colony Delhi 💯 Call Us 🔝9205541914 🔝( Delhi) Escort...Call Girls in New Friends Colony Delhi 💯 Call Us 🔝9205541914 🔝( Delhi) Escort...
Call Girls in New Friends Colony Delhi 💯 Call Us 🔝9205541914 🔝( Delhi) Escort...Delhi Call girls
 
VIP Independent Call Girls in Taloja 🌹 9920725232 ( Call Me ) Mumbai Escorts ...
VIP Independent Call Girls in Taloja 🌹 9920725232 ( Call Me ) Mumbai Escorts ...VIP Independent Call Girls in Taloja 🌹 9920725232 ( Call Me ) Mumbai Escorts ...
VIP Independent Call Girls in Taloja 🌹 9920725232 ( Call Me ) Mumbai Escorts ...dipikadinghjn ( Why You Choose Us? ) Escorts
 
Top Rated Pune Call Girls Lohegaon ⟟ 6297143586 ⟟ Call Me For Genuine Sex Se...
Top Rated  Pune Call Girls Lohegaon ⟟ 6297143586 ⟟ Call Me For Genuine Sex Se...Top Rated  Pune Call Girls Lohegaon ⟟ 6297143586 ⟟ Call Me For Genuine Sex Se...
Top Rated Pune Call Girls Lohegaon ⟟ 6297143586 ⟟ Call Me For Genuine Sex Se...Call Girls in Nagpur High Profile
 
Top Rated Pune Call Girls Viman Nagar ⟟ 6297143586 ⟟ Call Me For Genuine Sex...
Top Rated  Pune Call Girls Viman Nagar ⟟ 6297143586 ⟟ Call Me For Genuine Sex...Top Rated  Pune Call Girls Viman Nagar ⟟ 6297143586 ⟟ Call Me For Genuine Sex...
Top Rated Pune Call Girls Viman Nagar ⟟ 6297143586 ⟟ Call Me For Genuine Sex...Call Girls in Nagpur High Profile
 
VIP Independent Call Girls in Andheri 🌹 9920725232 ( Call Me ) Mumbai Escorts...
VIP Independent Call Girls in Andheri 🌹 9920725232 ( Call Me ) Mumbai Escorts...VIP Independent Call Girls in Andheri 🌹 9920725232 ( Call Me ) Mumbai Escorts...
VIP Independent Call Girls in Andheri 🌹 9920725232 ( Call Me ) Mumbai Escorts...dipikadinghjn ( Why You Choose Us? ) Escorts
 

Último (20)

WhatsApp 📞 Call : 9892124323 ✅Call Girls In Chembur ( Mumbai ) secure service
WhatsApp 📞 Call : 9892124323  ✅Call Girls In Chembur ( Mumbai ) secure serviceWhatsApp 📞 Call : 9892124323  ✅Call Girls In Chembur ( Mumbai ) secure service
WhatsApp 📞 Call : 9892124323 ✅Call Girls In Chembur ( Mumbai ) secure service
 
Top Rated Pune Call Girls Shikrapur ⟟ 6297143586 ⟟ Call Me For Genuine Sex S...
Top Rated  Pune Call Girls Shikrapur ⟟ 6297143586 ⟟ Call Me For Genuine Sex S...Top Rated  Pune Call Girls Shikrapur ⟟ 6297143586 ⟟ Call Me For Genuine Sex S...
Top Rated Pune Call Girls Shikrapur ⟟ 6297143586 ⟟ Call Me For Genuine Sex S...
 
Kharghar Blowjob Housewife Call Girls NUmber-9833754194-CBD Belapur Internati...
Kharghar Blowjob Housewife Call Girls NUmber-9833754194-CBD Belapur Internati...Kharghar Blowjob Housewife Call Girls NUmber-9833754194-CBD Belapur Internati...
Kharghar Blowjob Housewife Call Girls NUmber-9833754194-CBD Belapur Internati...
 
(Vedika) Low Rate Call Girls in Pune Call Now 8250077686 Pune Escorts 24x7
(Vedika) Low Rate Call Girls in Pune Call Now 8250077686 Pune Escorts 24x7(Vedika) Low Rate Call Girls in Pune Call Now 8250077686 Pune Escorts 24x7
(Vedika) Low Rate Call Girls in Pune Call Now 8250077686 Pune Escorts 24x7
 
VIP Call Girl in Mumbai 💧 9920725232 ( Call Me ) Get A New Crush Everyday Wit...
VIP Call Girl in Mumbai 💧 9920725232 ( Call Me ) Get A New Crush Everyday Wit...VIP Call Girl in Mumbai 💧 9920725232 ( Call Me ) Get A New Crush Everyday Wit...
VIP Call Girl in Mumbai 💧 9920725232 ( Call Me ) Get A New Crush Everyday Wit...
 
Mira Road Awesome 100% Independent Call Girls NUmber-9833754194-Dahisar Inter...
Mira Road Awesome 100% Independent Call Girls NUmber-9833754194-Dahisar Inter...Mira Road Awesome 100% Independent Call Girls NUmber-9833754194-Dahisar Inter...
Mira Road Awesome 100% Independent Call Girls NUmber-9833754194-Dahisar Inter...
 
Stock Market Brief Deck (Under Pressure).pdf
Stock Market Brief Deck (Under Pressure).pdfStock Market Brief Deck (Under Pressure).pdf
Stock Market Brief Deck (Under Pressure).pdf
 
falcon-invoice-discounting-unlocking-prime-investment-opportunities
falcon-invoice-discounting-unlocking-prime-investment-opportunitiesfalcon-invoice-discounting-unlocking-prime-investment-opportunities
falcon-invoice-discounting-unlocking-prime-investment-opportunities
 
Top Rated Pune Call Girls Sinhagad Road ⟟ 6297143586 ⟟ Call Me For Genuine S...
Top Rated  Pune Call Girls Sinhagad Road ⟟ 6297143586 ⟟ Call Me For Genuine S...Top Rated  Pune Call Girls Sinhagad Road ⟟ 6297143586 ⟟ Call Me For Genuine S...
Top Rated Pune Call Girls Sinhagad Road ⟟ 6297143586 ⟟ Call Me For Genuine S...
 
Top Rated Pune Call Girls Dighi ⟟ 6297143586 ⟟ Call Me For Genuine Sex Servi...
Top Rated  Pune Call Girls Dighi ⟟ 6297143586 ⟟ Call Me For Genuine Sex Servi...Top Rated  Pune Call Girls Dighi ⟟ 6297143586 ⟟ Call Me For Genuine Sex Servi...
Top Rated Pune Call Girls Dighi ⟟ 6297143586 ⟟ Call Me For Genuine Sex Servi...
 
VIP Independent Call Girls in Bandra West 🌹 9920725232 ( Call Me ) Mumbai Esc...
VIP Independent Call Girls in Bandra West 🌹 9920725232 ( Call Me ) Mumbai Esc...VIP Independent Call Girls in Bandra West 🌹 9920725232 ( Call Me ) Mumbai Esc...
VIP Independent Call Girls in Bandra West 🌹 9920725232 ( Call Me ) Mumbai Esc...
 
Call Girls Service Pune ₹7.5k Pick Up & Drop With Cash Payment 9352852248 Cal...
Call Girls Service Pune ₹7.5k Pick Up & Drop With Cash Payment 9352852248 Cal...Call Girls Service Pune ₹7.5k Pick Up & Drop With Cash Payment 9352852248 Cal...
Call Girls Service Pune ₹7.5k Pick Up & Drop With Cash Payment 9352852248 Cal...
 
Enjoy Night⚡Call Girls Patel Nagar Delhi >༒8448380779 Escort Service
Enjoy Night⚡Call Girls Patel Nagar Delhi >༒8448380779 Escort ServiceEnjoy Night⚡Call Girls Patel Nagar Delhi >༒8448380779 Escort Service
Enjoy Night⚡Call Girls Patel Nagar Delhi >༒8448380779 Escort Service
 
call girls in Sant Nagar (DELHI) 🔝 >༒9953056974 🔝 genuine Escort Service 🔝✔️✔️
call girls in Sant Nagar (DELHI) 🔝 >༒9953056974 🔝 genuine Escort Service 🔝✔️✔️call girls in Sant Nagar (DELHI) 🔝 >༒9953056974 🔝 genuine Escort Service 🔝✔️✔️
call girls in Sant Nagar (DELHI) 🔝 >༒9953056974 🔝 genuine Escort Service 🔝✔️✔️
 
Vip Call US 📞 7738631006 ✅Call Girls In Sakinaka ( Mumbai )
Vip Call US 📞 7738631006 ✅Call Girls In Sakinaka ( Mumbai )Vip Call US 📞 7738631006 ✅Call Girls In Sakinaka ( Mumbai )
Vip Call US 📞 7738631006 ✅Call Girls In Sakinaka ( Mumbai )
 
Call Girls in New Friends Colony Delhi 💯 Call Us 🔝9205541914 🔝( Delhi) Escort...
Call Girls in New Friends Colony Delhi 💯 Call Us 🔝9205541914 🔝( Delhi) Escort...Call Girls in New Friends Colony Delhi 💯 Call Us 🔝9205541914 🔝( Delhi) Escort...
Call Girls in New Friends Colony Delhi 💯 Call Us 🔝9205541914 🔝( Delhi) Escort...
 
VIP Independent Call Girls in Taloja 🌹 9920725232 ( Call Me ) Mumbai Escorts ...
VIP Independent Call Girls in Taloja 🌹 9920725232 ( Call Me ) Mumbai Escorts ...VIP Independent Call Girls in Taloja 🌹 9920725232 ( Call Me ) Mumbai Escorts ...
VIP Independent Call Girls in Taloja 🌹 9920725232 ( Call Me ) Mumbai Escorts ...
 
Top Rated Pune Call Girls Lohegaon ⟟ 6297143586 ⟟ Call Me For Genuine Sex Se...
Top Rated  Pune Call Girls Lohegaon ⟟ 6297143586 ⟟ Call Me For Genuine Sex Se...Top Rated  Pune Call Girls Lohegaon ⟟ 6297143586 ⟟ Call Me For Genuine Sex Se...
Top Rated Pune Call Girls Lohegaon ⟟ 6297143586 ⟟ Call Me For Genuine Sex Se...
 
Top Rated Pune Call Girls Viman Nagar ⟟ 6297143586 ⟟ Call Me For Genuine Sex...
Top Rated  Pune Call Girls Viman Nagar ⟟ 6297143586 ⟟ Call Me For Genuine Sex...Top Rated  Pune Call Girls Viman Nagar ⟟ 6297143586 ⟟ Call Me For Genuine Sex...
Top Rated Pune Call Girls Viman Nagar ⟟ 6297143586 ⟟ Call Me For Genuine Sex...
 
VIP Independent Call Girls in Andheri 🌹 9920725232 ( Call Me ) Mumbai Escorts...
VIP Independent Call Girls in Andheri 🌹 9920725232 ( Call Me ) Mumbai Escorts...VIP Independent Call Girls in Andheri 🌹 9920725232 ( Call Me ) Mumbai Escorts...
VIP Independent Call Girls in Andheri 🌹 9920725232 ( Call Me ) Mumbai Escorts...
 

Trees And More With Postgre S Q L

  • 1. Trees and More With PostgreSQL Common Table Expressions Percona Conference 2009 Copyright © 2009 David Fetter david.fetter@pgexperts.com All Rights Reserved
  • 2.
  • 3. Some Approaches • External Processing • Functions and Stored Procedures • Materialized Path Enumeration • Nested Set
  • 4. External Processing • Pros: • Lots of Language Choices • Cons: • Scaling • No Relational Operators
  • 5. Functions and Stored Procedures • Pros: • Easy to visualize • Easy to write • Cons: • Scaling • Hard to do relational operators
  • 6. Materialized Path Enumeration • Pros: • Easy to visualize • Cons: • DDL for each hierarchy • Full-table changes on write • Hard to do relational operators
  • 7. Nested Sets • Pros: • Easy to manipulate on SELECT • Sounds cool • Endorsed by a famous bald guy • Cons: • DDL for each hierarchy • Full-table changes on write • Hard to do relational operators
  • 8. Thanks to: • The ISO SQL Standards Committee • Yoshiyuki Asaba • Ishii Tatsuo • Jeff Davis • Gregory Stark • Tom Lane • etc., etc., etc.
  • 9. SQL Standard • Common Table Expressions (CTE)
  • 11. Recursion in General • Initial Condition • Recursion step • Termination condition
  • 12. E1 List Table CREATE TABLE employee( id INTEGER NOT NULL, boss_id INTEGER, UNIQUE(id, boss_id)/*, etc., etc. */ ); INSERT INTO employee(id, boss_id) VALUES(1,NULL), /* El capo di tutti capi */ (2,1),(3,1),(4,1), (5,2),(6,2),(7,2),(8,3),(9,3),(10,4), (11,5),(12,5),(13,6),(14,7),(15,8), (1,9);
  • 13. Tree Query Initiation WITH RECURSIVE t(node, path) AS ( SELECT id, ARRAY[id] FROM employee WHERE boss_id IS NULL /* Initiation Step */ UNION ALL SELECT e1.id, t.path || ARRAY[e1.id] FROM employee e1 JOIN t ON (e1.boss_id = t.node) WHERE id NOT IN (t.path) ) SELECT CASE WHEN array_upper(path,1)>1 THEN '+-' ELSE '' END || REPEAT('--', array_upper(path,1)-2) || node AS quot;Branchquot; FROM t ORDER BY path;
  • 14. Tree Query Recursion WITH RECURSIVE t(node, path) AS ( SELECT id, ARRAY[id] FROM employee WHERE boss_id IS NULL UNION ALL SELECT e1.id, t.path || ARRAY[e1.id] /* Recursion */ FROM employee e1 JOIN t ON (e1.boss_id = t.node) WHERE id NOT IN (t.path) ) SELECT CASE WHEN array_upper(path,1)>1 THEN '+-' ELSE '' END || REPEAT('--', array_upper(path,1)-2) || node AS quot;Branchquot; FROM t ORDER BY path;
  • 15. Tree Query Termination WITH RECURSIVE t(node, path) AS ( SELECT id, ARRAY[id] FROM employee WHERE boss_id IS NULL UNION ALL SELECT e1.id, t.path || ARRAY[e1.id] FROM employee e1 JOIN t ON (e1.boss_id = t.node) WHERE id NOT IN (t.path) /* Termination Condition */ ) SELECT CASE WHEN array_upper(path,1)>1 THEN '+-' ELSE '' END || REPEAT('--', array_upper(path,1)-2) || node AS quot;Branchquot; FROM t ORDER BY path;
  • 16. Tree Query Display WITH RECURSIVE t(node, path) AS ( SELECT id, ARRAY[id] FROM employee WHERE boss_id IS NULL UNION ALL SELECT e1.id, t.path || ARRAY[e1.id] FROM employee e1 JOIN t ON (e1.boss_id = t.node) WHERE id NOT IN (t.path) ) SELECT CASE WHEN array_upper(path,1)>1 THEN '+-' ELSE '' END || REPEAT('--', array_upper(path,1)-2) || node AS quot;Branchquot; /* Display */ FROM t ORDER BY path;
  • 17. Tree Query Initiation Branch ---------- 1 +-2 +---5 +-----11 +-----12 +---6 +-----13 +---7 +-----14 +-3 +---8 +-----15 +---9 +-4 +---10 +-9 (16 rows)
  • 18. Travelling Salesman Problem Given a number of cities and the costs of travelling from any city to any other city, what is the least- cost round-trip route that visits each city exactly once and then returns to the starting city?
  • 19. TSP Schema CREATE TABLE pairs ( from_city TEXT NOT NULL, to_city TEXT NOT NULL, distance INTEGER NOT NULL, PRIMARY KEY(from_city, to_city), CHECK (from_city < to_city) );
  • 20. TSP Data INSERT INTO pairs VALUES ('Bari','Bologna',672), ('Bari','Bolzano',939), ('Bari','Firenze',723), ('Bari','Genova',944), ('Bari','Milan',881), ('Bari','Napoli',257), ('Bari','Palermo',708), ('Bari','Reggio Calabria',464), ....
  • 21. TSP Program: Symmetric Setup WITH RECURSIVE both_ways( from_city, to_city, distance ) /* Working Table */ AS ( SELECT from_city, to_city, distance FROM pairs UNION ALL SELECT to_city AS quot;from_cityquot;, from_city AS quot;to_cityquot;, distance FROM pairs ),
  • 22. TSP Program: Symmetric Setup WITH RECURSIVE both_ways( from_city, to_city, distance ) AS (/* Distances One Way */ SELECT from_city, to_city, distance FROM pairs UNION ALL SELECT to_city AS quot;from_cityquot;, from_city AS quot;to_cityquot;, distance FROM pairs ),
  • 23. TSP Program: Symmetric Setup WITH RECURSIVE both_ways( from_city, to_city, distance ) AS ( SELECT from_city, to_city, distance FROM pairs UNION ALL /* Distances Other Way */ SELECT to_city AS quot;from_cityquot;, from_city AS quot;to_cityquot;, distance FROM pairs ),
  • 24. TSP Program: Path Initialization Step paths ( from_city, to_city, distance, path ) AS ( SELECT from_city, to_city, distance, ARRAY[from_city] AS quot;pathquot; FROM both_ways b1 WHERE b1.from_city = 'Roma' UNION ALL
  • 25. TSP Program: Path Recursion Step SELECT b2.from_city, b2.to_city, p.distance + b2.distance, p.path || b2.from_city FROM both_ways b2 JOIN paths p ON ( p.to_city = b2.from_city AND b2.from_city <> ALL (p.path[ 2:array_upper(p.path,1) ]) /* Prevent re-tracing */ AND array_upper(p.path,1) < 6 ) )
  • 26. TSP Program: Timely Termination Step SELECT b2.from_city, b2.to_city, p.distance + b2.distance, p.path || b2.from_city FROM both_ways b2 JOIN paths p ON ( p.to_city = b2.from_city AND b2.from_city <> ALL (p.path[ 2:array_upper(p.path,1) ]) /* Prevent re-tracing */ AND array_upper(p.path,1) < 6 /* Timely Termination */ ) )
  • 27. TSP Program: Filter and Display SELECT path || to_city AS quot;pathquot;, distance FROM paths WHERE to_city = 'Roma' AND ARRAY['Milan','Firenze','Napoli'] <@ path ORDER BY distance, path LIMIT 1;
  • 28. TSP Program: Filter and Display davidfetter@tsp=# i travelling_salesman.sql path | distance ----------------------------------+---------- {Roma,Firenze,Milan,Napoli,Roma} | 1553 (1 row) Time: 11679.503 ms
  • 29. Hausdorf-Besicovich- WTF Dimension WITH RECURSIVE Z(Ix, Iy, Cx, Cy, X, Y, I) AS ( SELECT Ix, Iy, X::float, Y::float, X::float, Y::float, 0 FROM (SELECT -2.2 + 0.031 * i, i FROM generate_series(0,101) AS i) AS xgen(x,ix) CROSS JOIN (SELECT -1.5 + 0.031 * i, i FROM generate_series(0,101) AS i) AS ygen(y,iy) UNION ALL SELECT Ix, Iy, Cx, Cy, X * X - Y * Y + Cx AS X, Y * X * 2 + Cy, I + 1 FROM Z WHERE X * X + Y * Y < 16::float AND I < 100 ),
  • 30. Filter Zt (Ix, Iy, I) AS ( SELECT Ix, Iy, MAX(I) AS I FROM Z GROUP BY Iy, Ix ORDER BY Iy, Ix )
  • 31. Display SELECT array_to_string( array_agg( SUBSTRING( ' .,,,-----++++%%%%@@@@#### ', GREATEST(I,1) ),'' ) FROM Zt GROUP BY Iy ORDER BY Iy;
  • 34. Thanks! Copyright © 2009 David Fetter david.fetter@pgexperts.com All Rights Reserved