SlideShare une entreprise Scribd logo
1  sur  74
PostgreSQL
Reuven M. Lerner (reuven@lerner.co.il)
             IL-Techtalks
        November 14th, 2012
Who am I?
• Web developer since 1993
• Linux Journal columnist since 1996
• Software architect, developer, consultant
• Mostly Ruby on Rails + PostgreSQL, but
  also Python, PHP, Perl, JavaScript, MySQL,
  MongoDB, and lots more...
• PostgreSQL user since (at least) 1997
What do I do?

• Web development, especially in Rails
• Teaching/training
• Coaching/consulting
What is a database?

 Store data
 confidently

                   Database


Retrieve data
   flexibly
Relational databases

   Define tables,
store data in them

                     Database


Retrieve data from
  related tables
Lots of options!

• Oracle
• Microsoft SQL Server
• IBM DB2
• MySQL
• PostgreSQL
How do you choose?
•   Integrity (ACID compliance)

•   Data types

•   Functionality

•   Tools

•   Extensibility

•   Documentation

•   Community
PostgreSQL
• Very fast, very scalable. (Just ask Skype.)
• Amazingly flexible, easily extensible.
• Rock-solid — no crashes, corruption,
  security issues for years
• Ridiculously easy administration
• It also happens to be free (MIT/BSD)
PostgreSQL
PostgreSQL
PostgreSQL
PostgreSQL
PostgreSQL
PostgreSQL
What about MySQL?
• PostgreSQL has many more features
• Not nearly as popular as MySQL
• No single company behind it
 • (A good thing, I think!)
• After using both, I prefer PostgreSQL
 • I’ll be happy to answer questions later
Brief history
• Ingres (Stonebreaker, Berkeley)
• Postgres (Stonebreaker, Berkeley)
• PostgreSQL project = Postgres + SQL
• About one major release per year
• Version 8.x — Windows port, recovery
• Version 9.0 — hot replication, upgrades
ACID
• ACID — basic standard for databases
 • Atomicity
 • Consistency
 • Isolation
 • Durability
• Pg has always been ACID compliant
Data types
• Boolean
• Numeric (integer, float, decimal)
• (var)char, text (infinitely large), binary
• sequences (guaranteed to be unique)
• Date/time and time intervals
• IP addresses, XML, enums, arrays
Or create your own!
Or create your own!

CREATE TYPE Person AS
(first_name TEXT, last_name
TEXT);
Or create your own!

CREATE TYPE Person AS
(first_name TEXT, last_name
TEXT);
Or create your own!

CREATE TYPE Person AS
(first_name TEXT, last_name
TEXT);


CREATE TABLE Members (group_id
INTEGER, member Person);
Strong typing
• PostgreSQL won’t automatically change
  types for you.
• This can be annoying at first — but it is
  meant to protect your data!
• You can cast from one type to another with
  the “cast” function or the :: operator
• You can also define your own casts
PostGIS
• Some people took this all the way
• Want to include geographical information?
• No problem — we’ve got PostGIS!
• Complete GIS solution, with data types and
  functions
• Keeps pace with main PostgreSQL revisions
Object oriented tables

• Employee table inherits from People table:
 CREATE TABLE Employee
 (employee_id INTEGER
 department_id INTEGER)
 INHERITS (People);
Foreign keys that work
CREATE TABLE DVDs (id SERIAL, title TEXT, store_id
INTEGER REFERENCES Stores);

INSERT INTO DVDs (title, store_id) VALUES ('Attack of
the Killer Tomatoes', 500);
Foreign keys that work
CREATE TABLE DVDs (id SERIAL, title TEXT, store_id
INTEGER REFERENCES Stores);

INSERT INTO DVDs (title, store_id) VALUES ('Attack of
the Killer Tomatoes', 500);

ERROR: insert or update on table "dvds" violates
foreign key constraint "dvds_store_id_fkey"
Foreign keys that work
CREATE TABLE DVDs (id SERIAL, title TEXT, store_id
INTEGER REFERENCES Stores);

INSERT INTO DVDs (title, store_id) VALUES ('Attack of
the Killer Tomatoes', 500);

ERROR: insert or update on table "dvds" violates
foreign key constraint "dvds_store_id_fkey"

DETAIL: Key (store_id)=(500) is not present in table
"stores".
Foreign keys that work
CREATE TABLE DVDs (id SERIAL, title TEXT, store_id
INTEGER REFERENCES Stores);

INSERT INTO DVDs (title, store_id) VALUES ('Attack of
the Killer Tomatoes', 500);

ERROR: insert or update on table "dvds" violates
foreign key constraint "dvds_store_id_fkey"

DETAIL: Key (store_id)=(500) is not present in table
"stores".

ERROR: insert or update on table "dvds" violates
foreign key constraint "dvds_store_id_fkey"
Foreign keys that work
CREATE TABLE DVDs (id SERIAL, title TEXT, store_id
INTEGER REFERENCES Stores);

INSERT INTO DVDs (title, store_id) VALUES ('Attack of
the Killer Tomatoes', 500);

ERROR: insert or update on table "dvds" violates
foreign key constraint "dvds_store_id_fkey"

DETAIL: Key (store_id)=(500) is not present in table
"stores".

ERROR: insert or update on table "dvds" violates
foreign key constraint "dvds_store_id_fkey"

DETAIL: Key (store_id)=(500) is not present in table
"stores".
Custom validity checks
CREATE TABLE DVDs (id SERIAL, title
TEXT check (length(title) > 3),
store_id INTEGER REFERENCES
Stores);
INSERT INTO DVDs (title, store_id)
VALUES ('AB', 500);
Custom validity checks
CREATE TABLE DVDs (id SERIAL, title
TEXT check (length(title) > 3),
store_id INTEGER REFERENCES
Stores);
INSERT INTO DVDs (title, store_id)
VALUES ('AB', 500);
ERROR: new row for relation "dvds"
violates check constraint
"dvds_title_check"
No more bad dates!
INSERT INTO UPDATES
(created_at) values ('32-
feb-2008');
No more bad dates!
INSERT INTO UPDATES
(created_at) values ('32-
feb-2008');
ERROR: date/time field value
out of range: "32-feb-2008"
No more bad dates!
INSERT INTO UPDATES
(created_at) values ('32-
feb-2008');
ERROR: date/time field value
out of range: "32-feb-2008"
LINE 1: insert into updates
(created_at) values ('32-
feb-2008');
Timestamp vs. Interval
testdb=# select now();
              now
-------------------------------
 2010-10-31 08:58:23.365792+02
(1 row)
                                  Point in time

testdb=# select now() - interval '3 days';
           ?column?
-------------------------------
 2010-10-28 08:58:28.870011+02
                                  Difference between
(1 row)                              points in time
Built-in functions
• Math
• Text processing (including regexps)
• Date/time calculations
• Conditionals (CASE, COALESCE, NULLIF)
  for use in queries
• Extensive library of geometrical functions
Or write your own!
• PL/pgSQL
• PL/Perl
• PL/Python
• PL/Ruby
• PL/R
• PL/Tcl
Or write your own!
CREATE OR REPLACE FUNCTION remove_cache_tables() RETURNS
VOID AS $$
DECLARE
      r pg_catalog.pg_tables%rowtype;
BEGIN
      FOR r IN SELECT * FROM pg_catalog.pg_tables
      WHERE schemaname = 'public'
        AND tablename ILIKE 'cache_%'
      LOOP
           RAISE NOTICE 'Now dropping table %', r.tablename;
           EXECUTE 'DROP TABLE ' || r.tablename;
      END LOOP;
END;
$$ LANGUAGE 'plpgsql';
Another example
CREATE OR REPLACE FUNCTION store_hostname() RETURNS
TRIGGER AS $store_hostname$

    BEGIN

           NEW.hostname := 'http://' ||

            substring(NEW.url, '(?:http://)?([^/]+)');

           RETURN NEW;

    END;

$store_hostname$ LANGUAGE plpgsql;
Triggers

• Yes, that last function was a trigger
• Automatically execute functions upon
  INSERT, UPDATE, and/or DELETE
• Can execute before or after
• Very powerful, very fast
Function possibilities
• Computing values, strings
• Returning table-like sets of values
• Encapsulating queries
• Dynamically generating queries via strings
• Triggers: Modifying data before it is inserted
  or updated
Why use a PL/lang?

• Other libraries (e.g., CPAN for Perl)
• Faster, optimized functions (eg., R)
• Programmer familiarity
• Cached query plans
Views and rules
• Views are stored SELECT statements
• Pretend that something is a read-only table
• Rules let you turn it into a read/write table
 • Intercept and rewrite incoming query
 • Check or change data
 • Change where data is stored
Full-text indexing

• Built into PostgreSQL
• Handles stop words, different languages,
  synonyms, and even (often) stemming
• Very powerful, but it can take some time to
  get configured correctly
Transactions
• In PostgreSQL from the beginning
• Use transactions for just about anything:
  BEGIN
  DROP TABLE DVDs;
  ROLLBACK;
  SELECT * FROM DVDs; -- Works!
Savepoints
(or, sub-transactions)
BEGIN;
INSERT INTO table1 VALUES (1);
SAVEPOINT my_savepoint;
INSERT INTO table1 VALUES (2);
ROLLBACK TO SAVEPOINT my_savepoint;
INSERT INTO table1 VALUES (3);
COMMIT;
MVCC
• Readers and writers don’t block each other
• “Multi-version concurrency control”
• xmin, xmax on each tuple; rows are those
  tuples with txid_current between them
• Old versions stick around until vacuumed
 • Autovacuum removes even this issue
MVCC
• Look at a row’s xmin and xmax
• Look at txid_current()
• Start transaction; look at row’s xmin/xmax
• Look at xmin/xmax on that row from
  another session
• Commit, and look again at both!
Downsides of MVCC
• MVCC is usually fantastic
• But if you insert or update many rows, and
  then do a COUNT(*), things will be slow
• There are solutions — including more
  aggressive auto-vacuuming
• 9.2 introduced features that improved this
Indexing
• Regular, unique indexes
• Functional indexes
 • Index calling a function on a column
• Partial indexes
 • Index only rows matching criteria
• Cluster table on an index
CTEs
• Adds a “WITH” statement, which defines a
  sorta-kinda temp table
• You can then query that same temp table
• Makes many queries easier to read, write,
  without a real temp table
• Better yet: CTEs can be recursive, for
  everything from Fibonacci to org charts
Speed and scalability
• MVCC + a smart query optimizer makes
  PostgreSQL pretty fast and smart
• Statistics based on previous query results
  inform the query planner
• Several scan types, join types are weighed
• Benchmarks consistently show excellent
  performance with high mixes of read/write
WAL
• All activity in the database is put in “write-
  ahead logs” before it happens
• If the database server fails, it replays the
  WALs, then continues
• You can change how often WALs are
  written, to improve performance
• PITR — restore database from WALs
Log shipping
• Copy WALs to a second, identical server —
  known as “log shipping” — and you have a
  backup
• If the primary server goes down, you can
  bring the secondary up in its place
• This was known as “warm standby,” and
  worked in 8.4
Hot standby,
 streaming replication
• As of 9.0, you don’t have to do this
• You can have the primary stream the
  information to the secondary
 • Almost-instant updates
• The secondary machine can answer read-
  only queries (“hot standby”), not just
  handle failover
Extensions
• Provides a standardized mechanism for
  downloading, installing, and versioning
  extensions
• New data types, functions, languages are
  possible
• Download, search via pgxn.org
• Similar to CPAN, PyPi, or Ruby gems
SQL/MED

• SQL/MED was introduced in 9.1
• Query information from other databases
  (and database-like interfaces)
• So if you have data in MySQL, Oracle,
  CSV ... just install a wrapper, and you can
  query it like a PostgreSQL table
Unlogged tables

• All actions are logged in WALs
• That adds some overhead, which isn’t
  required by throwaway data
• Unlogged tables (different from temp
  tables!) offer a speedup, in exchange for
  less reliability
New in 9.2
• JSON support
• Range types, for handling
• Much more scalable — from 24 cores and
  75k queries/sec to 64 cores and 350k
  queries/sec
• Index-only queries (“covering indexes”)
• Cascading replication
Web problems
• PostgreSQL is great as a Web backend
• But if you use an ORM (e.g., ActiveRecord),
  you are probably losing much of the power
  • e.g., foreign keys, CTE, triggers, and views
• No good way to bridge this gap — for now
• There are always methods, but this is an
  area that definitely needs some work
Tablespaces
• You can create any number of
  “tablespaces,” separate storage areas
• Put tables, indexes on different tablespaces
 • Most useful with multiple disks
• Separate tables (or parts of a partitioned
  table)... or separate tables from indexes
Partitioning
• Combine object-oriented tables, CHECK
  clauses, and tablespaces for partitioning
• Example: Invoices from Jan-June go in table
  “q12”, and July-December go in table “q34”
• Now PostgreSQL knows where to look
  when you SELECT from the parent table
• Note that INSERT requires a trigger
Reflection

• pg_catalog schema contains everything
  about your database
  • Tables, functions, views, etc.
• You can learn a great deal about
  PostgreSQL by looking through the
  pg_catalog schema
Advanced uses

• GridSQL: Split a query across multiple
  PostgreSQL servers
• Very large-scale data warehousing:
  Greenplum
Client libraries
• libpq (in C)        • Java (JDBC)
• Others by 3    rd   • .NET (npgsql)
  parties:            • ODBC
• Python              • JavaScript (!)
• Ruby                • Just about any
                        language you can
• Perl                  imagine
Tools
• Yeah, tools are more primitive
• If you love GUIs, and hate the command
  line, then PostgreSQL will be hard for you
• PgAdmin and other tools are OK, but not
  really up to the task for “real” work
 • PgAdmin does provide some graphical
    query building and “explain” output
Windows compatibility
• It works on Windows
• .NET drivers work, as well
• Logging is far from perfect (can go to the
  Windows log tool, but not filtered well)
• Configuration is still in a text file, foreign to
  most Windows people
• Windows is still a second-class citizen
Who uses it?
• Affilias
              • IMDB
• Apple
              • Skype
• BASF
              • Sourceforge
• Cisco
              • Heroku
• CD Baby
              • Checkpoint
• Etsy
Who supports it?

• EnterpriseDB — products and services
• 2 Quadrant
   nd


• Many freelancers (like me!)
PostgreSQL problems
• Tuning is still hard (but getting easier)
• Double quotes
• Lack of good GUI-based tools
• Some features (e.g., materialized views) that
  people want without having to resort to
  hacks and triggers/rules
• Multi-master (of course!)
Bottom line
• PostgreSQL: BSD licensed, easy to install,
  easy to use, easy to administer
• Still not quite up to commercial databases
  regarding features — but not far behind
• More than good enough for places like
  Skype and Affilias; probably good enough
  for you!
Want to learn more?
• Mailing lists, wikis, and blogs
 • All at http://postgresql.org/
 • http://planetpostgresql.org
• PostgreSQL training, consulting,
  development, hand-holding, and general
  encouragement
Thanks!
(Any questions?)



     reuven@lerner.co.il
   http://www.lerner.co.il/
        054-496-8405
“reuvenlerner” on Skype/AIM

Contenu connexe

Tendances

How does PostgreSQL work with disks: a DBA's checklist in detail. PGConf.US 2015
How does PostgreSQL work with disks: a DBA's checklist in detail. PGConf.US 2015How does PostgreSQL work with disks: a DBA's checklist in detail. PGConf.US 2015
How does PostgreSQL work with disks: a DBA's checklist in detail. PGConf.US 2015PostgreSQL-Consulting
 
Introduction to PostgreSQL
Introduction to PostgreSQLIntroduction to PostgreSQL
Introduction to PostgreSQLJoel Brewer
 
Postgresql database administration volume 1
Postgresql database administration volume 1Postgresql database administration volume 1
Postgresql database administration volume 1Federico Campoli
 
PostgreSQL Performance Tuning
PostgreSQL Performance TuningPostgreSQL Performance Tuning
PostgreSQL Performance Tuningelliando dias
 
PostgreSQL HA
PostgreSQL   HAPostgreSQL   HA
PostgreSQL HAharoonm
 
ClickHouse in Real Life. Case Studies and Best Practices, by Alexander Zaitsev
ClickHouse in Real Life. Case Studies and Best Practices, by Alexander ZaitsevClickHouse in Real Life. Case Studies and Best Practices, by Alexander Zaitsev
ClickHouse in Real Life. Case Studies and Best Practices, by Alexander ZaitsevAltinity Ltd
 
Mastering PostgreSQL Administration
Mastering PostgreSQL AdministrationMastering PostgreSQL Administration
Mastering PostgreSQL AdministrationEDB
 
PostgreSQL Administration for System Administrators
PostgreSQL Administration for System AdministratorsPostgreSQL Administration for System Administrators
PostgreSQL Administration for System AdministratorsCommand Prompt., Inc
 
Getting started with postgresql
Getting started with postgresqlGetting started with postgresql
Getting started with postgresqlbotsplash.com
 
Json in Postgres - the Roadmap
 Json in Postgres - the Roadmap Json in Postgres - the Roadmap
Json in Postgres - the RoadmapEDB
 
OpenGurukul : Database : PostgreSQL
OpenGurukul : Database : PostgreSQLOpenGurukul : Database : PostgreSQL
OpenGurukul : Database : PostgreSQLOpen Gurukul
 
PostgreSQL- An Introduction
PostgreSQL- An IntroductionPostgreSQL- An Introduction
PostgreSQL- An IntroductionSmita Prasad
 
Deep dive into PostgreSQL statistics.
Deep dive into PostgreSQL statistics.Deep dive into PostgreSQL statistics.
Deep dive into PostgreSQL statistics.Alexey Lesovsky
 
MySQL High Availability Solutions
MySQL High Availability SolutionsMySQL High Availability Solutions
MySQL High Availability SolutionsMydbops
 
Working with JSON Data in PostgreSQL vs. MongoDB
Working with JSON Data in PostgreSQL vs. MongoDBWorking with JSON Data in PostgreSQL vs. MongoDB
Working with JSON Data in PostgreSQL vs. MongoDBScaleGrid.io
 
Patroni - HA PostgreSQL made easy
Patroni - HA PostgreSQL made easyPatroni - HA PostgreSQL made easy
Patroni - HA PostgreSQL made easyAlexander Kukushkin
 
The Basics of MongoDB
The Basics of MongoDBThe Basics of MongoDB
The Basics of MongoDBvaluebound
 

Tendances (20)

How does PostgreSQL work with disks: a DBA's checklist in detail. PGConf.US 2015
How does PostgreSQL work with disks: a DBA's checklist in detail. PGConf.US 2015How does PostgreSQL work with disks: a DBA's checklist in detail. PGConf.US 2015
How does PostgreSQL work with disks: a DBA's checklist in detail. PGConf.US 2015
 
Introduction to PostgreSQL
Introduction to PostgreSQLIntroduction to PostgreSQL
Introduction to PostgreSQL
 
Postgresql database administration volume 1
Postgresql database administration volume 1Postgresql database administration volume 1
Postgresql database administration volume 1
 
PostgreSQL Performance Tuning
PostgreSQL Performance TuningPostgreSQL Performance Tuning
PostgreSQL Performance Tuning
 
Postgresql Federation
Postgresql FederationPostgresql Federation
Postgresql Federation
 
PostgreSQL HA
PostgreSQL   HAPostgreSQL   HA
PostgreSQL HA
 
ClickHouse in Real Life. Case Studies and Best Practices, by Alexander Zaitsev
ClickHouse in Real Life. Case Studies and Best Practices, by Alexander ZaitsevClickHouse in Real Life. Case Studies and Best Practices, by Alexander Zaitsev
ClickHouse in Real Life. Case Studies and Best Practices, by Alexander Zaitsev
 
Mastering PostgreSQL Administration
Mastering PostgreSQL AdministrationMastering PostgreSQL Administration
Mastering PostgreSQL Administration
 
PostgreSQL Administration for System Administrators
PostgreSQL Administration for System AdministratorsPostgreSQL Administration for System Administrators
PostgreSQL Administration for System Administrators
 
Postgre sql best_practices
Postgre sql best_practicesPostgre sql best_practices
Postgre sql best_practices
 
Getting started with postgresql
Getting started with postgresqlGetting started with postgresql
Getting started with postgresql
 
Json in Postgres - the Roadmap
 Json in Postgres - the Roadmap Json in Postgres - the Roadmap
Json in Postgres - the Roadmap
 
OpenGurukul : Database : PostgreSQL
OpenGurukul : Database : PostgreSQLOpenGurukul : Database : PostgreSQL
OpenGurukul : Database : PostgreSQL
 
PostgreSQL- An Introduction
PostgreSQL- An IntroductionPostgreSQL- An Introduction
PostgreSQL- An Introduction
 
Deep dive into PostgreSQL statistics.
Deep dive into PostgreSQL statistics.Deep dive into PostgreSQL statistics.
Deep dive into PostgreSQL statistics.
 
MySQL High Availability Solutions
MySQL High Availability SolutionsMySQL High Availability Solutions
MySQL High Availability Solutions
 
Working with JSON Data in PostgreSQL vs. MongoDB
Working with JSON Data in PostgreSQL vs. MongoDBWorking with JSON Data in PostgreSQL vs. MongoDB
Working with JSON Data in PostgreSQL vs. MongoDB
 
Patroni - HA PostgreSQL made easy
Patroni - HA PostgreSQL made easyPatroni - HA PostgreSQL made easy
Patroni - HA PostgreSQL made easy
 
NoSQL databases
NoSQL databasesNoSQL databases
NoSQL databases
 
The Basics of MongoDB
The Basics of MongoDBThe Basics of MongoDB
The Basics of MongoDB
 

Similaire à PostgreSQL

PostgreSQL 9.0 & The Future
PostgreSQL 9.0 & The FuturePostgreSQL 9.0 & The Future
PostgreSQL 9.0 & The FutureAaron Thul
 
PostgreSQL - It's kind've a nifty database
PostgreSQL - It's kind've a nifty databasePostgreSQL - It's kind've a nifty database
PostgreSQL - It's kind've a nifty databaseBarry Jones
 
Introduction to Azure Data Lake and U-SQL for SQL users (SQL Saturday 635)
Introduction to Azure Data Lake and U-SQL for SQL users (SQL Saturday 635)Introduction to Azure Data Lake and U-SQL for SQL users (SQL Saturday 635)
Introduction to Azure Data Lake and U-SQL for SQL users (SQL Saturday 635)Michael Rys
 
MYSQL Query Anti-Patterns That Can Be Moved to Sphinx
MYSQL Query Anti-Patterns That Can Be Moved to SphinxMYSQL Query Anti-Patterns That Can Be Moved to Sphinx
MYSQL Query Anti-Patterns That Can Be Moved to SphinxPythian
 
Object Relational Database Management System
Object Relational Database Management SystemObject Relational Database Management System
Object Relational Database Management SystemAmar Myana
 
ActiveJDBC - ActiveRecord implementation in Java
ActiveJDBC - ActiveRecord implementation in JavaActiveJDBC - ActiveRecord implementation in Java
ActiveJDBC - ActiveRecord implementation in Javaipolevoy
 
Introducing U-SQL (SQLPASS 2016)
Introducing U-SQL (SQLPASS 2016)Introducing U-SQL (SQLPASS 2016)
Introducing U-SQL (SQLPASS 2016)Michael Rys
 
PostgreSQL, your NoSQL database
PostgreSQL, your NoSQL databasePostgreSQL, your NoSQL database
PostgreSQL, your NoSQL databaseReuven Lerner
 
Bye bye $GLOBALS['TYPO3_DB']
Bye bye $GLOBALS['TYPO3_DB']Bye bye $GLOBALS['TYPO3_DB']
Bye bye $GLOBALS['TYPO3_DB']Jan Helke
 
xjtrutdctrd5454drxxresersestryugyufy6rythgfytfyt
xjtrutdctrd5454drxxresersestryugyufy6rythgfytfytxjtrutdctrd5454drxxresersestryugyufy6rythgfytfyt
xjtrutdctrd5454drxxresersestryugyufy6rythgfytfytWrushabhShirsat3
 
An Introduction to Elastic Search.
An Introduction to Elastic Search.An Introduction to Elastic Search.
An Introduction to Elastic Search.Jurriaan Persyn
 
Webinar 2017. Supercharge your analytics with ClickHouse. Alexander Zaitsev
Webinar 2017. Supercharge your analytics with ClickHouse. Alexander ZaitsevWebinar 2017. Supercharge your analytics with ClickHouse. Alexander Zaitsev
Webinar 2017. Supercharge your analytics with ClickHouse. Alexander ZaitsevAltinity Ltd
 
Migrating To PostgreSQL
Migrating To PostgreSQLMigrating To PostgreSQL
Migrating To PostgreSQLGrant Fritchey
 
Yapc10 Cdt World Domination
Yapc10   Cdt World DominationYapc10   Cdt World Domination
Yapc10 Cdt World DominationcPanel
 
Walkthrough Neo4j 1.9 & 2.0
Walkthrough Neo4j 1.9 & 2.0Walkthrough Neo4j 1.9 & 2.0
Walkthrough Neo4j 1.9 & 2.0Neo4j
 
•Design (create) 3 questions for a quiz show game and design regular.pdf
•Design (create) 3 questions for a quiz show game and design regular.pdf•Design (create) 3 questions for a quiz show game and design regular.pdf
•Design (create) 3 questions for a quiz show game and design regular.pdfjyothimuppasani1
 
An introduction to mysql Performance Optimization (2008)
An introduction to mysql Performance Optimization (2008)An introduction to mysql Performance Optimization (2008)
An introduction to mysql Performance Optimization (2008)lmrei
 

Similaire à PostgreSQL (20)

PostgreSQL 9.0 & The Future
PostgreSQL 9.0 & The FuturePostgreSQL 9.0 & The Future
PostgreSQL 9.0 & The Future
 
PostgreSQL - It's kind've a nifty database
PostgreSQL - It's kind've a nifty databasePostgreSQL - It's kind've a nifty database
PostgreSQL - It's kind've a nifty database
 
Mathias test
Mathias testMathias test
Mathias test
 
Introduction to Azure Data Lake and U-SQL for SQL users (SQL Saturday 635)
Introduction to Azure Data Lake and U-SQL for SQL users (SQL Saturday 635)Introduction to Azure Data Lake and U-SQL for SQL users (SQL Saturday 635)
Introduction to Azure Data Lake and U-SQL for SQL users (SQL Saturday 635)
 
MYSQL Query Anti-Patterns That Can Be Moved to Sphinx
MYSQL Query Anti-Patterns That Can Be Moved to SphinxMYSQL Query Anti-Patterns That Can Be Moved to Sphinx
MYSQL Query Anti-Patterns That Can Be Moved to Sphinx
 
Object Relational Database Management System
Object Relational Database Management SystemObject Relational Database Management System
Object Relational Database Management System
 
ActiveJDBC - ActiveRecord implementation in Java
ActiveJDBC - ActiveRecord implementation in JavaActiveJDBC - ActiveRecord implementation in Java
ActiveJDBC - ActiveRecord implementation in Java
 
Introducing U-SQL (SQLPASS 2016)
Introducing U-SQL (SQLPASS 2016)Introducing U-SQL (SQLPASS 2016)
Introducing U-SQL (SQLPASS 2016)
 
PostgreSQL, your NoSQL database
PostgreSQL, your NoSQL databasePostgreSQL, your NoSQL database
PostgreSQL, your NoSQL database
 
Full Text Search In PostgreSQL
Full Text Search In PostgreSQLFull Text Search In PostgreSQL
Full Text Search In PostgreSQL
 
Bye bye $GLOBALS['TYPO3_DB']
Bye bye $GLOBALS['TYPO3_DB']Bye bye $GLOBALS['TYPO3_DB']
Bye bye $GLOBALS['TYPO3_DB']
 
unit-ii.pptx
unit-ii.pptxunit-ii.pptx
unit-ii.pptx
 
xjtrutdctrd5454drxxresersestryugyufy6rythgfytfyt
xjtrutdctrd5454drxxresersestryugyufy6rythgfytfytxjtrutdctrd5454drxxresersestryugyufy6rythgfytfyt
xjtrutdctrd5454drxxresersestryugyufy6rythgfytfyt
 
An Introduction to Elastic Search.
An Introduction to Elastic Search.An Introduction to Elastic Search.
An Introduction to Elastic Search.
 
Webinar 2017. Supercharge your analytics with ClickHouse. Alexander Zaitsev
Webinar 2017. Supercharge your analytics with ClickHouse. Alexander ZaitsevWebinar 2017. Supercharge your analytics with ClickHouse. Alexander Zaitsev
Webinar 2017. Supercharge your analytics with ClickHouse. Alexander Zaitsev
 
Migrating To PostgreSQL
Migrating To PostgreSQLMigrating To PostgreSQL
Migrating To PostgreSQL
 
Yapc10 Cdt World Domination
Yapc10   Cdt World DominationYapc10   Cdt World Domination
Yapc10 Cdt World Domination
 
Walkthrough Neo4j 1.9 & 2.0
Walkthrough Neo4j 1.9 & 2.0Walkthrough Neo4j 1.9 & 2.0
Walkthrough Neo4j 1.9 & 2.0
 
•Design (create) 3 questions for a quiz show game and design regular.pdf
•Design (create) 3 questions for a quiz show game and design regular.pdf•Design (create) 3 questions for a quiz show game and design regular.pdf
•Design (create) 3 questions for a quiz show game and design regular.pdf
 
An introduction to mysql Performance Optimization (2008)
An introduction to mysql Performance Optimization (2008)An introduction to mysql Performance Optimization (2008)
An introduction to mysql Performance Optimization (2008)
 

Plus de Reuven Lerner

Technical training business talk.key
Technical training business talk.keyTechnical training business talk.key
Technical training business talk.keyReuven Lerner
 
Big Data — Your new best friend
Big Data — Your new best friendBig Data — Your new best friend
Big Data — Your new best friendReuven Lerner
 
Python's magic methods
Python's magic methodsPython's magic methods
Python's magic methodsReuven Lerner
 
What can Ruby learn from Python (and vice versa)?
What can Ruby learn from Python (and vice versa)?What can Ruby learn from Python (and vice versa)?
What can Ruby learn from Python (and vice versa)?Reuven Lerner
 
Functional Python Webinar from October 22nd, 2014
Functional Python Webinar from October 22nd, 2014Functional Python Webinar from October 22nd, 2014
Functional Python Webinar from October 22nd, 2014Reuven Lerner
 
Web APIs: The future of software
Web APIs: The future of softwareWeb APIs: The future of software
Web APIs: The future of softwareReuven Lerner
 
Intro to cloud computing — MegaCOMM 2013, Jerusalem
Intro to cloud computing — MegaCOMM 2013, JerusalemIntro to cloud computing — MegaCOMM 2013, Jerusalem
Intro to cloud computing — MegaCOMM 2013, JerusalemReuven Lerner
 
Modern Web technologies (and why you should care): Megacomm, Jerusalem, Febru...
Modern Web technologies (and why you should care): Megacomm, Jerusalem, Febru...Modern Web technologies (and why you should care): Megacomm, Jerusalem, Febru...
Modern Web technologies (and why you should care): Megacomm, Jerusalem, Febru...Reuven Lerner
 
Rails development environment talk
Rails development environment talkRails development environment talk
Rails development environment talkReuven Lerner
 
Git talk from Open 2011 conference in Israel
Git talk from Open 2011 conference in IsraelGit talk from Open 2011 conference in Israel
Git talk from Open 2011 conference in IsraelReuven Lerner
 
Dynamic languages, for software craftmanship group
Dynamic languages, for software craftmanship groupDynamic languages, for software craftmanship group
Dynamic languages, for software craftmanship groupReuven Lerner
 
Modern Web Technologies — Jerusalem Web Professionals, January 2011
Modern Web Technologies — Jerusalem Web Professionals, January 2011Modern Web Technologies — Jerusalem Web Professionals, January 2011
Modern Web Technologies — Jerusalem Web Professionals, January 2011Reuven Lerner
 
PostgreSQL talk, Database 2011 conference
PostgreSQL talk, Database 2011 conferencePostgreSQL talk, Database 2011 conference
PostgreSQL talk, Database 2011 conferenceReuven Lerner
 

Plus de Reuven Lerner (20)

Technical training business talk.key
Technical training business talk.keyTechnical training business talk.key
Technical training business talk.key
 
Big Data — Your new best friend
Big Data — Your new best friendBig Data — Your new best friend
Big Data — Your new best friend
 
Python's magic methods
Python's magic methodsPython's magic methods
Python's magic methods
 
What can Ruby learn from Python (and vice versa)?
What can Ruby learn from Python (and vice versa)?What can Ruby learn from Python (and vice versa)?
What can Ruby learn from Python (and vice versa)?
 
Functional Python Webinar from October 22nd, 2014
Functional Python Webinar from October 22nd, 2014Functional Python Webinar from October 22nd, 2014
Functional Python Webinar from October 22nd, 2014
 
Web APIs: The future of software
Web APIs: The future of softwareWeb APIs: The future of software
Web APIs: The future of software
 
Rails israel 2013
Rails israel 2013Rails israel 2013
Rails israel 2013
 
Intro to cloud computing — MegaCOMM 2013, Jerusalem
Intro to cloud computing — MegaCOMM 2013, JerusalemIntro to cloud computing — MegaCOMM 2013, Jerusalem
Intro to cloud computing — MegaCOMM 2013, Jerusalem
 
Rails traps
Rails trapsRails traps
Rails traps
 
Modern Web technologies (and why you should care): Megacomm, Jerusalem, Febru...
Modern Web technologies (and why you should care): Megacomm, Jerusalem, Febru...Modern Web technologies (and why you should care): Megacomm, Jerusalem, Febru...
Modern Web technologies (and why you should care): Megacomm, Jerusalem, Febru...
 
Rails development environment talk
Rails development environment talkRails development environment talk
Rails development environment talk
 
Git talk from Open 2011 conference in Israel
Git talk from Open 2011 conference in IsraelGit talk from Open 2011 conference in Israel
Git talk from Open 2011 conference in Israel
 
Dynamic languages, for software craftmanship group
Dynamic languages, for software craftmanship groupDynamic languages, for software craftmanship group
Dynamic languages, for software craftmanship group
 
Modern Web Technologies — Jerusalem Web Professionals, January 2011
Modern Web Technologies — Jerusalem Web Professionals, January 2011Modern Web Technologies — Jerusalem Web Professionals, January 2011
Modern Web Technologies — Jerusalem Web Professionals, January 2011
 
PostgreSQL talk, Database 2011 conference
PostgreSQL talk, Database 2011 conferencePostgreSQL talk, Database 2011 conference
PostgreSQL talk, Database 2011 conference
 
ActiveRecord 2.3
ActiveRecord 2.3ActiveRecord 2.3
ActiveRecord 2.3
 
Ruby objects
Ruby objectsRuby objects
Ruby objects
 
Rails console
Rails consoleRails console
Rails console
 
Rails tools
Rails toolsRails tools
Rails tools
 
Why ruby and rails
Why ruby and railsWhy ruby and rails
Why ruby and rails
 

Dernier

Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupFlorian Wilhelm
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsPixlogix Infotech
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionDilum Bandara
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr BaganFwdays
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubKalema Edgar
 
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostLeverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostZilliz
 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clashcharlottematthew16
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsRizwan Syed
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationSlibray Presentation
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.Curtis Poe
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024Lorenzo Miniero
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Mark Simos
 
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfHyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfPrecisely
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek SchlawackFwdays
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity PlanDatabarracks
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brandgvaughan
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Commit University
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Enterprise Knowledge
 

Dernier (20)

Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project Setup
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and Cons
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An Introduction
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding Club
 
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostLeverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clash
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL Certs
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck Presentation
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
 
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfHyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity Plan
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brand
 
DMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special EditionDMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special Edition
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024
 

PostgreSQL

  • 1. PostgreSQL Reuven M. Lerner (reuven@lerner.co.il) IL-Techtalks November 14th, 2012
  • 2. Who am I? • Web developer since 1993 • Linux Journal columnist since 1996 • Software architect, developer, consultant • Mostly Ruby on Rails + PostgreSQL, but also Python, PHP, Perl, JavaScript, MySQL, MongoDB, and lots more... • PostgreSQL user since (at least) 1997
  • 3. What do I do? • Web development, especially in Rails • Teaching/training • Coaching/consulting
  • 4. What is a database? Store data confidently Database Retrieve data flexibly
  • 5. Relational databases Define tables, store data in them Database Retrieve data from related tables
  • 6. Lots of options! • Oracle • Microsoft SQL Server • IBM DB2 • MySQL • PostgreSQL
  • 7. How do you choose? • Integrity (ACID compliance) • Data types • Functionality • Tools • Extensibility • Documentation • Community
  • 8. PostgreSQL • Very fast, very scalable. (Just ask Skype.) • Amazingly flexible, easily extensible. • Rock-solid — no crashes, corruption, security issues for years • Ridiculously easy administration • It also happens to be free (MIT/BSD)
  • 15. What about MySQL? • PostgreSQL has many more features • Not nearly as popular as MySQL • No single company behind it • (A good thing, I think!) • After using both, I prefer PostgreSQL • I’ll be happy to answer questions later
  • 16. Brief history • Ingres (Stonebreaker, Berkeley) • Postgres (Stonebreaker, Berkeley) • PostgreSQL project = Postgres + SQL • About one major release per year • Version 8.x — Windows port, recovery • Version 9.0 — hot replication, upgrades
  • 17. ACID • ACID — basic standard for databases • Atomicity • Consistency • Isolation • Durability • Pg has always been ACID compliant
  • 18. Data types • Boolean • Numeric (integer, float, decimal) • (var)char, text (infinitely large), binary • sequences (guaranteed to be unique) • Date/time and time intervals • IP addresses, XML, enums, arrays
  • 20. Or create your own! CREATE TYPE Person AS (first_name TEXT, last_name TEXT);
  • 21. Or create your own! CREATE TYPE Person AS (first_name TEXT, last_name TEXT);
  • 22. Or create your own! CREATE TYPE Person AS (first_name TEXT, last_name TEXT); CREATE TABLE Members (group_id INTEGER, member Person);
  • 23. Strong typing • PostgreSQL won’t automatically change types for you. • This can be annoying at first — but it is meant to protect your data! • You can cast from one type to another with the “cast” function or the :: operator • You can also define your own casts
  • 24. PostGIS • Some people took this all the way • Want to include geographical information? • No problem — we’ve got PostGIS! • Complete GIS solution, with data types and functions • Keeps pace with main PostgreSQL revisions
  • 25. Object oriented tables • Employee table inherits from People table: CREATE TABLE Employee (employee_id INTEGER department_id INTEGER) INHERITS (People);
  • 26. Foreign keys that work CREATE TABLE DVDs (id SERIAL, title TEXT, store_id INTEGER REFERENCES Stores); INSERT INTO DVDs (title, store_id) VALUES ('Attack of the Killer Tomatoes', 500);
  • 27. Foreign keys that work CREATE TABLE DVDs (id SERIAL, title TEXT, store_id INTEGER REFERENCES Stores); INSERT INTO DVDs (title, store_id) VALUES ('Attack of the Killer Tomatoes', 500); ERROR: insert or update on table "dvds" violates foreign key constraint "dvds_store_id_fkey"
  • 28. Foreign keys that work CREATE TABLE DVDs (id SERIAL, title TEXT, store_id INTEGER REFERENCES Stores); INSERT INTO DVDs (title, store_id) VALUES ('Attack of the Killer Tomatoes', 500); ERROR: insert or update on table "dvds" violates foreign key constraint "dvds_store_id_fkey" DETAIL: Key (store_id)=(500) is not present in table "stores".
  • 29. Foreign keys that work CREATE TABLE DVDs (id SERIAL, title TEXT, store_id INTEGER REFERENCES Stores); INSERT INTO DVDs (title, store_id) VALUES ('Attack of the Killer Tomatoes', 500); ERROR: insert or update on table "dvds" violates foreign key constraint "dvds_store_id_fkey" DETAIL: Key (store_id)=(500) is not present in table "stores". ERROR: insert or update on table "dvds" violates foreign key constraint "dvds_store_id_fkey"
  • 30. Foreign keys that work CREATE TABLE DVDs (id SERIAL, title TEXT, store_id INTEGER REFERENCES Stores); INSERT INTO DVDs (title, store_id) VALUES ('Attack of the Killer Tomatoes', 500); ERROR: insert or update on table "dvds" violates foreign key constraint "dvds_store_id_fkey" DETAIL: Key (store_id)=(500) is not present in table "stores". ERROR: insert or update on table "dvds" violates foreign key constraint "dvds_store_id_fkey" DETAIL: Key (store_id)=(500) is not present in table "stores".
  • 31. Custom validity checks CREATE TABLE DVDs (id SERIAL, title TEXT check (length(title) > 3), store_id INTEGER REFERENCES Stores); INSERT INTO DVDs (title, store_id) VALUES ('AB', 500);
  • 32. Custom validity checks CREATE TABLE DVDs (id SERIAL, title TEXT check (length(title) > 3), store_id INTEGER REFERENCES Stores); INSERT INTO DVDs (title, store_id) VALUES ('AB', 500); ERROR: new row for relation "dvds" violates check constraint "dvds_title_check"
  • 33. No more bad dates! INSERT INTO UPDATES (created_at) values ('32- feb-2008');
  • 34. No more bad dates! INSERT INTO UPDATES (created_at) values ('32- feb-2008'); ERROR: date/time field value out of range: "32-feb-2008"
  • 35. No more bad dates! INSERT INTO UPDATES (created_at) values ('32- feb-2008'); ERROR: date/time field value out of range: "32-feb-2008" LINE 1: insert into updates (created_at) values ('32- feb-2008');
  • 36. Timestamp vs. Interval testdb=# select now(); now ------------------------------- 2010-10-31 08:58:23.365792+02 (1 row) Point in time testdb=# select now() - interval '3 days'; ?column? ------------------------------- 2010-10-28 08:58:28.870011+02 Difference between (1 row) points in time
  • 37. Built-in functions • Math • Text processing (including regexps) • Date/time calculations • Conditionals (CASE, COALESCE, NULLIF) for use in queries • Extensive library of geometrical functions
  • 38. Or write your own! • PL/pgSQL • PL/Perl • PL/Python • PL/Ruby • PL/R • PL/Tcl
  • 39. Or write your own! CREATE OR REPLACE FUNCTION remove_cache_tables() RETURNS VOID AS $$ DECLARE r pg_catalog.pg_tables%rowtype; BEGIN FOR r IN SELECT * FROM pg_catalog.pg_tables WHERE schemaname = 'public' AND tablename ILIKE 'cache_%' LOOP RAISE NOTICE 'Now dropping table %', r.tablename; EXECUTE 'DROP TABLE ' || r.tablename; END LOOP; END; $$ LANGUAGE 'plpgsql';
  • 40. Another example CREATE OR REPLACE FUNCTION store_hostname() RETURNS TRIGGER AS $store_hostname$ BEGIN NEW.hostname := 'http://' || substring(NEW.url, '(?:http://)?([^/]+)'); RETURN NEW; END; $store_hostname$ LANGUAGE plpgsql;
  • 41. Triggers • Yes, that last function was a trigger • Automatically execute functions upon INSERT, UPDATE, and/or DELETE • Can execute before or after • Very powerful, very fast
  • 42. Function possibilities • Computing values, strings • Returning table-like sets of values • Encapsulating queries • Dynamically generating queries via strings • Triggers: Modifying data before it is inserted or updated
  • 43. Why use a PL/lang? • Other libraries (e.g., CPAN for Perl) • Faster, optimized functions (eg., R) • Programmer familiarity • Cached query plans
  • 44. Views and rules • Views are stored SELECT statements • Pretend that something is a read-only table • Rules let you turn it into a read/write table • Intercept and rewrite incoming query • Check or change data • Change where data is stored
  • 45. Full-text indexing • Built into PostgreSQL • Handles stop words, different languages, synonyms, and even (often) stemming • Very powerful, but it can take some time to get configured correctly
  • 46. Transactions • In PostgreSQL from the beginning • Use transactions for just about anything: BEGIN DROP TABLE DVDs; ROLLBACK; SELECT * FROM DVDs; -- Works!
  • 47. Savepoints (or, sub-transactions) BEGIN; INSERT INTO table1 VALUES (1); SAVEPOINT my_savepoint; INSERT INTO table1 VALUES (2); ROLLBACK TO SAVEPOINT my_savepoint; INSERT INTO table1 VALUES (3); COMMIT;
  • 48. MVCC • Readers and writers don’t block each other • “Multi-version concurrency control” • xmin, xmax on each tuple; rows are those tuples with txid_current between them • Old versions stick around until vacuumed • Autovacuum removes even this issue
  • 49. MVCC • Look at a row’s xmin and xmax • Look at txid_current() • Start transaction; look at row’s xmin/xmax • Look at xmin/xmax on that row from another session • Commit, and look again at both!
  • 50. Downsides of MVCC • MVCC is usually fantastic • But if you insert or update many rows, and then do a COUNT(*), things will be slow • There are solutions — including more aggressive auto-vacuuming • 9.2 introduced features that improved this
  • 51. Indexing • Regular, unique indexes • Functional indexes • Index calling a function on a column • Partial indexes • Index only rows matching criteria • Cluster table on an index
  • 52. CTEs • Adds a “WITH” statement, which defines a sorta-kinda temp table • You can then query that same temp table • Makes many queries easier to read, write, without a real temp table • Better yet: CTEs can be recursive, for everything from Fibonacci to org charts
  • 53. Speed and scalability • MVCC + a smart query optimizer makes PostgreSQL pretty fast and smart • Statistics based on previous query results inform the query planner • Several scan types, join types are weighed • Benchmarks consistently show excellent performance with high mixes of read/write
  • 54. WAL • All activity in the database is put in “write- ahead logs” before it happens • If the database server fails, it replays the WALs, then continues • You can change how often WALs are written, to improve performance • PITR — restore database from WALs
  • 55. Log shipping • Copy WALs to a second, identical server — known as “log shipping” — and you have a backup • If the primary server goes down, you can bring the secondary up in its place • This was known as “warm standby,” and worked in 8.4
  • 56. Hot standby, streaming replication • As of 9.0, you don’t have to do this • You can have the primary stream the information to the secondary • Almost-instant updates • The secondary machine can answer read- only queries (“hot standby”), not just handle failover
  • 57. Extensions • Provides a standardized mechanism for downloading, installing, and versioning extensions • New data types, functions, languages are possible • Download, search via pgxn.org • Similar to CPAN, PyPi, or Ruby gems
  • 58. SQL/MED • SQL/MED was introduced in 9.1 • Query information from other databases (and database-like interfaces) • So if you have data in MySQL, Oracle, CSV ... just install a wrapper, and you can query it like a PostgreSQL table
  • 59. Unlogged tables • All actions are logged in WALs • That adds some overhead, which isn’t required by throwaway data • Unlogged tables (different from temp tables!) offer a speedup, in exchange for less reliability
  • 60. New in 9.2 • JSON support • Range types, for handling • Much more scalable — from 24 cores and 75k queries/sec to 64 cores and 350k queries/sec • Index-only queries (“covering indexes”) • Cascading replication
  • 61. Web problems • PostgreSQL is great as a Web backend • But if you use an ORM (e.g., ActiveRecord), you are probably losing much of the power • e.g., foreign keys, CTE, triggers, and views • No good way to bridge this gap — for now • There are always methods, but this is an area that definitely needs some work
  • 62. Tablespaces • You can create any number of “tablespaces,” separate storage areas • Put tables, indexes on different tablespaces • Most useful with multiple disks • Separate tables (or parts of a partitioned table)... or separate tables from indexes
  • 63. Partitioning • Combine object-oriented tables, CHECK clauses, and tablespaces for partitioning • Example: Invoices from Jan-June go in table “q12”, and July-December go in table “q34” • Now PostgreSQL knows where to look when you SELECT from the parent table • Note that INSERT requires a trigger
  • 64. Reflection • pg_catalog schema contains everything about your database • Tables, functions, views, etc. • You can learn a great deal about PostgreSQL by looking through the pg_catalog schema
  • 65. Advanced uses • GridSQL: Split a query across multiple PostgreSQL servers • Very large-scale data warehousing: Greenplum
  • 66. Client libraries • libpq (in C) • Java (JDBC) • Others by 3 rd • .NET (npgsql) parties: • ODBC • Python • JavaScript (!) • Ruby • Just about any language you can • Perl imagine
  • 67. Tools • Yeah, tools are more primitive • If you love GUIs, and hate the command line, then PostgreSQL will be hard for you • PgAdmin and other tools are OK, but not really up to the task for “real” work • PgAdmin does provide some graphical query building and “explain” output
  • 68. Windows compatibility • It works on Windows • .NET drivers work, as well • Logging is far from perfect (can go to the Windows log tool, but not filtered well) • Configuration is still in a text file, foreign to most Windows people • Windows is still a second-class citizen
  • 69. Who uses it? • Affilias • IMDB • Apple • Skype • BASF • Sourceforge • Cisco • Heroku • CD Baby • Checkpoint • Etsy
  • 70. Who supports it? • EnterpriseDB — products and services • 2 Quadrant nd • Many freelancers (like me!)
  • 71. PostgreSQL problems • Tuning is still hard (but getting easier) • Double quotes • Lack of good GUI-based tools • Some features (e.g., materialized views) that people want without having to resort to hacks and triggers/rules • Multi-master (of course!)
  • 72. Bottom line • PostgreSQL: BSD licensed, easy to install, easy to use, easy to administer • Still not quite up to commercial databases regarding features — but not far behind • More than good enough for places like Skype and Affilias; probably good enough for you!
  • 73. Want to learn more? • Mailing lists, wikis, and blogs • All at http://postgresql.org/ • http://planetpostgresql.org • PostgreSQL training, consulting, development, hand-holding, and general encouragement
  • 74. Thanks! (Any questions?) reuven@lerner.co.il http://www.lerner.co.il/ 054-496-8405 “reuvenlerner” on Skype/AIM

Notes de l'éditeur

  1. \n
  2. \n
  3. \n
  4. \n
  5. \n
  6. \n
  7. \n
  8. \n
  9. \n
  10. \n
  11. \n
  12. \n
  13. \n
  14. \n
  15. \n
  16. \n
  17. \n
  18. \n
  19. \n
  20. \n
  21. \n
  22. \n
  23. \n
  24. \n
  25. \n
  26. \n
  27. \n
  28. \n
  29. \n
  30. \n
  31. \n
  32. \n
  33. \n
  34. \n
  35. \n
  36. \n
  37. \n
  38. \n
  39. \n
  40. \n
  41. \n
  42. \n
  43. \n
  44. \n
  45. \n
  46. \n
  47. \n
  48. \n
  49. \n
  50. \n
  51. \n
  52. \n
  53. \n
  54. \n
  55. \n
  56. \n
  57. \n
  58. \n
  59. \n
  60. \n
  61. \n
  62. \n
  63. \n
  64. \n
  65. \n
  66. \n
  67. \n
  68. \n
  69. \n
  70. \n
  71. \n
  72. \n
  73. \n
  74. \n
  75. \n
  76. \n
  77. \n