SlideShare a Scribd company logo
1 of 24
Download to read offline
Table Partitioning
PostgreSQL + Rails
Agnieszka Figiel, Cambridge Ruby User Group Mar 2014
What is table partitioning in
PostgreSQL?
1 logical table = n smaller physical tables
What are the benefits?
improved query performance for big tables *
* works best when results are coming from
single partition
When to consider partitioning?
Big table that cannot be queried efficiently, as
the index is enormous as well.
Rule of thumb: table does not fit into memory
How is data split?
By ranges:
year > 2010 AND year <= 2012
By lists of key values:
company_id = 5
How does it work?
At the heart of it lie 2 mechanisms:
➔ table inheritance
➔ table CHECK constraints
Table inheritance: schema
CREATE TABLE A (value INT);
CREATE TABLE B () INHERITS (A);
Table "public.a"
Column | Type | Modifiers
--------+---------+-----------
value | integer |
Table "public.b"
Column | Type | Modifiers
--------+---------+-----------
value | integer |
Inherits: a
Table inheritance: schema
CREATE TABLE C (extra_field TEXT) INHERITS (A);
Table "public.c"
Column | Type | Modifiers
-------------+---------+-----------
value | integer |
extra_field | text |
Inherits: a
NB: may inherit from multiple tables
Table inheritance: querying
INSERT INTO A VALUES (0);
INSERT INTO B VALUES (10);
INSERT INTO C VALUES (20, 'zonk');
SELECT * FROM A WHERE value < 20;
value
-------
0
10
SELECT * FROM ONLY A WHERE value < 20;
value
-------
0
What happened?
EXPLAIN ANALYZE SELECT * FROM A WHERE value < 20;
QUERY PLAN
----------------------------------------------------------------------------------------------------
Append (cost=0.00..69.38 rows=1290 width=4) (actual time=0.020..0.033 rows=2 loops=1)
-> Seq Scan on a (cost=0.00..4.00 rows=80 width=4) (actual time=0.019..0.021 rows=1 loops=1)
Filter: (value < 20)
-> Seq Scan on b (cost=0.00..40.00 rows=800 width=4) (actual time=0.005..0.006 rows=1 loops=1)
Filter: (value < 20)
-> Seq Scan on c (cost=0.00..25.38 rows=410 width=4) (actual time=0.005..0.005 rows=0 loops=1)
Filter: (value < 20)
Rows Removed by Filter: 1
Table CHECK constraint
CREATE TABLE A (value INT);
CREATE TABLE B (CHECK (value < 20)) INHERITS (A);
CREATE TABLE C (CHECK (value >= 20)) INHERITS (A);
INSERT INTO B VALUES (10);
INSERT INTO C VALUES (20);
INSERT INTO C VALUES(5);
ERROR: new row for relation "c" violates check constraint "c_value_check"
DETAIL: Failing row contains (5).
Ta da!
EXPLAIN ANALYZE SELECT * FROM A WHERE value < 20;
QUERY PLAN
----------------------------------------------------------------------------------------------------
Append (cost=0.00..40.00 rows=801 width=4) (actual time=0.015..0.017 rows=1 loops=1)
-> Seq Scan on a (cost=0.00..0.00 rows=1 width=4) (actual time=0.002..0.002 rows=0 loops=1)
Filter: (value < 20)
-> Seq Scan on b (cost=0.00..40.00 rows=800 width=4) (actual time=0.012..0.013 rows=1 loops=1)
Filter: (value < 20)
Gotcha #1
Make sure that:
SET constraint_exclusion = on;
Gotcha #2
All check constraints and not-null constraints on a parent table are
automatically inherited by its children.
Other types of constraints (unique, primary key, and foreign key constraints)
are not inherited.
Solution #2: create constraints or
indexes in all partitions
CREATE TABLE A (id serial NOT NULL, value INT NOT NULL);
CREATE TABLE B (
CONSTRAINT B_pkey PRIMARY KEY (id),
CHECK (value < 20)
) INHERITS (A);
CREATE TABLE C (
CONSTRAINT C_pkey PRIMARY KEY (id),
CHECK (value >= 20)
) INHERITS (A);
Gotcha #3
There is no practical way to enforce uniqueness of a SERIAL id across
partitions.
INSERT INTO B (value) VALUES (10);
INSERT INTO C (value) VALUES (20);
INSERT INTO C VALUES (1, 30);
SELECT * FROM A;
id | value
----+-------
1 | 10
2 | 20
1 | 30
Solution #3
➔ carry on and always filter by partitioning key
➔ use UUID (uuid-ossp)
Gotcha #4
Specifying that another table's column REFERENCES a(value) would allow the
other table to contain “a values”, but not “b or c values”. There is no good
workaround for this case.
How to insert / update rows?
➔ PostgreSQL docs recommend using triggers
➔ also possible to do it using rules (overhead, bulk)
Trigger example
CREATE OR REPLACE FUNCTION a_insert_trigger()
RETURNS TRIGGER AS $$
BEGIN
IF NEW.value < 20 THEN
INSERT INTO b VALUES (NEW.*);
ELSE
INSERT INTO c VALUES (NEW.*);
END IF;
RETURN NULL;
END;
$$
LANGUAGE plpgsql;
CREATE TRIGGER insert_a_trigger
BEFORE INSERT ON a
FOR EACH ROW EXECUTE PROCEDURE a_insert_trigger();
Partitioned gem
https://github.com/fiksu/partitioned
class Company < ActiveRecord::Base; end
class ByCompanyId < Partitioned::ByForeignKey
self.abstract_class = true
belongs_to :company
def self.partition_foreign_key
return :company_id
end
partitioned do |partition|
partition.index :id, :unique => true
end
end
class Employee < ByCompanyId; end
employee = Employee.from_partition(1).find(1)
UUID in Rails
Rails 4:
enable_extension 'uuid-ossp'
create_table :documents, id: :uuid do |t|
t.string :title
t.string :author
t.timestamps
end
Rails 3:
gem postgres_ext https://github.com/dockyard/postgres_ext
Actual performance improvements?
➔ table with ~13 mln rows
➔ partitioned by date into 8 partitions
➔ complex, long-running query
➔ baseline: 0.07 tps
➔ when results in single partition: 0.15 tps
➔ when results in 2 partitions: like baseline
References
➔ http://www.postgresql.org/docs/9.3/static/ddl-
partitioning.html
➔ PostgreSQL 9.0 High Performance Gregory Smith

More Related Content

What's hot

Transparent Data Encryption in PostgreSQL and Integration with Key Management...
Transparent Data Encryption in PostgreSQL and Integration with Key Management...Transparent Data Encryption in PostgreSQL and Integration with Key Management...
Transparent Data Encryption in PostgreSQL and Integration with Key Management...
Masahiko Sawada
 

What's hot (20)

MySQL Group Replication
MySQL Group ReplicationMySQL Group Replication
MySQL Group Replication
 
Using all of the high availability options in MariaDB
Using all of the high availability options in MariaDBUsing all of the high availability options in MariaDB
Using all of the high availability options in MariaDB
 
Monitoring Oracle Database Instances with Zabbix
Monitoring Oracle Database Instances with ZabbixMonitoring Oracle Database Instances with Zabbix
Monitoring Oracle Database Instances with Zabbix
 
Optimizing MariaDB for maximum performance
Optimizing MariaDB for maximum performanceOptimizing MariaDB for maximum performance
Optimizing MariaDB for maximum performance
 
Galera cluster for high availability
Galera cluster for high availability Galera cluster for high availability
Galera cluster for high availability
 
PostgreSQL WAL for DBAs
PostgreSQL WAL for DBAs PostgreSQL WAL for DBAs
PostgreSQL WAL for DBAs
 
Almost Perfect Service Discovery and Failover with ProxySQL and Orchestrator
Almost Perfect Service Discovery and Failover with ProxySQL and OrchestratorAlmost Perfect Service Discovery and Failover with ProxySQL and Orchestrator
Almost Perfect Service Discovery and Failover with ProxySQL and Orchestrator
 
Tanel Poder - Scripts and Tools short
Tanel Poder - Scripts and Tools shortTanel Poder - Scripts and Tools short
Tanel Poder - Scripts and Tools short
 
InnoDb Vs NDB Cluster
InnoDb Vs NDB ClusterInnoDb Vs NDB Cluster
InnoDb Vs NDB Cluster
 
ProxySQL in the Cloud
ProxySQL in the CloudProxySQL in the Cloud
ProxySQL in the Cloud
 
MariaDB Galera Cluster presentation
MariaDB Galera Cluster presentationMariaDB Galera Cluster presentation
MariaDB Galera Cluster presentation
 
MySQL InnoDB Cluster - A complete High Availability solution for MySQL
MySQL InnoDB Cluster - A complete High Availability solution for MySQLMySQL InnoDB Cluster - A complete High Availability solution for MySQL
MySQL InnoDB Cluster - A complete High Availability solution for MySQL
 
(New)SQL on AWS: Aurora serverless
(New)SQL on AWS: Aurora serverless(New)SQL on AWS: Aurora serverless
(New)SQL on AWS: Aurora serverless
 
ProxySQL for MySQL
ProxySQL for MySQLProxySQL for MySQL
ProxySQL for MySQL
 
Using Performance Insights to Optimize Database Performance (DAT402) - AWS re...
Using Performance Insights to Optimize Database Performance (DAT402) - AWS re...Using Performance Insights to Optimize Database Performance (DAT402) - AWS re...
Using Performance Insights to Optimize Database Performance (DAT402) - AWS re...
 
Query logging with proxysql
Query logging with proxysqlQuery logging with proxysql
Query logging with proxysql
 
Transparent Data Encryption in PostgreSQL and Integration with Key Management...
Transparent Data Encryption in PostgreSQL and Integration with Key Management...Transparent Data Encryption in PostgreSQL and Integration with Key Management...
Transparent Data Encryption in PostgreSQL and Integration with Key Management...
 
Zabbix Performance Tuning
Zabbix Performance TuningZabbix Performance Tuning
Zabbix Performance Tuning
 
Productizing Structured Streaming Jobs
Productizing Structured Streaming JobsProductizing Structured Streaming Jobs
Productizing Structured Streaming Jobs
 
Galera explained 3
Galera explained 3Galera explained 3
Galera explained 3
 

Similar to Table partitioning in PostgreSQL + Rails

Myth busters - performance tuning 101 2007
Myth busters - performance tuning 101 2007Myth busters - performance tuning 101 2007
Myth busters - performance tuning 101 2007
paulguerin
 
DDL,DML,SQL Functions and Joins
DDL,DML,SQL Functions and JoinsDDL,DML,SQL Functions and Joins
DDL,DML,SQL Functions and Joins
Ashwin Dinoriya
 
Entity Attribute Value (Eav)
Entity   Attribute   Value (Eav)Entity   Attribute   Value (Eav)
Entity Attribute Value (Eav)
Tâm
 

Similar to Table partitioning in PostgreSQL + Rails (20)

Less08 Schema
Less08 SchemaLess08 Schema
Less08 Schema
 
MySQL 8.0 NF : Common Table Expressions (CTE)
MySQL 8.0 NF : Common Table Expressions (CTE)MySQL 8.0 NF : Common Table Expressions (CTE)
MySQL 8.0 NF : Common Table Expressions (CTE)
 
Tableau + Redshift views for dummies
Tableau + Redshift views for dummiesTableau + Redshift views for dummies
Tableau + Redshift views for dummies
 
Myth busters - performance tuning 101 2007
Myth busters - performance tuning 101 2007Myth busters - performance tuning 101 2007
Myth busters - performance tuning 101 2007
 
Preparing for BIT – IT2301 Database Management Systems 2001f
Preparing for BIT – IT2301 Database Management Systems 2001fPreparing for BIT – IT2301 Database Management Systems 2001f
Preparing for BIT – IT2301 Database Management Systems 2001f
 
Optimizer features in recent releases of other databases
Optimizer features in recent releases of other databasesOptimizer features in recent releases of other databases
Optimizer features in recent releases of other databases
 
chapter 8 SQL.ppt
chapter 8 SQL.pptchapter 8 SQL.ppt
chapter 8 SQL.ppt
 
Chapter 07 ddl_sql
Chapter 07 ddl_sqlChapter 07 ddl_sql
Chapter 07 ddl_sql
 
Sql wksht-2
Sql wksht-2Sql wksht-2
Sql wksht-2
 
Mysql
MysqlMysql
Mysql
 
Mysql
MysqlMysql
Mysql
 
Mysql
MysqlMysql
Mysql
 
Db1 lecture4
Db1 lecture4Db1 lecture4
Db1 lecture4
 
Optimizing queries MySQL
Optimizing queries MySQLOptimizing queries MySQL
Optimizing queries MySQL
 
Session 8 connect your universal application with database .. builders & deve...
Session 8 connect your universal application with database .. builders & deve...Session 8 connect your universal application with database .. builders & deve...
Session 8 connect your universal application with database .. builders & deve...
 
DDL,DML,SQL Functions and Joins
DDL,DML,SQL Functions and JoinsDDL,DML,SQL Functions and Joins
DDL,DML,SQL Functions and Joins
 
Entity Attribute Value (Eav)
Entity   Attribute   Value (Eav)Entity   Attribute   Value (Eav)
Entity Attribute Value (Eav)
 
SQL Overview
SQL OverviewSQL Overview
SQL Overview
 
zekeLabs sql-slides
zekeLabs sql-slideszekeLabs sql-slides
zekeLabs sql-slides
 
45 Essential SQL Interview Questions
45 Essential SQL Interview Questions45 Essential SQL Interview Questions
45 Essential SQL Interview Questions
 

Recently uploaded

+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
Health
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
mohitmore19
 
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female serviceCALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
anilsa9823
 

Recently uploaded (20)

Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTV
 
Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with Precision
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptx
 
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.com
 
How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.js
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
 
Microsoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdfMicrosoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdf
 
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female serviceCALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Models
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf
 
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS LiveVip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
 
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AISyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
 

Table partitioning in PostgreSQL + Rails

  • 1. Table Partitioning PostgreSQL + Rails Agnieszka Figiel, Cambridge Ruby User Group Mar 2014
  • 2. What is table partitioning in PostgreSQL? 1 logical table = n smaller physical tables
  • 3. What are the benefits? improved query performance for big tables * * works best when results are coming from single partition
  • 4. When to consider partitioning? Big table that cannot be queried efficiently, as the index is enormous as well. Rule of thumb: table does not fit into memory
  • 5. How is data split? By ranges: year > 2010 AND year <= 2012 By lists of key values: company_id = 5
  • 6. How does it work? At the heart of it lie 2 mechanisms: ➔ table inheritance ➔ table CHECK constraints
  • 7. Table inheritance: schema CREATE TABLE A (value INT); CREATE TABLE B () INHERITS (A); Table "public.a" Column | Type | Modifiers --------+---------+----------- value | integer | Table "public.b" Column | Type | Modifiers --------+---------+----------- value | integer | Inherits: a
  • 8. Table inheritance: schema CREATE TABLE C (extra_field TEXT) INHERITS (A); Table "public.c" Column | Type | Modifiers -------------+---------+----------- value | integer | extra_field | text | Inherits: a NB: may inherit from multiple tables
  • 9. Table inheritance: querying INSERT INTO A VALUES (0); INSERT INTO B VALUES (10); INSERT INTO C VALUES (20, 'zonk'); SELECT * FROM A WHERE value < 20; value ------- 0 10 SELECT * FROM ONLY A WHERE value < 20; value ------- 0
  • 10. What happened? EXPLAIN ANALYZE SELECT * FROM A WHERE value < 20; QUERY PLAN ---------------------------------------------------------------------------------------------------- Append (cost=0.00..69.38 rows=1290 width=4) (actual time=0.020..0.033 rows=2 loops=1) -> Seq Scan on a (cost=0.00..4.00 rows=80 width=4) (actual time=0.019..0.021 rows=1 loops=1) Filter: (value < 20) -> Seq Scan on b (cost=0.00..40.00 rows=800 width=4) (actual time=0.005..0.006 rows=1 loops=1) Filter: (value < 20) -> Seq Scan on c (cost=0.00..25.38 rows=410 width=4) (actual time=0.005..0.005 rows=0 loops=1) Filter: (value < 20) Rows Removed by Filter: 1
  • 11. Table CHECK constraint CREATE TABLE A (value INT); CREATE TABLE B (CHECK (value < 20)) INHERITS (A); CREATE TABLE C (CHECK (value >= 20)) INHERITS (A); INSERT INTO B VALUES (10); INSERT INTO C VALUES (20); INSERT INTO C VALUES(5); ERROR: new row for relation "c" violates check constraint "c_value_check" DETAIL: Failing row contains (5).
  • 12. Ta da! EXPLAIN ANALYZE SELECT * FROM A WHERE value < 20; QUERY PLAN ---------------------------------------------------------------------------------------------------- Append (cost=0.00..40.00 rows=801 width=4) (actual time=0.015..0.017 rows=1 loops=1) -> Seq Scan on a (cost=0.00..0.00 rows=1 width=4) (actual time=0.002..0.002 rows=0 loops=1) Filter: (value < 20) -> Seq Scan on b (cost=0.00..40.00 rows=800 width=4) (actual time=0.012..0.013 rows=1 loops=1) Filter: (value < 20)
  • 13. Gotcha #1 Make sure that: SET constraint_exclusion = on;
  • 14. Gotcha #2 All check constraints and not-null constraints on a parent table are automatically inherited by its children. Other types of constraints (unique, primary key, and foreign key constraints) are not inherited.
  • 15. Solution #2: create constraints or indexes in all partitions CREATE TABLE A (id serial NOT NULL, value INT NOT NULL); CREATE TABLE B ( CONSTRAINT B_pkey PRIMARY KEY (id), CHECK (value < 20) ) INHERITS (A); CREATE TABLE C ( CONSTRAINT C_pkey PRIMARY KEY (id), CHECK (value >= 20) ) INHERITS (A);
  • 16. Gotcha #3 There is no practical way to enforce uniqueness of a SERIAL id across partitions. INSERT INTO B (value) VALUES (10); INSERT INTO C (value) VALUES (20); INSERT INTO C VALUES (1, 30); SELECT * FROM A; id | value ----+------- 1 | 10 2 | 20 1 | 30
  • 17. Solution #3 ➔ carry on and always filter by partitioning key ➔ use UUID (uuid-ossp)
  • 18. Gotcha #4 Specifying that another table's column REFERENCES a(value) would allow the other table to contain “a values”, but not “b or c values”. There is no good workaround for this case.
  • 19. How to insert / update rows? ➔ PostgreSQL docs recommend using triggers ➔ also possible to do it using rules (overhead, bulk)
  • 20. Trigger example CREATE OR REPLACE FUNCTION a_insert_trigger() RETURNS TRIGGER AS $$ BEGIN IF NEW.value < 20 THEN INSERT INTO b VALUES (NEW.*); ELSE INSERT INTO c VALUES (NEW.*); END IF; RETURN NULL; END; $$ LANGUAGE plpgsql; CREATE TRIGGER insert_a_trigger BEFORE INSERT ON a FOR EACH ROW EXECUTE PROCEDURE a_insert_trigger();
  • 21. Partitioned gem https://github.com/fiksu/partitioned class Company < ActiveRecord::Base; end class ByCompanyId < Partitioned::ByForeignKey self.abstract_class = true belongs_to :company def self.partition_foreign_key return :company_id end partitioned do |partition| partition.index :id, :unique => true end end class Employee < ByCompanyId; end employee = Employee.from_partition(1).find(1)
  • 22. UUID in Rails Rails 4: enable_extension 'uuid-ossp' create_table :documents, id: :uuid do |t| t.string :title t.string :author t.timestamps end Rails 3: gem postgres_ext https://github.com/dockyard/postgres_ext
  • 23. Actual performance improvements? ➔ table with ~13 mln rows ➔ partitioned by date into 8 partitions ➔ complex, long-running query ➔ baseline: 0.07 tps ➔ when results in single partition: 0.15 tps ➔ when results in 2 partitions: like baseline