SlideShare a Scribd company logo
1 of 37
Download to read offline
Writeable CTEs
                   (the next big thing)



Copyright © 2009
David Fetter david.fetter@pgexperts.com
All Rights Reserved
Current CTEs
WITH [RECURSIVE] t1 [(column type,…)] AS
(
    [SELECT | VALUES]
[UNION [ALL]
    [SELECT]
),
t2 AS…tn AS…
SELECT…
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?
OBTW

With CTE and Windowing, SQL is Turing Complete.
What Didn't the
Old Syntax Do?
WRITE!
WITH [RECURSIVE] t1 [(column type,…)] AS
(
    [SELECT | VALUES |
   (INSERT | UPDATE | DELETE) [RETURNING]]
[UNION [ALL]
    [SELECT | VALUES |
   (INSERT     | UPDATE | DELETE) [RETURNING]]
)
(SELECT |   INSERT | UPDATE | DELETE)      …
For 8.5:
Simple Partition Management

 CREATE TABLE log (
     ts TIMESTAMPTZ NOT NULL,
     msg TEXT
 );
For 8.5:
Simple Partition Management
 CREATE TABLE log_200901 ()
 INHERITS(log);

 ALTER TABLE log_200901 ADD
 CONSTRAINT right_month CHECK(
     ts >= '2009-01-01' AND
     ts < '2009-02-01');
For 8.5:
      Simple Partition Management


johto@postgres:54321=# WITH
t1 AS (DELETE FROM ONLY log WHERE ts < '2009-02-01' RETURNING *),
INSERT INTO log_200901 SELECT * FROM t1;
INSERT 0 83240
What you'll be able to do:
WITH t AS (
     DELETE FROM ONLY log WHERE ts >= '2009-01-01'
                       AND ts < '2009-02-01'
                       RETURNING *)
INSERT INTO log_200901
SELECT * FROM t;


                       QUERY PLAN
---------------------------------------------------------
 Insert (cost=27.40..27.52 rows=83240 width=40)
   -> CTE Scan on t (cost=27.40..27.52 rows=83240 width=40)
         CTE t
           -> Delete (cost=0.00..27.40 rows=83240 width=6)
                 -> Seq Scan on log (cost=0.00..27.40 rows=83240 width=6)
                       Filter: (..)
(6 rows)
What you can do now:
        Partition Management

johto@postgres:54321=# WITH
t1 AS (DELETE FROM ONLY log WHERE ts < '2009-02-01' RETURNING *),
t2 AS (INSERT INTO log_200901 SELECT * FROM t1)
SELECT min(ts), max(ts), count(*) FROM t1;
             min             │              max             │ count
───────────────── | ──────────────── | ────
 2009-01-01 00:00:01.6416-08 │ 2009-01-30 23:58:38.6976-08 │ 83240
(1 row)
Query Clustering:
            I/O Minimization

CREATE TABLE person (
    id SERIAL PRIMARY KEY,
    first_name TEXT,
    last_name TEXT,
    CHECK (CASE WHEN first_name IS NULL THEN 0 ELSE 1 END +
           CASE WHEN last_name IS NULL THEN 0 ELSE 1 END >= 1)
    birthdate DATE NOT NULL,
    gender TEXT
);
Query Clustering:
         I/O Minimization

CREATE TABLE im (
    id SERIAL PRIMARY KEY,
    provider TEXT NOT NULL, /* should be fk */
    handle TEXT NOT NULL
);
Query Clustering:
      I/O Minimization
CREATE TABLE phone (
    id SERIAL PRIMARY KEY,
    country_code TEXT NOT NULL,
    phone_number TEXT NOT NULL,
    extension TEXT
);
Query Clustering:
 I/O Minimization
CREATE TABLE street (
    id SERIAL PRIMARY KEY,
    street1 TEXT NOT NULL,
    street2 TEXT,
    street3 TEXT,
    city TEXT NOT NULL,
    state TEXT,
    country TEXT NOT NULL,
    post_code TEXT
);
Query Clustering:
   I/O Minimization
CREATE TABLE person_im (
    person_id INTEGER NOT NULL REFERENCES person (id),
    im_id INTEGER NOT NULL REFERENCES im (id),
    UNIQUE (person_id, im_id)
);

CREATE TABLE person_phone (
    person_id INTEGER NOT NULL REFERENCES person (id),
    phone_id INTEGER NOT NULL REFERENCES phone (id),
    UNIQUE (person_id, phone_id)
);

CREATE TABLE person_street (
    person_id INTEGER NOT NULL REFERENCES person (id),
    street_id INTEGER NOT NULL REFERENCES street (id),
    UNIQUE (person_id, street_id)
);
Query Clustering:
         I/O Minimization

WITH t_person AS (
    INSERT INTO person (first_name, last_name)
    VALUES ('David', 'Fetter')
    RETURNING id
),
Query Clustering:
        I/O Minimization
t_im AS (
    INSERT INTO im (provider, handle)
    VALUES
        ('Yahoo!', 'dfetter'),
        ('AIM', 'dfetter666'),
        ('XMPP', 'david.fetter@gmail.com')
    RETURNING id
),
t_person_im AS (
    INSERT INTO person_im
    SELECT * FROM t_person CROSS JOIN t_im
),
Query Clustering:
        I/O Minimization
t_phone (phone_id) AS (
    INSERT INTO phone (country_code, phone_number)
    VALUES
        ('+1','415 235 3778'),
        ('+1','510 893 6100')
    RETURNING id
),
t_person_phone AS (
    INSERT INTO person_phone
    SELECT * FROM t_person CROSS JOIN t_phone
),
Query Clustering:
              I/O Minimization

t_street AS (
    INSERT INTO street (street1, city, state, country, post_code)
    VALUES
        ('2500B Magnolia Street', 'Oakland','California','USA','94607-2410'),
        ('2166 Hayes Street Suite 200', 'San Francisco','California','USA','94117')
),
t_person_street AS (
    INSERT INTO person_street
    SELECT * FROM t_person CROSS JOIN t_street
)
Query Clustering:
  I/O Minimization


VALUES(true);
Query Clustering:
     Transaction Management
CREATE TABLE foo (
    id SERIAL PRIMARY KEY,
    bar_id INTEGER NOT NULL
);

CREATE TABLE bar (
    id SERIAL PRIMARY KEY,
    foo_id INTEGER NOT NULL REFERENCES foo(id)
                           ON DELETE CASCADE
                           INITIALLY DEFERRED
);

ALTER TABLE foo ADD FOREIGN KEY (bar_id) REFERENCES bar(id)
                                   ON DELETE CASCADE
                                   INITIALLY DEFERRED;
Query Clustering:
     Transaction Management
WITH t AS
(
	

 INSERT INTO foo(id, bar_id)
	

 VALUES(
	

 	

 DEFAULT,
	

 	

 nextval(pg_get_serial_sequence('bar', 'id'))
    )
	

 RETURNING id AS foo_id, bar_id
)
INSERT INTO bar(id,foo_id)
SELECT bar_id, foo_id FROM t RETURNING *;
How'd He Do That?!?



First try: David digs into the grammar and gets cut
a few times.
How'd He Do That?!?


First try: Marko reworks the planner. It needs to
know when it creates a ModifyTable node. These used
to have another name.
How'd He Do That?!?



First try: Marko reworks the executor.   It needs new
nodes. Mmmm...nodes.
How'd He Do That?!?



Marko reworks the executor, Part II:
Copy & Paste. Now it's getting ugly...
How'd He Do That?!?


Jaime Casanova, Tom Lane, and Robert Haas look at
the reworked executor.

D'oh!
How'd He Do That?!?



FAIL!
Way too much code copying from top
level to the new nodes.
How'd He Do That?!?



Planner changes for ModifyTable node (a few)
How'd He Do That?!?



Executor changes: ONE new node called ModifyTable
How'd He Do That?!?


    Johto restructures the whole code base for the
ModifyTable node. "The usual stuff," (he said casually) for
                      new nodes.
How'd He Do That?!?




 WIN!
Next Steps

INSERT, UPDATE and DELETE on the top level.
RECURSIVE
Optimization
How'd He Do That?!?


Questions?
 Comments?
Thank You!
         http://2009.pgday.eu/feedback
Copyright © 2009
David Fetter david.fetter@pgexperts.com
All Rights Reserved

More Related Content

What's hot

Python data structures
Python data structuresPython data structures
Python data structures
Harry Potter
 
Programa en C++ ( escriba 3 números y diga cual es el mayor))
Programa en C++ ( escriba 3 números y diga cual es el mayor))Programa en C++ ( escriba 3 números y diga cual es el mayor))
Programa en C++ ( escriba 3 números y diga cual es el mayor))
Alex Penso Romero
 

What's hot (14)

Notes for GNU Octave - Numerical Programming - for Students - 02 of 02 by aru...
Notes for GNU Octave - Numerical Programming - for Students - 02 of 02 by aru...Notes for GNU Octave - Numerical Programming - for Students - 02 of 02 by aru...
Notes for GNU Octave - Numerical Programming - for Students - 02 of 02 by aru...
 
Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 2 of 5 by...
Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 2 of 5 by...Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 2 of 5 by...
Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 2 of 5 by...
 
Sql
SqlSql
Sql
 
Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 4 of 5 by...
Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 4 of 5 by...Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 4 of 5 by...
Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 4 of 5 by...
 
Notes for C++ Programming / Object Oriented C++ Programming for MCA, BCA and ...
Notes for C++ Programming / Object Oriented C++ Programming for MCA, BCA and ...Notes for C++ Programming / Object Oriented C++ Programming for MCA, BCA and ...
Notes for C++ Programming / Object Oriented C++ Programming for MCA, BCA and ...
 
ejemplos gambas
ejemplos gambasejemplos gambas
ejemplos gambas
 
SQL
SQLSQL
SQL
 
Lecture 4 sql {basics keys and constraints}
Lecture 4 sql {basics  keys and constraints}Lecture 4 sql {basics  keys and constraints}
Lecture 4 sql {basics keys and constraints}
 
Select To Order By
Select  To  Order BySelect  To  Order By
Select To Order By
 
Python data structures
Python data structuresPython data structures
Python data structures
 
Sql queries
Sql queriesSql queries
Sql queries
 
Swift에서 꼬리재귀 사용기 (Tail Recursion)
Swift에서 꼬리재귀 사용기 (Tail Recursion)Swift에서 꼬리재귀 사용기 (Tail Recursion)
Swift에서 꼬리재귀 사용기 (Tail Recursion)
 
Programa en C++ ( escriba 3 números y diga cual es el mayor))
Programa en C++ ( escriba 3 números y diga cual es el mayor))Programa en C++ ( escriba 3 números y diga cual es el mayor))
Programa en C++ ( escriba 3 números y diga cual es el mayor))
 
Resoluçãohaskell2
Resoluçãohaskell2Resoluçãohaskell2
Resoluçãohaskell2
 

Viewers also liked (6)

B offer n acceptance
B offer n acceptanceB offer n acceptance
B offer n acceptance
 
Super Hero List: In order to become a Super Hero when I grow up I will need t...
Super Hero List: In order to become a Super Hero when I grow up I will need t...Super Hero List: In order to become a Super Hero when I grow up I will need t...
Super Hero List: In order to become a Super Hero when I grow up I will need t...
 
Postgres Open Keynote: The Next 25 Years
Postgres Open Keynote: The Next 25 YearsPostgres Open Keynote: The Next 25 Years
Postgres Open Keynote: The Next 25 Years
 
Main Task
Main TaskMain Task
Main Task
 
Genre research & case study for noel clarke
Genre research & case study for noel clarkeGenre research & case study for noel clarke
Genre research & case study for noel clarke
 
Open Source Press Relations
Open Source Press RelationsOpen Source Press Relations
Open Source Press Relations
 

Similar to Writeable CTEs: The Next Big Thing

CS 542 Database Index Structures
CS 542 Database Index StructuresCS 542 Database Index Structures
CS 542 Database Index Structures
J Singh
 
Task4output.txt 2 5 9 13 15 10 1 0 3 7 11 14 1.docx
Task4output.txt 2  5  9 13 15 10  1  0  3  7 11 14 1.docxTask4output.txt 2  5  9 13 15 10  1  0  3  7 11 14 1.docx
Task4output.txt 2 5 9 13 15 10 1 0 3 7 11 14 1.docx
josies1
 
Database management system file
Database management system fileDatabase management system file
Database management system file
Ankit Dixit
 
CS 542 Controlling Database Integrity and Performance
CS 542 Controlling Database Integrity and PerformanceCS 542 Controlling Database Integrity and Performance
CS 542 Controlling Database Integrity and Performance
J Singh
 
Creating Tablespaces and Tables in DB2BCIS 4620zArchit.docx
Creating Tablespaces and Tables in DB2BCIS 4620zArchit.docxCreating Tablespaces and Tables in DB2BCIS 4620zArchit.docx
Creating Tablespaces and Tables in DB2BCIS 4620zArchit.docx
willcoxjanay
 
Trees And More With Postgre S Q L
Trees And  More With  Postgre S Q LTrees And  More With  Postgre S Q L
Trees And More With Postgre S Q L
PerconaPerformance
 

Similar to Writeable CTEs: The Next Big Thing (20)

CS 542 Database Index Structures
CS 542 Database Index StructuresCS 542 Database Index Structures
CS 542 Database Index Structures
 
Postgresql 9.3 overview
Postgresql 9.3 overviewPostgresql 9.3 overview
Postgresql 9.3 overview
 
DConf 2016 std.database (a proposed interface & implementation)
DConf 2016 std.database (a proposed interface & implementation)DConf 2016 std.database (a proposed interface & implementation)
DConf 2016 std.database (a proposed interface & implementation)
 
Les09 (using ddl statements to create and manage tables)
Les09 (using ddl statements to create and manage tables)Les09 (using ddl statements to create and manage tables)
Les09 (using ddl statements to create and manage tables)
 
Ppt INFORMATIVE PRACTICES for class 11th chapter 14
Ppt INFORMATIVE PRACTICES for class 11th chapter 14Ppt INFORMATIVE PRACTICES for class 11th chapter 14
Ppt INFORMATIVE PRACTICES for class 11th chapter 14
 
Les09
Les09Les09
Les09
 
How to tune a query - ODTUG 2012
How to tune a query - ODTUG 2012How to tune a query - ODTUG 2012
How to tune a query - ODTUG 2012
 
Sql commands
Sql commandsSql commands
Sql commands
 
Optimizando MySQL
Optimizando MySQLOptimizando MySQL
Optimizando MySQL
 
Task4output.txt 2 5 9 13 15 10 1 0 3 7 11 14 1.docx
Task4output.txt 2  5  9 13 15 10  1  0  3  7 11 14 1.docxTask4output.txt 2  5  9 13 15 10  1  0  3  7 11 14 1.docx
Task4output.txt 2 5 9 13 15 10 1 0 3 7 11 14 1.docx
 
Sql
SqlSql
Sql
 
Database management system file
Database management system fileDatabase management system file
Database management system file
 
CS 542 Controlling Database Integrity and Performance
CS 542 Controlling Database Integrity and PerformanceCS 542 Controlling Database Integrity and Performance
CS 542 Controlling Database Integrity and Performance
 
Cassandra v3.0 at Rakuten meet-up on 12/2/2015
Cassandra v3.0 at Rakuten meet-up on 12/2/2015Cassandra v3.0 at Rakuten meet-up on 12/2/2015
Cassandra v3.0 at Rakuten meet-up on 12/2/2015
 
Sql 2006
Sql 2006Sql 2006
Sql 2006
 
Creating Tablespaces and Tables in DB2BCIS 4620zArchit.docx
Creating Tablespaces and Tables in DB2BCIS 4620zArchit.docxCreating Tablespaces and Tables in DB2BCIS 4620zArchit.docx
Creating Tablespaces and Tables in DB2BCIS 4620zArchit.docx
 
python_avw - Unit-03.pdf
python_avw - Unit-03.pdfpython_avw - Unit-03.pdf
python_avw - Unit-03.pdf
 
Trees And More With Postgre S Q L
Trees And  More With  Postgre S Q LTrees And  More With  Postgre S Q L
Trees And More With Postgre S Q L
 
SQL -PHP Tutorial
SQL -PHP TutorialSQL -PHP Tutorial
SQL -PHP Tutorial
 
4sem dbms(1)
4sem dbms(1)4sem dbms(1)
4sem dbms(1)
 

More from PostgreSQL Experts, Inc.

Elephant Roads: PostgreSQL Patches and Variants
Elephant Roads: PostgreSQL Patches and VariantsElephant Roads: PostgreSQL Patches and Variants
Elephant Roads: PostgreSQL Patches and Variants
PostgreSQL Experts, Inc.
 

More from PostgreSQL Experts, Inc. (20)

Shootout at the PAAS Corral
Shootout at the PAAS CorralShootout at the PAAS Corral
Shootout at the PAAS Corral
 
Shootout at the AWS Corral
Shootout at the AWS CorralShootout at the AWS Corral
Shootout at the AWS Corral
 
Fail over fail_back
Fail over fail_backFail over fail_back
Fail over fail_back
 
PostgreSQL Replication in 10 Minutes - SCALE
PostgreSQL Replication in 10  Minutes - SCALEPostgreSQL Replication in 10  Minutes - SCALE
PostgreSQL Replication in 10 Minutes - SCALE
 
HowTo DR
HowTo DRHowTo DR
HowTo DR
 
Give A Great Tech Talk 2013
Give A Great Tech Talk 2013Give A Great Tech Talk 2013
Give A Great Tech Talk 2013
 
Pg py-and-squid-pypgday
Pg py-and-squid-pypgdayPg py-and-squid-pypgday
Pg py-and-squid-pypgday
 
92 grand prix_2013
92 grand prix_201392 grand prix_2013
92 grand prix_2013
 
Five steps perform_2013
Five steps perform_2013Five steps perform_2013
Five steps perform_2013
 
7 Ways To Crash Postgres
7 Ways To Crash Postgres7 Ways To Crash Postgres
7 Ways To Crash Postgres
 
PWNage: Producing a newsletter with Perl
PWNage: Producing a newsletter with PerlPWNage: Producing a newsletter with Perl
PWNage: Producing a newsletter with Perl
 
10 Ways to Destroy Your Community
10 Ways to Destroy Your Community10 Ways to Destroy Your Community
10 Ways to Destroy Your Community
 
5 (more) Ways To Destroy Your Community
5 (more) Ways To Destroy Your Community5 (more) Ways To Destroy Your Community
5 (more) Ways To Destroy Your Community
 
Preventing Community (from Linux Collab)
Preventing Community (from Linux Collab)Preventing Community (from Linux Collab)
Preventing Community (from Linux Collab)
 
Development of 8.3 In India
Development of 8.3 In IndiaDevelopment of 8.3 In India
Development of 8.3 In India
 
PostgreSQL and MySQL
PostgreSQL and MySQLPostgreSQL and MySQL
PostgreSQL and MySQL
 
50 Ways To Love Your Project
50 Ways To Love Your Project50 Ways To Love Your Project
50 Ways To Love Your Project
 
8.4 Upcoming Features
8.4 Upcoming Features 8.4 Upcoming Features
8.4 Upcoming Features
 
Elephant Roads: PostgreSQL Patches and Variants
Elephant Roads: PostgreSQL Patches and VariantsElephant Roads: PostgreSQL Patches and Variants
Elephant Roads: PostgreSQL Patches and Variants
 
PostgreSQL Development Today: 9.0
PostgreSQL Development Today: 9.0PostgreSQL Development Today: 9.0
PostgreSQL Development Today: 9.0
 

Recently uploaded

IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
Enterprise Knowledge
 

Recently uploaded (20)

Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
Tech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdfTech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdf
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 

Writeable CTEs: The Next Big Thing

  • 1. Writeable CTEs (the next big thing) Copyright © 2009 David Fetter david.fetter@pgexperts.com All Rights Reserved
  • 2. Current CTEs WITH [RECURSIVE] t1 [(column type,…)] AS ( [SELECT | VALUES] [UNION [ALL] [SELECT] ), t2 AS…tn AS… SELECT…
  • 3.
  • 4. 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?
  • 5. OBTW With CTE and Windowing, SQL is Turing Complete.
  • 6. What Didn't the Old Syntax Do?
  • 7. WRITE! WITH [RECURSIVE] t1 [(column type,…)] AS ( [SELECT | VALUES | (INSERT | UPDATE | DELETE) [RETURNING]] [UNION [ALL] [SELECT | VALUES | (INSERT | UPDATE | DELETE) [RETURNING]] ) (SELECT | INSERT | UPDATE | DELETE) …
  • 8. For 8.5: Simple Partition Management CREATE TABLE log ( ts TIMESTAMPTZ NOT NULL, msg TEXT );
  • 9. For 8.5: Simple Partition Management CREATE TABLE log_200901 () INHERITS(log); ALTER TABLE log_200901 ADD CONSTRAINT right_month CHECK( ts >= '2009-01-01' AND ts < '2009-02-01');
  • 10. For 8.5: Simple Partition Management johto@postgres:54321=# WITH t1 AS (DELETE FROM ONLY log WHERE ts < '2009-02-01' RETURNING *), INSERT INTO log_200901 SELECT * FROM t1; INSERT 0 83240
  • 11. What you'll be able to do: WITH t AS ( DELETE FROM ONLY log WHERE ts >= '2009-01-01' AND ts < '2009-02-01' RETURNING *) INSERT INTO log_200901 SELECT * FROM t; QUERY PLAN --------------------------------------------------------- Insert (cost=27.40..27.52 rows=83240 width=40) -> CTE Scan on t (cost=27.40..27.52 rows=83240 width=40) CTE t -> Delete (cost=0.00..27.40 rows=83240 width=6) -> Seq Scan on log (cost=0.00..27.40 rows=83240 width=6) Filter: (..) (6 rows)
  • 12. What you can do now: Partition Management johto@postgres:54321=# WITH t1 AS (DELETE FROM ONLY log WHERE ts < '2009-02-01' RETURNING *), t2 AS (INSERT INTO log_200901 SELECT * FROM t1) SELECT min(ts), max(ts), count(*) FROM t1; min │ max │ count ───────────────── | ──────────────── | ──── 2009-01-01 00:00:01.6416-08 │ 2009-01-30 23:58:38.6976-08 │ 83240 (1 row)
  • 13. Query Clustering: I/O Minimization CREATE TABLE person ( id SERIAL PRIMARY KEY, first_name TEXT, last_name TEXT, CHECK (CASE WHEN first_name IS NULL THEN 0 ELSE 1 END + CASE WHEN last_name IS NULL THEN 0 ELSE 1 END >= 1) birthdate DATE NOT NULL, gender TEXT );
  • 14. Query Clustering: I/O Minimization CREATE TABLE im ( id SERIAL PRIMARY KEY, provider TEXT NOT NULL, /* should be fk */ handle TEXT NOT NULL );
  • 15. Query Clustering: I/O Minimization CREATE TABLE phone ( id SERIAL PRIMARY KEY, country_code TEXT NOT NULL, phone_number TEXT NOT NULL, extension TEXT );
  • 16. Query Clustering: I/O Minimization CREATE TABLE street ( id SERIAL PRIMARY KEY, street1 TEXT NOT NULL, street2 TEXT, street3 TEXT, city TEXT NOT NULL, state TEXT, country TEXT NOT NULL, post_code TEXT );
  • 17. Query Clustering: I/O Minimization CREATE TABLE person_im ( person_id INTEGER NOT NULL REFERENCES person (id), im_id INTEGER NOT NULL REFERENCES im (id), UNIQUE (person_id, im_id) ); CREATE TABLE person_phone ( person_id INTEGER NOT NULL REFERENCES person (id), phone_id INTEGER NOT NULL REFERENCES phone (id), UNIQUE (person_id, phone_id) ); CREATE TABLE person_street ( person_id INTEGER NOT NULL REFERENCES person (id), street_id INTEGER NOT NULL REFERENCES street (id), UNIQUE (person_id, street_id) );
  • 18. Query Clustering: I/O Minimization WITH t_person AS ( INSERT INTO person (first_name, last_name) VALUES ('David', 'Fetter') RETURNING id ),
  • 19. Query Clustering: I/O Minimization t_im AS ( INSERT INTO im (provider, handle) VALUES ('Yahoo!', 'dfetter'), ('AIM', 'dfetter666'), ('XMPP', 'david.fetter@gmail.com') RETURNING id ), t_person_im AS ( INSERT INTO person_im SELECT * FROM t_person CROSS JOIN t_im ),
  • 20. Query Clustering: I/O Minimization t_phone (phone_id) AS ( INSERT INTO phone (country_code, phone_number) VALUES ('+1','415 235 3778'), ('+1','510 893 6100') RETURNING id ), t_person_phone AS ( INSERT INTO person_phone SELECT * FROM t_person CROSS JOIN t_phone ),
  • 21. Query Clustering: I/O Minimization t_street AS ( INSERT INTO street (street1, city, state, country, post_code) VALUES ('2500B Magnolia Street', 'Oakland','California','USA','94607-2410'), ('2166 Hayes Street Suite 200', 'San Francisco','California','USA','94117') ), t_person_street AS ( INSERT INTO person_street SELECT * FROM t_person CROSS JOIN t_street )
  • 22. Query Clustering: I/O Minimization VALUES(true);
  • 23. Query Clustering: Transaction Management CREATE TABLE foo ( id SERIAL PRIMARY KEY, bar_id INTEGER NOT NULL ); CREATE TABLE bar ( id SERIAL PRIMARY KEY, foo_id INTEGER NOT NULL REFERENCES foo(id) ON DELETE CASCADE INITIALLY DEFERRED ); ALTER TABLE foo ADD FOREIGN KEY (bar_id) REFERENCES bar(id) ON DELETE CASCADE INITIALLY DEFERRED;
  • 24. Query Clustering: Transaction Management WITH t AS ( INSERT INTO foo(id, bar_id) VALUES( DEFAULT, nextval(pg_get_serial_sequence('bar', 'id')) ) RETURNING id AS foo_id, bar_id ) INSERT INTO bar(id,foo_id) SELECT bar_id, foo_id FROM t RETURNING *;
  • 25. How'd He Do That?!? First try: David digs into the grammar and gets cut a few times.
  • 26. How'd He Do That?!? First try: Marko reworks the planner. It needs to know when it creates a ModifyTable node. These used to have another name.
  • 27. How'd He Do That?!? First try: Marko reworks the executor. It needs new nodes. Mmmm...nodes.
  • 28. How'd He Do That?!? Marko reworks the executor, Part II: Copy & Paste. Now it's getting ugly...
  • 29. How'd He Do That?!? Jaime Casanova, Tom Lane, and Robert Haas look at the reworked executor. D'oh!
  • 30. How'd He Do That?!? FAIL! Way too much code copying from top level to the new nodes.
  • 31. How'd He Do That?!? Planner changes for ModifyTable node (a few)
  • 32. How'd He Do That?!? Executor changes: ONE new node called ModifyTable
  • 33. How'd He Do That?!? Johto restructures the whole code base for the ModifyTable node. "The usual stuff," (he said casually) for new nodes.
  • 34. How'd He Do That?!? WIN!
  • 35. Next Steps INSERT, UPDATE and DELETE on the top level. RECURSIVE Optimization
  • 36. How'd He Do That?!? Questions? Comments?
  • 37. Thank You! http://2009.pgday.eu/feedback Copyright © 2009 David Fetter david.fetter@pgexperts.com All Rights Reserved