SlideShare a Scribd company logo
1 of 40
Writeable CTEs,
 A Revolution in SQL
PGCon
May 20, 2011
Copyright © 2011
David Fetter dfetter@vmware.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 9.1:
Simple Partition Management

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

 ALTER TABLE log_201101 ADD
 CONSTRAINT right_month CHECK(
     ts >= '2011-01-01' AND
     ts < '2011-02-01');
For 9.1:
    Simple Partition Management

berliner@pgday_eu_2010:54321# WITH t1 AS (
    DELETE FROM ONLY log
    WHERE ts >='2011-01-01' AND ts < '2011-02-01'
    RETURNING *
)
INSERT INTO log_201101 SELECT * FROM t1;
INSERT 0 45270
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', 'davidfetter@postgresql.org')
    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','650 427 3751')
    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
        ('438 W. Grand Ave., Apartment 727','Oakland','California','USA','94612-2341'),
        ('3421 Hillview Avenue', 'Palo Alto','California','USA','94304')
),
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 *;
Materialized Views
 WITH t AS (
   DELETE FROM foo
   RETURNING a, b
 )
 INSERT INTO mv_foo
 SELECT a, SUM(b)
 FROM t GROUP BY a
Just Cool Stuff™
WITH t AS (
  INSERT INTO foo
  VALUES (...),...,(...)
  RETURNING a
)
SELECT bar.a, bar.b
FROM bar JOIN t USING(a)
Head-Scratcher:
 SNAPSHOTS
WITH t AS (DELETE FROM foo)
SELECT * FROM foo;

(0 rows)?
(100123 rows)?
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?!?


Marko Tiikkaja 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.
Finish the patch
   EXPLAIN ANALYZE
   SPI
   SQL functions
Bug fixes, cleanup, testing
RECURSIVE
Optimization
Future?

DCL (GRANT/REVOKE)
DDL (CREATE/ALTER/DROP)
Where Is It?!?

http://www.postgresql.org/developer/beta
WITH t AS (
    VALUES
        ('Questions'),
        ('Comments'),
        ('Rotten Tomatoes')
)
INSERT INTO davidfetter
SELECT * FROM t
RETURNING...
Thanks, eh!
 Copyright © 2011
 David Fetter dfetter@vmware.com
 All Rights Reserved

More Related Content

What's hot

What's hot (19)

Reading the .explain() Output
Reading the .explain() OutputReading the .explain() Output
Reading the .explain() Output
 
Sql commands
Sql commandsSql commands
Sql commands
 
Bibashsql
BibashsqlBibashsql
Bibashsql
 
[1062BPY12001] Data analysis with R / week 4
[1062BPY12001] Data analysis with R / week 4[1062BPY12001] Data analysis with R / week 4
[1062BPY12001] Data analysis with R / week 4
 
Sql
SqlSql
Sql
 
Tallerpractica
TallerpracticaTallerpractica
Tallerpractica
 
Sql
SqlSql
Sql
 
Sql
SqlSql
Sql
 
Computer practicals(part) Class 12
Computer practicals(part) Class 12Computer practicals(part) Class 12
Computer practicals(part) Class 12
 
키보드 키와 기호 이름 알아보기
키보드 키와 기호 이름 알아보기키보드 키와 기호 이름 알아보기
키보드 키와 기호 이름 알아보기
 
MY SQL
MY SQLMY SQL
MY SQL
 
Data Wrangling with dplyr
Data Wrangling with dplyrData Wrangling with dplyr
Data Wrangling with dplyr
 
Produce nice outputs for graphical, tabular and textual reporting in R-Report...
Produce nice outputs for graphical, tabular and textual reporting in R-Report...Produce nice outputs for graphical, tabular and textual reporting in R-Report...
Produce nice outputs for graphical, tabular and textual reporting in R-Report...
 
Appendix A Tables
Appendix A   TablesAppendix A   Tables
Appendix A Tables
 
ABAP EVENTS EXAMPLE
ABAP EVENTS EXAMPLEABAP EVENTS EXAMPLE
ABAP EVENTS EXAMPLE
 
Slaying the Dragon: Implementing a Programming Language in Ruby
Slaying the Dragon: Implementing a Programming Language in RubySlaying the Dragon: Implementing a Programming Language in Ruby
Slaying the Dragon: Implementing a Programming Language in Ruby
 
Sentencias básicas en oracle
Sentencias básicas en oracleSentencias básicas en oracle
Sentencias básicas en oracle
 
Explore Data using dplyr
Explore Data using dplyrExplore Data using dplyr
Explore Data using dplyr
 
Protocols
ProtocolsProtocols
Protocols
 

Similar to Writeable ct es_pgcon_may_2011

CS 542 Database Index Structures
CS 542 Database Index StructuresCS 542 Database Index Structures
CS 542 Database Index StructuresJ Singh
 
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 PerformanceJ Singh
 
SQL FILE FROM MOODLEUSE [master]GO Object Databa.pdf
SQL FILE FROM MOODLEUSE [master]GO Object Databa.pdfSQL FILE FROM MOODLEUSE [master]GO Object Databa.pdf
SQL FILE FROM MOODLEUSE [master]GO Object Databa.pdfarrowit1
 
Sql
SqlSql
SqlJoao
 
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)cruisercoder
 
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.docxwillcoxjanay
 
Appendix A Tables
Appendix A   TablesAppendix A   Tables
Appendix A TablesLiquidHub
 
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)Achmad Solichin
 
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/2015datastaxjp
 
Postgresql 9.3 overview
Postgresql 9.3 overviewPostgresql 9.3 overview
Postgresql 9.3 overviewAveic
 
Postgres can do THAT?
Postgres can do THAT?Postgres can do THAT?
Postgres can do THAT?alexbrasetvik
 
Sql practise for beginners
Sql practise for beginnersSql practise for beginners
Sql practise for beginnersISsoft
 

Similar to Writeable ct es_pgcon_may_2011 (20)

Writeable CTEs: The Next Big Thing
Writeable CTEs: The Next Big ThingWriteable CTEs: The Next Big Thing
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
 
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
 
SQL FILE FROM MOODLEUSE [master]GO Object Databa.pdf
SQL FILE FROM MOODLEUSE [master]GO Object Databa.pdfSQL FILE FROM MOODLEUSE [master]GO Object Databa.pdf
SQL FILE FROM MOODLEUSE [master]GO Object Databa.pdf
 
Sql
SqlSql
Sql
 
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)
 
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
 
Bd venta.sql
Bd venta.sqlBd venta.sql
Bd venta.sql
 
Db1 lecture4
Db1 lecture4Db1 lecture4
Db1 lecture4
 
Appendix A Tables
Appendix A   TablesAppendix A   Tables
Appendix A 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)
Les09 (using ddl statements to create and manage tables)
 
Les09
Les09Les09
Les09
 
Mysql schema emp dept
Mysql schema emp deptMysql schema emp dept
Mysql schema emp dept
 
SQL -PHP Tutorial
SQL -PHP TutorialSQL -PHP Tutorial
SQL -PHP Tutorial
 
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
 
Cassandra 2.2 & 3.0
Cassandra 2.2 & 3.0Cassandra 2.2 & 3.0
Cassandra 2.2 & 3.0
 
Postgresql 9.3 overview
Postgresql 9.3 overviewPostgresql 9.3 overview
Postgresql 9.3 overview
 
Postgres can do THAT?
Postgres can do THAT?Postgres can do THAT?
Postgres can do THAT?
 
Sql practise for beginners
Sql practise for beginnersSql practise for beginners
Sql practise for beginners
 

More from David Fetter

Assertions and how to use them
Assertions and how to use themAssertions and how to use them
Assertions and how to use themDavid Fetter
 
PostgreSQL Hooks for Fun and Profit
PostgreSQL Hooks for Fun and ProfitPostgreSQL Hooks for Fun and Profit
PostgreSQL Hooks for Fun and ProfitDavid Fetter
 
Tree tricks osdc_melbourne_20101124
Tree tricks osdc_melbourne_20101124Tree tricks osdc_melbourne_20101124
Tree tricks osdc_melbourne_20101124David Fetter
 
Grouping sets sfpug_20141118
Grouping sets sfpug_20141118Grouping sets sfpug_20141118
Grouping sets sfpug_20141118David Fetter
 
Rdbms roadmap 20140130
Rdbms roadmap 20140130Rdbms roadmap 20140130
Rdbms roadmap 20140130David Fetter
 
Slides pg conf_eu_20131031
Slides pg conf_eu_20131031Slides pg conf_eu_20131031
Slides pg conf_eu_20131031David Fetter
 
Federation with foreign_data_wrappers_pg_conf_eu_20131031
Federation with foreign_data_wrappers_pg_conf_eu_20131031Federation with foreign_data_wrappers_pg_conf_eu_20131031
Federation with foreign_data_wrappers_pg_conf_eu_20131031David Fetter
 
Intergalactic data speak_highload++_20131028
Intergalactic data speak_highload++_20131028Intergalactic data speak_highload++_20131028
Intergalactic data speak_highload++_20131028David Fetter
 
G so c_and_commitfests_and_pointy_hair_oh_my_sfpug_20131008
G so c_and_commitfests_and_pointy_hair_oh_my_sfpug_20131008G so c_and_commitfests_and_pointy_hair_oh_my_sfpug_20131008
G so c_and_commitfests_and_pointy_hair_oh_my_sfpug_20131008David Fetter
 
Ct es past_present_future_nycpgday_20130322
Ct es past_present_future_nycpgday_20130322Ct es past_present_future_nycpgday_20130322
Ct es past_present_future_nycpgday_20130322David Fetter
 
Universal data access_with_sql_med
Universal data access_with_sql_medUniversal data access_with_sql_med
Universal data access_with_sql_medDavid Fetter
 
Lightning sf perl_mongers_20120327
Lightning sf perl_mongers_20120327Lightning sf perl_mongers_20120327
Lightning sf perl_mongers_20120327David Fetter
 
Threat modeling sf_perl_mongers_20130227
Threat modeling sf_perl_mongers_20130227Threat modeling sf_perl_mongers_20130227
Threat modeling sf_perl_mongers_20130227David Fetter
 
Security revolutionized fosdem_20120205
Security revolutionized fosdem_20120205Security revolutionized fosdem_20120205
Security revolutionized fosdem_20120205David Fetter
 
View triggers pg_east_20110325
View triggers pg_east_20110325View triggers pg_east_20110325
View triggers pg_east_20110325David Fetter
 
PL/Parrot San Francisco Perl Mongers 2010/05/25
PL/Parrot San Francisco Perl Mongers 2010/05/25PL/Parrot San Francisco Perl Mongers 2010/05/25
PL/Parrot San Francisco Perl Mongers 2010/05/25David Fetter
 

More from David Fetter (16)

Assertions and how to use them
Assertions and how to use themAssertions and how to use them
Assertions and how to use them
 
PostgreSQL Hooks for Fun and Profit
PostgreSQL Hooks for Fun and ProfitPostgreSQL Hooks for Fun and Profit
PostgreSQL Hooks for Fun and Profit
 
Tree tricks osdc_melbourne_20101124
Tree tricks osdc_melbourne_20101124Tree tricks osdc_melbourne_20101124
Tree tricks osdc_melbourne_20101124
 
Grouping sets sfpug_20141118
Grouping sets sfpug_20141118Grouping sets sfpug_20141118
Grouping sets sfpug_20141118
 
Rdbms roadmap 20140130
Rdbms roadmap 20140130Rdbms roadmap 20140130
Rdbms roadmap 20140130
 
Slides pg conf_eu_20131031
Slides pg conf_eu_20131031Slides pg conf_eu_20131031
Slides pg conf_eu_20131031
 
Federation with foreign_data_wrappers_pg_conf_eu_20131031
Federation with foreign_data_wrappers_pg_conf_eu_20131031Federation with foreign_data_wrappers_pg_conf_eu_20131031
Federation with foreign_data_wrappers_pg_conf_eu_20131031
 
Intergalactic data speak_highload++_20131028
Intergalactic data speak_highload++_20131028Intergalactic data speak_highload++_20131028
Intergalactic data speak_highload++_20131028
 
G so c_and_commitfests_and_pointy_hair_oh_my_sfpug_20131008
G so c_and_commitfests_and_pointy_hair_oh_my_sfpug_20131008G so c_and_commitfests_and_pointy_hair_oh_my_sfpug_20131008
G so c_and_commitfests_and_pointy_hair_oh_my_sfpug_20131008
 
Ct es past_present_future_nycpgday_20130322
Ct es past_present_future_nycpgday_20130322Ct es past_present_future_nycpgday_20130322
Ct es past_present_future_nycpgday_20130322
 
Universal data access_with_sql_med
Universal data access_with_sql_medUniversal data access_with_sql_med
Universal data access_with_sql_med
 
Lightning sf perl_mongers_20120327
Lightning sf perl_mongers_20120327Lightning sf perl_mongers_20120327
Lightning sf perl_mongers_20120327
 
Threat modeling sf_perl_mongers_20130227
Threat modeling sf_perl_mongers_20130227Threat modeling sf_perl_mongers_20130227
Threat modeling sf_perl_mongers_20130227
 
Security revolutionized fosdem_20120205
Security revolutionized fosdem_20120205Security revolutionized fosdem_20120205
Security revolutionized fosdem_20120205
 
View triggers pg_east_20110325
View triggers pg_east_20110325View triggers pg_east_20110325
View triggers pg_east_20110325
 
PL/Parrot San Francisco Perl Mongers 2010/05/25
PL/Parrot San Francisco Perl Mongers 2010/05/25PL/Parrot San Francisco Perl Mongers 2010/05/25
PL/Parrot San Francisco Perl Mongers 2010/05/25
 

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 SolutionsEnterprise Knowledge
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slidevu2urc
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024Results
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxKatpro Technologies
 
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 AutomationSafe Software
 
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...Martijn de Jong
 
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 WorkerThousandEyes
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...apidays
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 
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...Enterprise Knowledge
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?Antenna Manufacturer Coco
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
 
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 productivityPrincipled Technologies
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc
 
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 2024The Digital Insurer
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CVKhem
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Scriptwesley chun
 
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...Neo4j
 

Recently uploaded (20)

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
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
 
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...
 
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
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
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...
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
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
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
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
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
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...
 

Writeable ct es_pgcon_may_2011

  • 1. Writeable CTEs, A Revolution in SQL PGCon May 20, 2011 Copyright © 2011 David Fetter dfetter@vmware.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 9.1: Simple Partition Management CREATE TABLE log ( ts TIMESTAMPTZ NOT NULL, msg TEXT NOT NULL );
  • 9. For 9.1: Simple Partition Management CREATE TABLE log_201101 () INHERITS(log); ALTER TABLE log_201101 ADD CONSTRAINT right_month CHECK( ts >= '2011-01-01' AND ts < '2011-02-01');
  • 10. For 9.1: Simple Partition Management berliner@pgday_eu_2010:54321# WITH t1 AS ( DELETE FROM ONLY log WHERE ts >='2011-01-01' AND ts < '2011-02-01' RETURNING * ) INSERT INTO log_201101 SELECT * FROM t1; INSERT 0 45270
  • 11. 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 );
  • 12. Query Clustering: I/O Minimization CREATE TABLE im ( id SERIAL PRIMARY KEY, provider TEXT NOT NULL, /* should be fk */ handle TEXT NOT NULL );
  • 13. Query Clustering: I/O Minimization CREATE TABLE phone ( id SERIAL PRIMARY KEY, country_code TEXT NOT NULL, phone_number TEXT NOT NULL, extension TEXT );
  • 14. 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 );
  • 15. 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) );
  • 16. Query Clustering: I/O Minimization WITH t_person AS ( INSERT INTO person (first_name, last_name) VALUES ('David', 'Fetter') RETURNING id ),
  • 17. Query Clustering: I/O Minimization t_im AS ( INSERT INTO im (provider, handle) VALUES ('Yahoo!', 'dfetter'), ('AIM', 'dfetter666'), ('XMPP', 'davidfetter@postgresql.org') RETURNING id ), t_person_im AS ( INSERT INTO person_im SELECT * FROM t_person CROSS JOIN t_im ),
  • 18. Query Clustering: I/O Minimization t_phone (phone_id) AS ( INSERT INTO phone (country_code, phone_number) VALUES ('+1','415 235 3778'), ('+1','650 427 3751') RETURNING id ), t_person_phone AS ( INSERT INTO person_phone SELECT * FROM t_person CROSS JOIN t_phone ),
  • 19. Query Clustering: I/O Minimization t_street AS ( INSERT INTO street (street1, city, state, country, post_code) VALUES ('438 W. Grand Ave., Apartment 727','Oakland','California','USA','94612-2341'), ('3421 Hillview Avenue', 'Palo Alto','California','USA','94304') ), t_person_street AS ( INSERT INTO person_street SELECT * FROM t_person CROSS JOIN t_street )
  • 20. Query Clustering: I/O Minimization VALUES(true);
  • 21. 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;
  • 22. 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 *;
  • 23. Materialized Views WITH t AS ( DELETE FROM foo RETURNING a, b ) INSERT INTO mv_foo SELECT a, SUM(b) FROM t GROUP BY a
  • 24. Just Cool Stuff™ WITH t AS ( INSERT INTO foo VALUES (...),...,(...) RETURNING a ) SELECT bar.a, bar.b FROM bar JOIN t USING(a)
  • 25. Head-Scratcher: SNAPSHOTS WITH t AS (DELETE FROM foo) SELECT * FROM foo; (0 rows)? (100123 rows)?
  • 26. How'd He Do That?!? First try: David digs into the grammar and gets cut a few times.
  • 27. 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.
  • 28. How'd He Do That?!? First try: Marko reworks the executor. It needs new nodes. Mmmm...nodes.
  • 29. How'd He Do That?!? Marko reworks the executor, Part II: Copy & Paste. Now it's getting ugly...
  • 30. How'd He Do That?!? Jaime Casanova, Tom Lane, and Robert Haas look at the reworked executor. D'oh!
  • 31. How'd He Do That?!? FAIL! Way too much code copying from top level to the new nodes.
  • 32. How'd He Do That?!? Planner changes for ModifyTable node (a few)
  • 33. How'd He Do That?!? Executor changes: ONE new node called ModifyTable
  • 34. How'd He Do That?!? Marko Tiikkaja restructures the whole code base for the ModifyTable node. "The usual stuff," (he said casually) for new nodes.
  • 35. How'd He Do That?!? WIN!
  • 36. Next Steps INSERT, UPDATE and DELETE on the top level. Finish the patch EXPLAIN ANALYZE SPI SQL functions Bug fixes, cleanup, testing RECURSIVE Optimization
  • 39. WITH t AS ( VALUES ('Questions'), ('Comments'), ('Rotten Tomatoes') ) INSERT INTO davidfetter SELECT * FROM t RETURNING...
  • 40. Thanks, eh! Copyright © 2011 David Fetter dfetter@vmware.com All Rights Reserved

Editor's Notes

  1. \n
  2. You could do some pretty cool stuff with them. Draw pretty pictures, for example.\n
  3. And now...\n
  4. Yep. That&apos;s NP-Hard. We can do it.\n
  5. \n
  6. Cook breakfast? Make coffee? Let&apos;s look again!\n
  7. \n
  8. Here&apos;s how we started.\n
  9. Here&apos;s how we started.\n
  10. Here&apos;s how we started.\n
  11. \n
  12. \n
  13. \n
  14. OK, now some join tables\n
  15. ...and let&apos;s start coding :)\n
  16. \n
  17. \n
  18. \n
  19. OK, we&apos;re done now :)\n
  20. How about some more sophisticated stuff?\n
  21. \n
  22. \n
  23. Thanks yet again, Marko! :)\n
  24. \n
  25. One snapshot per query.\n
  26. \n
  27. \n
  28. \n
  29. \n
  30. \n
  31. (In short, -1 from me. Tom Lane)\n
  32. \n
  33. \n
  34. \n
  35. \n
  36. IDU top-level, thanks to Hitoshi Harada\n
  37. Sometime over the course of this project, I realized that my hair had gotten pretty pointy.\n
  38. \n
  39. \n
  40. \n