SlideShare a Scribd company logo
Demystifying
Presented by
Asher Snyder
@ashyboy
co-founder of
Latest PostgreSQL version 9.0.1
www.postgresql.org
What is PostgreSQL?
• Completely Open Source Database System
– Started in 1995
– Open source project
– Not owned by any one company
– Controlled by the community
– Can’t be bought (Looking at you ORACLE)
• ORDMBS
– Object-relational database management system?
• RDBMS with object-oriented database model
– That’s right, it’s not just an RDMBS
– You can create your own objects
– You can inherit
• Fully ACID compliant
– Atomicity, Consistency, Isolation, Durability. Guarantees that
database transactions are processed reliably.
• ANSI SQL compliant
Notable Features
• Transactions
• Functions (Stored procedures)
• Rules
• Views
• Triggers
• Inheritance
• Custom Types
• Referential Integrity
• Array Data Types
• Schemas
• Hot Standby (as of 9.0)
• Streaming Replication (as of 9.0)
Support
• Excellent Personal Support!
– Vibrant Community
• Active Mailing List
• Active IRC - #postgres on irc.freenode.net
– Absolutely amazing
• Complete, Extensive and Detailed Documentation
– http://www.postgresql.org/docs/
• Regular and frequent releases and updates
– Public Roadmap
• Support for older builds
– Currently support and release updates to builds as
old as 5 years
Support
• Numerous Shared Hosts
– Such as A2hosting (http://www.a2hosting.com)
• Numerous GUI Administration Tools
– pgAdmin (http://www.pgadmin.org/)
– php pgAdmin
(http://phppgadmin.sourceforge.net/)
– Notable commercial tools
• Navicat (http://www.navicat.com)
• EMS (http://sqlmanager.net)
– Many many more
• http://wiki.postgresql.org/wiki/Community_Guide_to_
PostgreSQL_GUI_Tools
Installation
• Despite what you’ve heard
Postgres is NOT hard to install
$ apt-get install postgresql
On Ubuntu or Debian:
$ emerge postgresql
On Gentoo:
$ adduser postgres
mkdir /usr/local/pgsql/data
chown postgres /usr/local/pgsql/data
su - postgres
/usr/local/pgsql/bin/initdb -D /usr/local/pgsql/data
/usr/local/pgsql/bin/postgres -D /usr/local/pgsql/data
Manual Installation:
Installation (cont)
• Regardless of what installation method
you choose. Make sure to modify
postgresql.conf and pg_hba.conf
configuration files if you want to allow
outside access.
# TYPE DATABASE USER CIDR-ADDRESS METHOD
host all all 0.0.0.0/0 md5
pg_hba.conf - Controls which hosts are allowed to connect
Allows for connection from any outside connection with md5 verification
# - Connection Settings
listen_addresses = '*' # IP address to listen on
#listen_addresses = 'localhost' # default
postgresql.conf - PostgreSQL configuration file
Allows PostgreSQL to listen on any address
Getting Started
$ /etc/init.d/postgresql start
pg_hba.conf - Controls which hosts are allowed to connect
$ /usr/local/pgsql/bin/postgres -D /usr/local/pgsql/data
alternatively, you can start it manually
Start from distro
Creating Your Database
$ psql
Launch psql
CREATE DATABASE first_db;
Create your first PostgreSQL database
c first_db
Connect to your newly created database
Tables
Tables - Creating
CREATE TABLE users (
"user_id" SERIAL,
"email" TEXT,
"firstname" TEXT,
"lastname" TEXT,
"password" TEXT,
PRIMARY KEY("user_id")
);
• What’s a SERIAL?
– Short for INTEGER NOT NULL with default value of
nextval('users_user_id_seq')
• Similar to AUTO_INCREMENT property of other databases.
Tables - Inserting
INSERT INTO users (email, firstname, lastname, password)
VALUES ('asnyder@noloh.com', 'Asher', 'Snyder', 'Pass');
We can explicitly define each field and the value associated with it.
This will set user_id to the default value.
INSERT INTO users VALUES (DEFAULT, 'john@example.com',
'John', 'Doe', 'OtherPass');
Alternatively, we can not specify the column names and insert
based on the column order, using DEFAULT for the user_id.
SELECT * FROM users;
Lets see the results
user_id | email | firstname | lastname | password
--------+-------------------+-----------+------------------+-----------+----------------------------
1 | asnyder@noloh.com | Ash | Snyder | Pass
2 | John | Doe | john@example.com | OtherPass
Views
Views
CREATE VIEW v_get_all_users AS
SELECT * FROM users;
• Views allow you store a query for easy retrieval later.
– Query a view as if it were a table
– Allows you to name your query
– Use views as types
– Abstract & encapsulate table structure changes
• Allows for easier modification & extension of your database
Create basic view
Query the view
SELECT * FROM v_get_all_users;
user_id | email | firstname | lastname | password
--------+-------------------+-----------+------------------+-----------+----------------------------
1 | asnyder@noloh.com | Ash | Snyder | Pass
2 | John | Doe | john@example.com | OtherPass
Views (cont)
ALTER TABLE users ADD COLUMN "time_created"
TIMESTAMP WITHOUT TIME ZONE DEFAULT
Alter Table
Now, if we were to query the table we would see a timestamp showing us when
the user was created.
SELECT * FROM users;
As you can see, this is not very useful for humans. This is where a view can
come in to make your life easier.
user_id | email | firstname | lastname | password | time_created
--------+-------------------+-----------+------------------+-----------+----------------------------
1 | asnyder@noloh.com | Ash | Snyder | Pass | 2010-10-27 14:30:07.335936
2 | John | Doe | john@example.com | OtherPass | 2010-10-27 14:30:07.335936
Views (cont)
CREATE OR REPLACE VIEW v_get_all_users
AS
SELECT user_id,
email,
firstname,
lastname,
password,
time_created,
to_char(time_created, 'FMMonth
FMDDth, YYYY FMHH12:MI:SS AM') as
friendly_time
FROM users;
Alter View
Views (cont)
Now, when we query the view we can actually interpret time_created
SELECT * FROM v_get_all_users;
user_id | email | firstname | lastname | password | time_created
---------+-------------------+-----------+------------------+-----------+----------------------------
1 | asnyder@noloh.com | Ash | Snyder | Pass | 2010-10-27 14:30:07.335936
2 | John | Doe | john@example.com | OtherPass | 2010-10-27 15:20:05.235936
| friendly_time
+-------------------------------
October 27th, 2010 2:30:07 PM
October 27th, 2010 3:20:05 PM
Views (cont) – Joined View
Finally, lets create a joined view
CREATE TABLE companies (
"company_id" SERIAL,
"company_name" TEXT,
PRIMARY KEY("company_id")
);
Create companies table
INSERT INTO companies VALUES(DEFAULT, 'NOLOH LLC.');
Add company
ALTER TABLE users ADD COLUMN company_id INTEGER;
Add company_id to users
UPDATE users SET company_id = 1;
Update users
Views (cont) – Joined View
CREATE OR REPLACE VIEW v_get_all_users
AS
SELECT user_id,
email,
firstname,
lastname,
password,
time_created,
to_char(time_created, 'FMMonth FMDDth, YYYY
FMHH12:MI:SS AM') as friendly_time,
t2.company_id,
t2.company_name
FROM users t1
LEFT JOIN companies t2 ON (t1.company_id =
t2.company_id);
Alter view
Views (cont)
SELECT * FROM v_get_all_users;
user_id | email | firstname | lastname | password | time_created
---------+-------------------+-----------+------------------+-----------+----------------------------
1 | asnyder@noloh.com | Ash | Snyder | SomePass | 2010-10-27 14:30:07.335936
2 | John | Doe | john@example.com | OtherPass | 2010-10-27 15:20:05.235936
| friendly_time | company_id | company_name
+------------------------------+------------+--------------
October 27th, 2010 2:30:07 PM | 1 | NOLOH LLC.
October 27th, 2010 3:20:05 PM | 1 | NOLOH LLC.
Query view
Nice! Now instead of having to modify a query each time we can just use
v_get_all_users. We can even use this VIEW as a return type when
creating your own database functions.
Functions
Functions
• Also known as Stored Procedures
• Allows you to carry out operations that would normally
take several queries and round-trips in a single function
within the database
• Allows database re-use as other applications can interact
directly with your stored procedures instead of a middle-
tier or duplicating code
• Can be used in other functions
• First class citizens
– Query functions like tables
– Create functions in language of your choice
• SQL, PL/pgSQL, C, Python, etc.
– Allowed to modify tables and perform multiple operations
– Defaults
– In/Out parameters
Functions (cont)
CREATE FUNCTION f_add_company(p_name TEXT) RETURNS
INTEGER
AS
$func$
INSERT INTO companies (company_name) VALUES ($1)
RETURNING company_id;
$func$
LANGUAGE SQL;
Create basic function
Call f_add_company
f_add_company
---------------
2
(1 row)
SELECT f_add_company('Google');
Functions (cont) – Syntax Explained
• Return type
– In this case we used INTEGER
• Can be anything you like including your views and own custom types
– Can even return an ARRAY of types, such as INTEGER[]
• Do not confusing this with returning a SET of types.
• Returning multiple rows of a particular types is done
through RETURN SETOF. For example, RETURN SETOF
v_get_all_users.
• $func$ is our delimiter separating the function body. It
can be any string you like. For example $body$ instead of
$func$.
• $1 refers to parameter corresponding to that number. We
can also use the parameter name instead. In our example
this would be 'p_name'.
Functions (cont) – PL/pgSQL
• If you’re using PostgreSQL < 9.0 make
sure you add PL/pgSQL support
CREATE TRUSTED PROCEDURAL LANGUAGE "plpgsql"
HANDLER "plpgsql_call_handler"
VALIDATOR "plpgsql_validator";
Functions (cont) – PL/pgSQL
CREATE OR REPLACE FUNCTION f_add_company(p_name TEXT) RETURNS INTEGER
AS
$func$
DECLARE
return_var INTEGER;
BEGIN
SELECT INTO return_var company_id FROM companies WHERE
lower(company_name) = lower($1);
IF NOT FOUND THEN
INSERT INTO companies (company_name) VALUES ($1) RETURNING
company_id INTO return_var;
END IF;
RETURN return_var;
END;
$func$
LANGUAGE plpgsql;
Functions (cont)
Call f_add_company
f_add_company
---------------
3
(1 row)
SELECT f_add_company('Zend');
Call f_add_company with repeated entry
f_add_company
---------------
2
(1 row)
SELECT f_add_company('Google');
• We can see that using functions in our database allows us
to integrate safeguards and business logic into our
functions allowing for increased modularity and re-use.
Triggers
Triggers
• Specifies a function to be called BEFORE or AFTER any
INSERT, UPDATE, or DELETE operation
– Similar to an event handler (but clearly confined) in event
based programming
– BEFORE triggers fire before the data is actually inserted.
– AFTER triggers fire after the statement is executed and
data is inserted into the row
• Function takes NO parameters and returns type
TRIGGER
• Most commonly used for logging or validation
• Can be defined on entire statement or a per-row basis
– Statement level triggers should always return NULL
• As of 9.0 can be specified for specific columns and
specific WHEN conditions
Triggers (cont)
CREATE TABLE logs (
"log_id" SERIAL,
"log" TEXT,
PRIMARY KEY("log_id")
);
Create logs table
CREATE FUNCTION "tr_log_handler"()
RETURNS trigger AS
$func$
DECLARE
log_string TEXT;
BEGIN
log_string := 'User ' || OLD.user_id || ' changed ' || CURRENT_TIMESTAMP;
IF NEW.email != OLD.email THEN
log_string := log_string || 'email changed from '
|| OLD.email || ' to ' || NEW.email || '. ';
END IF;
IF NEW.firstname != OLD.firstname THEN
log_string := log_string || 'firstname changed from '
|| OLD.firstname || ' to ' || NEW.firstname || '. ';
END IF;
IF NEW.lastname != OLD.lastname THEN
log_string := log_string || 'lastname changed from '
|| OLD.lastname || ' to ' || NEW.lastname || '. ';
END IF;
INSERT INTO logs (log) VALUES (log_string);
RETURN NEW;
END;
$func$
LANGUAGE plpgsql;
Create trigger handler
Triggers (cont)
CREATE TRIGGER "tr_log" AFTER UPDATE
ON users FOR EACH ROW
EXECUTE PROCEDURE "tr_log_handler"();
Create trigger
log_id | log
--------+---------------------------------------------------------------------------------
1 | User 1 changed 2010-08-30 23:43:23.771347-04 firstname changed from Asher to Ash.
(1 row)
SELECT * FROM logs;
Update user
UPDATE users SET firstname = 'Ash' WHERE user_id = 1;
Display logs
Full-Text Search
Full-Text Search
• Allows documents to be preprocessed
• Search through text to find matches
• Sort matches based on relevance
– Apply weights to certain attributes to
increase/decrease relevance
• Faster than LIKE, ILIKE, and LIKE with regular
expressions
• Define your own dictionaries
– Define your own words, synonyms, phrase
relationships, word variations
Full-Text Search
• tsvector
– Vectorized text data
• tsquery
– Search predicate
• Converted to Normalized lexemes
– Ex. run, runs, ran and running are forms of the same lexeme
• @@
– Match operator
Full-Text Search (cont)
SELECT 'phpbarcelona 2010 is a great conference'::tsvector
@@ 'conference & great'::tsquery;
Match Test 1
SELECT 'phpbarcelona 2010 is a great conference'
@@ 'conference & bad'
Match Test 2
?column?
---------
t
(1 row)
?column?
---------
f
(1 row)
Full-Text Search (cont) – to_
SELECT to_tsvector('phpbarcelona 2010 is a great conference‘)
@@ plainto_tsquery('conference & great') ;
to_tsvector & plainto_tsquery
SELECT * FROM companies WHERE to_tsvector(company_name) @@
to_tsquery('unlimited');
Search through tables
?column?
---------
t
(1 row)
company_id | company_name
------------+--------------
(0 rows)
Full-Text Search
• setweight
– Possible weights are A, B, C, D
• equivalent 1.0, 0.4, 0.2, 0.1 respectively
• ts_rank
– Normal ranking function
• ts_rank_cd
– uses the cover density method of ranking, as
specified in Clarke, Cormack, and Tudhope’s
“Relevance Ranking for One to Three Term
Queries” in the journal, “Information Processing
and Management”, 1999.
Full-Text Search (cont) - Ranking
SELECT case_id, file_name,
ts_rank_cd(setweight(to_tsvector(coalesce(t1.file_name)), 'A') ||
setweight(to_tsvector(coalesce(t1.contents)), 'B'), query) AS rank
FROM cases.cases t1, plainto_tsquery('copyright') query
WHERE to_tsvector(file_name || ' ' || contents) @@ query
ORDER BY rank DESC LIMIT 10
setweight & ts_rank_cd
case_id | file_name | rank
---------+------------------------------------------------------+------
101 | Harper & Row v Nation Enter 471 US 539.pdf | 84.8
113 | IN Re Literary Works Elec Databases 509 F3d 522.pdf | 76
215 | Lexmark Intl v Static Control 387 F3d 522.pdf | 75.2
283 | Feist Pubs v Rural Tel 499 US 340.pdf | 67.2
216 | Lucks Music Library v Ashcroft 321 F Supp 2d 107.pdf | 59.2
342 | Blue Nile v Ice 478 F Supp 2d 1240.pdf | 50.8
374 | Perfect 10 v Amazon 487 F3d 701.pdf | 43.6
85 | Pillsbury v Milky Way 215 USPQ 124.pdf | 43.6
197 | St Lukes Cataract v Sanderson 573 F3d 1186.pdf | 42
272 | Religious Technology v Netcom 907 F Supp 1361.pdf | 42
(10 rows)
Questions
?
@ashyboy
Presented by
Asher Snyder
co-founder of

More Related Content

What's hot

MySQL
MySQLMySQL
Postgre sql run book
Postgre sql run bookPostgre sql run book
Postgre sql run book
Vasudeva Rao
 
CQL performance with Apache Cassandra 3.0 (Aaron Morton, The Last Pickle) | C...
CQL performance with Apache Cassandra 3.0 (Aaron Morton, The Last Pickle) | C...CQL performance with Apache Cassandra 3.0 (Aaron Morton, The Last Pickle) | C...
CQL performance with Apache Cassandra 3.0 (Aaron Morton, The Last Pickle) | C...
DataStax
 
Introduction databases and MYSQL
Introduction databases and MYSQLIntroduction databases and MYSQL
Introduction databases and MYSQL
Naeem Junejo
 
Building node.js applications with Database Jones
Building node.js applications with Database JonesBuilding node.js applications with Database Jones
Building node.js applications with Database Jones
John David Duncan
 
Apache Cassandra Lesson: Data Modelling and CQL3
Apache Cassandra Lesson: Data Modelling and CQL3Apache Cassandra Lesson: Data Modelling and CQL3
Apache Cassandra Lesson: Data Modelling and CQL3
Markus Klems
 
database-querry-student-note
database-querry-student-notedatabase-querry-student-note
database-querry-student-noteLeerpiny Makouach
 
Terraform Cosmos DB
Terraform Cosmos DBTerraform Cosmos DB
Terraform Cosmos DB
Moisés Elías Araya
 
Data Processing Inside PostgreSQL
Data Processing Inside PostgreSQLData Processing Inside PostgreSQL
Data Processing Inside PostgreSQL
EDB
 
Beginner guide to mysql command line
Beginner guide to mysql command lineBeginner guide to mysql command line
Beginner guide to mysql command line
Priti Solanki
 
PostgreSQL Database Slides
PostgreSQL Database SlidesPostgreSQL Database Slides
PostgreSQL Database Slides
metsarin
 
An Introduction to Basics of Search and Relevancy with Apache Solr
An Introduction to Basics of Search and Relevancy with Apache SolrAn Introduction to Basics of Search and Relevancy with Apache Solr
An Introduction to Basics of Search and Relevancy with Apache Solr
Lucidworks (Archived)
 
[WLDN] Supercharging word press development in 2018
[WLDN] Supercharging word press development in 2018[WLDN] Supercharging word press development in 2018
[WLDN] Supercharging word press development in 2018
Adam Tomat
 

What's hot (19)

mysqlHiep.ppt
mysqlHiep.pptmysqlHiep.ppt
mysqlHiep.ppt
 
MySQL
MySQLMySQL
MySQL
 
Mysql Ppt
Mysql PptMysql Ppt
Mysql Ppt
 
Postgre sql run book
Postgre sql run bookPostgre sql run book
Postgre sql run book
 
CQL performance with Apache Cassandra 3.0 (Aaron Morton, The Last Pickle) | C...
CQL performance with Apache Cassandra 3.0 (Aaron Morton, The Last Pickle) | C...CQL performance with Apache Cassandra 3.0 (Aaron Morton, The Last Pickle) | C...
CQL performance with Apache Cassandra 3.0 (Aaron Morton, The Last Pickle) | C...
 
Introduction databases and MYSQL
Introduction databases and MYSQLIntroduction databases and MYSQL
Introduction databases and MYSQL
 
Building node.js applications with Database Jones
Building node.js applications with Database JonesBuilding node.js applications with Database Jones
Building node.js applications with Database Jones
 
Apache Cassandra Lesson: Data Modelling and CQL3
Apache Cassandra Lesson: Data Modelling and CQL3Apache Cassandra Lesson: Data Modelling and CQL3
Apache Cassandra Lesson: Data Modelling and CQL3
 
Mysql
MysqlMysql
Mysql
 
database-querry-student-note
database-querry-student-notedatabase-querry-student-note
database-querry-student-note
 
Postgre sql unleashed
Postgre sql unleashedPostgre sql unleashed
Postgre sql unleashed
 
Terraform Cosmos DB
Terraform Cosmos DBTerraform Cosmos DB
Terraform Cosmos DB
 
ASM
ASMASM
ASM
 
Data Processing Inside PostgreSQL
Data Processing Inside PostgreSQLData Processing Inside PostgreSQL
Data Processing Inside PostgreSQL
 
Beginner guide to mysql command line
Beginner guide to mysql command lineBeginner guide to mysql command line
Beginner guide to mysql command line
 
PostgreSQL Database Slides
PostgreSQL Database SlidesPostgreSQL Database Slides
PostgreSQL Database Slides
 
Powershell alias
Powershell aliasPowershell alias
Powershell alias
 
An Introduction to Basics of Search and Relevancy with Apache Solr
An Introduction to Basics of Search and Relevancy with Apache SolrAn Introduction to Basics of Search and Relevancy with Apache Solr
An Introduction to Basics of Search and Relevancy with Apache Solr
 
[WLDN] Supercharging word press development in 2018
[WLDN] Supercharging word press development in 2018[WLDN] Supercharging word press development in 2018
[WLDN] Supercharging word press development in 2018
 

Viewers also liked

Ejemplo de Aplicaciones en Weka
Ejemplo de Aplicaciones en WekaEjemplo de Aplicaciones en Weka
Ejemplo de Aplicaciones en Weka
Raquel Solano
 
Database Tools by Skype
Database Tools by SkypeDatabase Tools by Skype
Database Tools by Skypeelliando dias
 
Connection Pooling in PostgreSQL using pgbouncer
Connection Pooling in PostgreSQL using pgbouncer Connection Pooling in PostgreSQL using pgbouncer
Connection Pooling in PostgreSQL using pgbouncer
Sameer Kumar
 
Meet Spilo, Zalando’s HIGH-AVAILABLE POSTGRESQL CLUSTER - Feike Steenbergen
Meet Spilo, Zalando’s HIGH-AVAILABLE POSTGRESQL CLUSTER - Feike SteenbergenMeet Spilo, Zalando’s HIGH-AVAILABLE POSTGRESQL CLUSTER - Feike Steenbergen
Meet Spilo, Zalando’s HIGH-AVAILABLE POSTGRESQL CLUSTER - Feike Steenbergen
distributed matters
 
"Отказоустойчивый standby PostgreSQL (HAProxy + PgBouncer)" Виктор Ягофаров (...
"Отказоустойчивый standby PostgreSQL (HAProxy + PgBouncer)" Виктор Ягофаров (..."Отказоустойчивый standby PostgreSQL (HAProxy + PgBouncer)" Виктор Ягофаров (...
"Отказоустойчивый standby PostgreSQL (HAProxy + PgBouncer)" Виктор Ягофаров (...
AvitoTech
 
plProxy, pgBouncer, pgBalancer
plProxy, pgBouncer, pgBalancerplProxy, pgBouncer, pgBalancer
plProxy, pgBouncer, pgBalancerelliando dias
 
Managing Databases In A DevOps Environment 2016
Managing Databases In A DevOps Environment 2016Managing Databases In A DevOps Environment 2016
Managing Databases In A DevOps Environment 2016
Robert Treat
 
Building Hybrid data cluster using PostgreSQL and MongoDB
Building Hybrid data cluster using PostgreSQL and MongoDBBuilding Hybrid data cluster using PostgreSQL and MongoDB
Building Hybrid data cluster using PostgreSQL and MongoDBAshnikbiz
 
Scaling postgres
Scaling postgresScaling postgres
Scaling postgres
Denish Patel
 

Viewers also liked (9)

Ejemplo de Aplicaciones en Weka
Ejemplo de Aplicaciones en WekaEjemplo de Aplicaciones en Weka
Ejemplo de Aplicaciones en Weka
 
Database Tools by Skype
Database Tools by SkypeDatabase Tools by Skype
Database Tools by Skype
 
Connection Pooling in PostgreSQL using pgbouncer
Connection Pooling in PostgreSQL using pgbouncer Connection Pooling in PostgreSQL using pgbouncer
Connection Pooling in PostgreSQL using pgbouncer
 
Meet Spilo, Zalando’s HIGH-AVAILABLE POSTGRESQL CLUSTER - Feike Steenbergen
Meet Spilo, Zalando’s HIGH-AVAILABLE POSTGRESQL CLUSTER - Feike SteenbergenMeet Spilo, Zalando’s HIGH-AVAILABLE POSTGRESQL CLUSTER - Feike Steenbergen
Meet Spilo, Zalando’s HIGH-AVAILABLE POSTGRESQL CLUSTER - Feike Steenbergen
 
"Отказоустойчивый standby PostgreSQL (HAProxy + PgBouncer)" Виктор Ягофаров (...
"Отказоустойчивый standby PostgreSQL (HAProxy + PgBouncer)" Виктор Ягофаров (..."Отказоустойчивый standby PostgreSQL (HAProxy + PgBouncer)" Виктор Ягофаров (...
"Отказоустойчивый standby PostgreSQL (HAProxy + PgBouncer)" Виктор Ягофаров (...
 
plProxy, pgBouncer, pgBalancer
plProxy, pgBouncer, pgBalancerplProxy, pgBouncer, pgBalancer
plProxy, pgBouncer, pgBalancer
 
Managing Databases In A DevOps Environment 2016
Managing Databases In A DevOps Environment 2016Managing Databases In A DevOps Environment 2016
Managing Databases In A DevOps Environment 2016
 
Building Hybrid data cluster using PostgreSQL and MongoDB
Building Hybrid data cluster using PostgreSQL and MongoDBBuilding Hybrid data cluster using PostgreSQL and MongoDB
Building Hybrid data cluster using PostgreSQL and MongoDB
 
Scaling postgres
Scaling postgresScaling postgres
Scaling postgres
 

Similar to Demystifying PostgreSQL

Kåre Rude Andersen - Be a hero – optimize scom and present your services
Kåre Rude Andersen - Be a hero – optimize scom and present your servicesKåre Rude Andersen - Be a hero – optimize scom and present your services
Kåre Rude Andersen - Be a hero – optimize scom and present your servicesNordic Infrastructure Conference
 
ETL With Cassandra Streaming Bulk Loading
ETL With Cassandra Streaming Bulk LoadingETL With Cassandra Streaming Bulk Loading
ETL With Cassandra Streaming Bulk Loadingalex_araujo
 
Postgres Vienna DB Meetup 2014
Postgres Vienna DB Meetup 2014Postgres Vienna DB Meetup 2014
Postgres Vienna DB Meetup 2014
Michael Renner
 
lec02-data-models-sql-basics.pptx
lec02-data-models-sql-basics.pptxlec02-data-models-sql-basics.pptx
lec02-data-models-sql-basics.pptx
cAnhTrn53
 
Ten Reasons Why You Should Prefer PostgreSQL to MySQL
Ten Reasons Why You Should Prefer PostgreSQL to MySQLTen Reasons Why You Should Prefer PostgreSQL to MySQL
Ten Reasons Why You Should Prefer PostgreSQL to MySQL
anandology
 
Deep dive formatting
Deep dive formattingDeep dive formatting
Deep dive formattingThomas Lee
 
mySQL and Relational Databases
mySQL and Relational DatabasesmySQL and Relational Databases
mySQL and Relational Databaseswebhostingguy
 
Cassandra 2012
Cassandra 2012Cassandra 2012
Cassandra 2012
beobal
 
My sql with querys
My sql with querysMy sql with querys
My sql with querysNIRMAL FELIX
 
Overview of RedDatabase 2.5
Overview of RedDatabase 2.5Overview of RedDatabase 2.5
Overview of RedDatabase 2.5
Mind The Firebird
 
AZMS PRESENTATION.pptx
AZMS PRESENTATION.pptxAZMS PRESENTATION.pptx
AZMS PRESENTATION.pptx
SonuShaw16
 
Developing web applications in Rust
Developing web applications in RustDeveloping web applications in Rust
Developing web applications in Rust
Sylvain Wallez
 
AWS re:Invent 2016: How Citus Enables Scalable PostgreSQL on AWS (DAT207)
AWS re:Invent 2016: How Citus Enables Scalable PostgreSQL on AWS (DAT207)AWS re:Invent 2016: How Citus Enables Scalable PostgreSQL on AWS (DAT207)
AWS re:Invent 2016: How Citus Enables Scalable PostgreSQL on AWS (DAT207)
Amazon Web Services
 
Postgres & Redis Sitting in a Tree- Rimas Silkaitis, Heroku
Postgres & Redis Sitting in a Tree- Rimas Silkaitis, HerokuPostgres & Redis Sitting in a Tree- Rimas Silkaitis, Heroku
Postgres & Redis Sitting in a Tree- Rimas Silkaitis, Heroku
Redis Labs
 
DNN Database Tips & Tricks
DNN Database Tips & TricksDNN Database Tips & Tricks
DNN Database Tips & Tricks
Will Strohl
 
SFScon 2020 - Nikola Milisavljevic - BASE - Python REST API framework
SFScon 2020 - Nikola Milisavljevic - BASE - Python REST API frameworkSFScon 2020 - Nikola Milisavljevic - BASE - Python REST API framework
SFScon 2020 - Nikola Milisavljevic - BASE - Python REST API framework
South Tyrol Free Software Conference
 
Basic Unix
Basic UnixBasic Unix
Basic Unix
Rajesh Kumar
 
DBMS LAB FILE1 task 1 , task 2, task3 and many more.pdf
DBMS LAB FILE1 task 1 , task 2, task3 and many more.pdfDBMS LAB FILE1 task 1 , task 2, task3 and many more.pdf
DBMS LAB FILE1 task 1 , task 2, task3 and many more.pdf
AbhishekKumarPandit5
 
Let's scale-out PostgreSQL using Citus (English)
Let's scale-out PostgreSQL using Citus (English)Let's scale-out PostgreSQL using Citus (English)
Let's scale-out PostgreSQL using Citus (English)
Noriyoshi Shinoda
 

Similar to Demystifying PostgreSQL (20)

Kåre Rude Andersen - Be a hero – optimize scom and present your services
Kåre Rude Andersen - Be a hero – optimize scom and present your servicesKåre Rude Andersen - Be a hero – optimize scom and present your services
Kåre Rude Andersen - Be a hero – optimize scom and present your services
 
ETL With Cassandra Streaming Bulk Loading
ETL With Cassandra Streaming Bulk LoadingETL With Cassandra Streaming Bulk Loading
ETL With Cassandra Streaming Bulk Loading
 
Postgres Vienna DB Meetup 2014
Postgres Vienna DB Meetup 2014Postgres Vienna DB Meetup 2014
Postgres Vienna DB Meetup 2014
 
lec02-data-models-sql-basics.pptx
lec02-data-models-sql-basics.pptxlec02-data-models-sql-basics.pptx
lec02-data-models-sql-basics.pptx
 
Ten Reasons Why You Should Prefer PostgreSQL to MySQL
Ten Reasons Why You Should Prefer PostgreSQL to MySQLTen Reasons Why You Should Prefer PostgreSQL to MySQL
Ten Reasons Why You Should Prefer PostgreSQL to MySQL
 
Deep dive formatting
Deep dive formattingDeep dive formatting
Deep dive formatting
 
AD Cmdlets
AD CmdletsAD Cmdlets
AD Cmdlets
 
mySQL and Relational Databases
mySQL and Relational DatabasesmySQL and Relational Databases
mySQL and Relational Databases
 
Cassandra 2012
Cassandra 2012Cassandra 2012
Cassandra 2012
 
My sql with querys
My sql with querysMy sql with querys
My sql with querys
 
Overview of RedDatabase 2.5
Overview of RedDatabase 2.5Overview of RedDatabase 2.5
Overview of RedDatabase 2.5
 
AZMS PRESENTATION.pptx
AZMS PRESENTATION.pptxAZMS PRESENTATION.pptx
AZMS PRESENTATION.pptx
 
Developing web applications in Rust
Developing web applications in RustDeveloping web applications in Rust
Developing web applications in Rust
 
AWS re:Invent 2016: How Citus Enables Scalable PostgreSQL on AWS (DAT207)
AWS re:Invent 2016: How Citus Enables Scalable PostgreSQL on AWS (DAT207)AWS re:Invent 2016: How Citus Enables Scalable PostgreSQL on AWS (DAT207)
AWS re:Invent 2016: How Citus Enables Scalable PostgreSQL on AWS (DAT207)
 
Postgres & Redis Sitting in a Tree- Rimas Silkaitis, Heroku
Postgres & Redis Sitting in a Tree- Rimas Silkaitis, HerokuPostgres & Redis Sitting in a Tree- Rimas Silkaitis, Heroku
Postgres & Redis Sitting in a Tree- Rimas Silkaitis, Heroku
 
DNN Database Tips & Tricks
DNN Database Tips & TricksDNN Database Tips & Tricks
DNN Database Tips & Tricks
 
SFScon 2020 - Nikola Milisavljevic - BASE - Python REST API framework
SFScon 2020 - Nikola Milisavljevic - BASE - Python REST API frameworkSFScon 2020 - Nikola Milisavljevic - BASE - Python REST API framework
SFScon 2020 - Nikola Milisavljevic - BASE - Python REST API framework
 
Basic Unix
Basic UnixBasic Unix
Basic Unix
 
DBMS LAB FILE1 task 1 , task 2, task3 and many more.pdf
DBMS LAB FILE1 task 1 , task 2, task3 and many more.pdfDBMS LAB FILE1 task 1 , task 2, task3 and many more.pdf
DBMS LAB FILE1 task 1 , task 2, task3 and many more.pdf
 
Let's scale-out PostgreSQL using Citus (English)
Let's scale-out PostgreSQL using Citus (English)Let's scale-out PostgreSQL using Citus (English)
Let's scale-out PostgreSQL using Citus (English)
 

Recently uploaded

Quantum Computing: Current Landscape and the Future Role of APIs
Quantum Computing: Current Landscape and the Future Role of APIsQuantum Computing: Current Landscape and the Future Role of APIs
Quantum Computing: Current Landscape and the Future Role of APIs
Vlad Stirbu
 
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
Product School
 
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdfFIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance
 
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdfSmart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
91mobiles
 
Introduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - CybersecurityIntroduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - Cybersecurity
mikeeftimakis1
 
Free Complete Python - A step towards Data Science
Free Complete Python - A step towards Data ScienceFree Complete Python - A step towards Data Science
Free Complete Python - A step towards Data Science
RinaMondal9
 
Assure Contact Center Experiences for Your Customers With ThousandEyes
Assure Contact Center Experiences for Your Customers With ThousandEyesAssure Contact Center Experiences for Your Customers With ThousandEyes
Assure Contact Center Experiences for Your Customers With ThousandEyes
ThousandEyes
 
Essentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with ParametersEssentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with Parameters
Safe Software
 
UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3
DianaGray10
 
How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...
Product School
 
A tale of scale & speed: How the US Navy is enabling software delivery from l...
A tale of scale & speed: How the US Navy is enabling software delivery from l...A tale of scale & speed: How the US Navy is enabling software delivery from l...
A tale of scale & speed: How the US Navy is enabling software delivery from l...
sonjaschweigert1
 
GraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge GraphGraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge Graph
Guy Korland
 
SAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdf
SAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdfSAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdf
SAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdf
Peter Spielvogel
 
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
DanBrown980551
 
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Thierry Lestable
 
PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)
Ralf Eggert
 
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 previewState of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
Prayukth K V
 
PCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase TeamPCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase Team
ControlCase
 
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
BookNet Canada
 
Generative AI Deep Dive: Advancing from Proof of Concept to Production
Generative AI Deep Dive: Advancing from Proof of Concept to ProductionGenerative AI Deep Dive: Advancing from Proof of Concept to Production
Generative AI Deep Dive: Advancing from Proof of Concept to Production
Aggregage
 

Recently uploaded (20)

Quantum Computing: Current Landscape and the Future Role of APIs
Quantum Computing: Current Landscape and the Future Role of APIsQuantum Computing: Current Landscape and the Future Role of APIs
Quantum Computing: Current Landscape and the Future Role of APIs
 
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
 
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdfFIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
 
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdfSmart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
 
Introduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - CybersecurityIntroduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - Cybersecurity
 
Free Complete Python - A step towards Data Science
Free Complete Python - A step towards Data ScienceFree Complete Python - A step towards Data Science
Free Complete Python - A step towards Data Science
 
Assure Contact Center Experiences for Your Customers With ThousandEyes
Assure Contact Center Experiences for Your Customers With ThousandEyesAssure Contact Center Experiences for Your Customers With ThousandEyes
Assure Contact Center Experiences for Your Customers With ThousandEyes
 
Essentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with ParametersEssentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with Parameters
 
UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3
 
How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...
 
A tale of scale & speed: How the US Navy is enabling software delivery from l...
A tale of scale & speed: How the US Navy is enabling software delivery from l...A tale of scale & speed: How the US Navy is enabling software delivery from l...
A tale of scale & speed: How the US Navy is enabling software delivery from l...
 
GraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge GraphGraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge Graph
 
SAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdf
SAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdfSAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdf
SAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdf
 
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
 
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
 
PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)
 
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 previewState of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
 
PCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase TeamPCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase Team
 
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
 
Generative AI Deep Dive: Advancing from Proof of Concept to Production
Generative AI Deep Dive: Advancing from Proof of Concept to ProductionGenerative AI Deep Dive: Advancing from Proof of Concept to Production
Generative AI Deep Dive: Advancing from Proof of Concept to Production
 

Demystifying PostgreSQL

  • 1. Demystifying Presented by Asher Snyder @ashyboy co-founder of Latest PostgreSQL version 9.0.1 www.postgresql.org
  • 2. What is PostgreSQL? • Completely Open Source Database System – Started in 1995 – Open source project – Not owned by any one company – Controlled by the community – Can’t be bought (Looking at you ORACLE) • ORDMBS – Object-relational database management system? • RDBMS with object-oriented database model – That’s right, it’s not just an RDMBS – You can create your own objects – You can inherit • Fully ACID compliant – Atomicity, Consistency, Isolation, Durability. Guarantees that database transactions are processed reliably. • ANSI SQL compliant
  • 3. Notable Features • Transactions • Functions (Stored procedures) • Rules • Views • Triggers • Inheritance • Custom Types • Referential Integrity • Array Data Types • Schemas • Hot Standby (as of 9.0) • Streaming Replication (as of 9.0)
  • 4. Support • Excellent Personal Support! – Vibrant Community • Active Mailing List • Active IRC - #postgres on irc.freenode.net – Absolutely amazing • Complete, Extensive and Detailed Documentation – http://www.postgresql.org/docs/ • Regular and frequent releases and updates – Public Roadmap • Support for older builds – Currently support and release updates to builds as old as 5 years
  • 5. Support • Numerous Shared Hosts – Such as A2hosting (http://www.a2hosting.com) • Numerous GUI Administration Tools – pgAdmin (http://www.pgadmin.org/) – php pgAdmin (http://phppgadmin.sourceforge.net/) – Notable commercial tools • Navicat (http://www.navicat.com) • EMS (http://sqlmanager.net) – Many many more • http://wiki.postgresql.org/wiki/Community_Guide_to_ PostgreSQL_GUI_Tools
  • 6. Installation • Despite what you’ve heard Postgres is NOT hard to install $ apt-get install postgresql On Ubuntu or Debian: $ emerge postgresql On Gentoo: $ adduser postgres mkdir /usr/local/pgsql/data chown postgres /usr/local/pgsql/data su - postgres /usr/local/pgsql/bin/initdb -D /usr/local/pgsql/data /usr/local/pgsql/bin/postgres -D /usr/local/pgsql/data Manual Installation:
  • 7. Installation (cont) • Regardless of what installation method you choose. Make sure to modify postgresql.conf and pg_hba.conf configuration files if you want to allow outside access. # TYPE DATABASE USER CIDR-ADDRESS METHOD host all all 0.0.0.0/0 md5 pg_hba.conf - Controls which hosts are allowed to connect Allows for connection from any outside connection with md5 verification # - Connection Settings listen_addresses = '*' # IP address to listen on #listen_addresses = 'localhost' # default postgresql.conf - PostgreSQL configuration file Allows PostgreSQL to listen on any address
  • 8. Getting Started $ /etc/init.d/postgresql start pg_hba.conf - Controls which hosts are allowed to connect $ /usr/local/pgsql/bin/postgres -D /usr/local/pgsql/data alternatively, you can start it manually Start from distro
  • 9. Creating Your Database $ psql Launch psql CREATE DATABASE first_db; Create your first PostgreSQL database c first_db Connect to your newly created database
  • 11. Tables - Creating CREATE TABLE users ( "user_id" SERIAL, "email" TEXT, "firstname" TEXT, "lastname" TEXT, "password" TEXT, PRIMARY KEY("user_id") ); • What’s a SERIAL? – Short for INTEGER NOT NULL with default value of nextval('users_user_id_seq') • Similar to AUTO_INCREMENT property of other databases.
  • 12. Tables - Inserting INSERT INTO users (email, firstname, lastname, password) VALUES ('asnyder@noloh.com', 'Asher', 'Snyder', 'Pass'); We can explicitly define each field and the value associated with it. This will set user_id to the default value. INSERT INTO users VALUES (DEFAULT, 'john@example.com', 'John', 'Doe', 'OtherPass'); Alternatively, we can not specify the column names and insert based on the column order, using DEFAULT for the user_id. SELECT * FROM users; Lets see the results user_id | email | firstname | lastname | password --------+-------------------+-----------+------------------+-----------+---------------------------- 1 | asnyder@noloh.com | Ash | Snyder | Pass 2 | John | Doe | john@example.com | OtherPass
  • 13. Views
  • 14. Views CREATE VIEW v_get_all_users AS SELECT * FROM users; • Views allow you store a query for easy retrieval later. – Query a view as if it were a table – Allows you to name your query – Use views as types – Abstract & encapsulate table structure changes • Allows for easier modification & extension of your database Create basic view Query the view SELECT * FROM v_get_all_users; user_id | email | firstname | lastname | password --------+-------------------+-----------+------------------+-----------+---------------------------- 1 | asnyder@noloh.com | Ash | Snyder | Pass 2 | John | Doe | john@example.com | OtherPass
  • 15. Views (cont) ALTER TABLE users ADD COLUMN "time_created" TIMESTAMP WITHOUT TIME ZONE DEFAULT Alter Table Now, if we were to query the table we would see a timestamp showing us when the user was created. SELECT * FROM users; As you can see, this is not very useful for humans. This is where a view can come in to make your life easier. user_id | email | firstname | lastname | password | time_created --------+-------------------+-----------+------------------+-----------+---------------------------- 1 | asnyder@noloh.com | Ash | Snyder | Pass | 2010-10-27 14:30:07.335936 2 | John | Doe | john@example.com | OtherPass | 2010-10-27 14:30:07.335936
  • 16. Views (cont) CREATE OR REPLACE VIEW v_get_all_users AS SELECT user_id, email, firstname, lastname, password, time_created, to_char(time_created, 'FMMonth FMDDth, YYYY FMHH12:MI:SS AM') as friendly_time FROM users; Alter View
  • 17. Views (cont) Now, when we query the view we can actually interpret time_created SELECT * FROM v_get_all_users; user_id | email | firstname | lastname | password | time_created ---------+-------------------+-----------+------------------+-----------+---------------------------- 1 | asnyder@noloh.com | Ash | Snyder | Pass | 2010-10-27 14:30:07.335936 2 | John | Doe | john@example.com | OtherPass | 2010-10-27 15:20:05.235936 | friendly_time +------------------------------- October 27th, 2010 2:30:07 PM October 27th, 2010 3:20:05 PM
  • 18. Views (cont) – Joined View Finally, lets create a joined view CREATE TABLE companies ( "company_id" SERIAL, "company_name" TEXT, PRIMARY KEY("company_id") ); Create companies table INSERT INTO companies VALUES(DEFAULT, 'NOLOH LLC.'); Add company ALTER TABLE users ADD COLUMN company_id INTEGER; Add company_id to users UPDATE users SET company_id = 1; Update users
  • 19. Views (cont) – Joined View CREATE OR REPLACE VIEW v_get_all_users AS SELECT user_id, email, firstname, lastname, password, time_created, to_char(time_created, 'FMMonth FMDDth, YYYY FMHH12:MI:SS AM') as friendly_time, t2.company_id, t2.company_name FROM users t1 LEFT JOIN companies t2 ON (t1.company_id = t2.company_id); Alter view
  • 20. Views (cont) SELECT * FROM v_get_all_users; user_id | email | firstname | lastname | password | time_created ---------+-------------------+-----------+------------------+-----------+---------------------------- 1 | asnyder@noloh.com | Ash | Snyder | SomePass | 2010-10-27 14:30:07.335936 2 | John | Doe | john@example.com | OtherPass | 2010-10-27 15:20:05.235936 | friendly_time | company_id | company_name +------------------------------+------------+-------------- October 27th, 2010 2:30:07 PM | 1 | NOLOH LLC. October 27th, 2010 3:20:05 PM | 1 | NOLOH LLC. Query view Nice! Now instead of having to modify a query each time we can just use v_get_all_users. We can even use this VIEW as a return type when creating your own database functions.
  • 22. Functions • Also known as Stored Procedures • Allows you to carry out operations that would normally take several queries and round-trips in a single function within the database • Allows database re-use as other applications can interact directly with your stored procedures instead of a middle- tier or duplicating code • Can be used in other functions • First class citizens – Query functions like tables – Create functions in language of your choice • SQL, PL/pgSQL, C, Python, etc. – Allowed to modify tables and perform multiple operations – Defaults – In/Out parameters
  • 23. Functions (cont) CREATE FUNCTION f_add_company(p_name TEXT) RETURNS INTEGER AS $func$ INSERT INTO companies (company_name) VALUES ($1) RETURNING company_id; $func$ LANGUAGE SQL; Create basic function Call f_add_company f_add_company --------------- 2 (1 row) SELECT f_add_company('Google');
  • 24. Functions (cont) – Syntax Explained • Return type – In this case we used INTEGER • Can be anything you like including your views and own custom types – Can even return an ARRAY of types, such as INTEGER[] • Do not confusing this with returning a SET of types. • Returning multiple rows of a particular types is done through RETURN SETOF. For example, RETURN SETOF v_get_all_users. • $func$ is our delimiter separating the function body. It can be any string you like. For example $body$ instead of $func$. • $1 refers to parameter corresponding to that number. We can also use the parameter name instead. In our example this would be 'p_name'.
  • 25. Functions (cont) – PL/pgSQL • If you’re using PostgreSQL < 9.0 make sure you add PL/pgSQL support CREATE TRUSTED PROCEDURAL LANGUAGE "plpgsql" HANDLER "plpgsql_call_handler" VALIDATOR "plpgsql_validator";
  • 26. Functions (cont) – PL/pgSQL CREATE OR REPLACE FUNCTION f_add_company(p_name TEXT) RETURNS INTEGER AS $func$ DECLARE return_var INTEGER; BEGIN SELECT INTO return_var company_id FROM companies WHERE lower(company_name) = lower($1); IF NOT FOUND THEN INSERT INTO companies (company_name) VALUES ($1) RETURNING company_id INTO return_var; END IF; RETURN return_var; END; $func$ LANGUAGE plpgsql;
  • 27. Functions (cont) Call f_add_company f_add_company --------------- 3 (1 row) SELECT f_add_company('Zend'); Call f_add_company with repeated entry f_add_company --------------- 2 (1 row) SELECT f_add_company('Google'); • We can see that using functions in our database allows us to integrate safeguards and business logic into our functions allowing for increased modularity and re-use.
  • 29. Triggers • Specifies a function to be called BEFORE or AFTER any INSERT, UPDATE, or DELETE operation – Similar to an event handler (but clearly confined) in event based programming – BEFORE triggers fire before the data is actually inserted. – AFTER triggers fire after the statement is executed and data is inserted into the row • Function takes NO parameters and returns type TRIGGER • Most commonly used for logging or validation • Can be defined on entire statement or a per-row basis – Statement level triggers should always return NULL • As of 9.0 can be specified for specific columns and specific WHEN conditions
  • 30. Triggers (cont) CREATE TABLE logs ( "log_id" SERIAL, "log" TEXT, PRIMARY KEY("log_id") ); Create logs table CREATE FUNCTION "tr_log_handler"() RETURNS trigger AS $func$ DECLARE log_string TEXT; BEGIN log_string := 'User ' || OLD.user_id || ' changed ' || CURRENT_TIMESTAMP; IF NEW.email != OLD.email THEN log_string := log_string || 'email changed from ' || OLD.email || ' to ' || NEW.email || '. '; END IF; IF NEW.firstname != OLD.firstname THEN log_string := log_string || 'firstname changed from ' || OLD.firstname || ' to ' || NEW.firstname || '. '; END IF; IF NEW.lastname != OLD.lastname THEN log_string := log_string || 'lastname changed from ' || OLD.lastname || ' to ' || NEW.lastname || '. '; END IF; INSERT INTO logs (log) VALUES (log_string); RETURN NEW; END; $func$ LANGUAGE plpgsql; Create trigger handler
  • 31. Triggers (cont) CREATE TRIGGER "tr_log" AFTER UPDATE ON users FOR EACH ROW EXECUTE PROCEDURE "tr_log_handler"(); Create trigger log_id | log --------+--------------------------------------------------------------------------------- 1 | User 1 changed 2010-08-30 23:43:23.771347-04 firstname changed from Asher to Ash. (1 row) SELECT * FROM logs; Update user UPDATE users SET firstname = 'Ash' WHERE user_id = 1; Display logs
  • 33. Full-Text Search • Allows documents to be preprocessed • Search through text to find matches • Sort matches based on relevance – Apply weights to certain attributes to increase/decrease relevance • Faster than LIKE, ILIKE, and LIKE with regular expressions • Define your own dictionaries – Define your own words, synonyms, phrase relationships, word variations
  • 34. Full-Text Search • tsvector – Vectorized text data • tsquery – Search predicate • Converted to Normalized lexemes – Ex. run, runs, ran and running are forms of the same lexeme • @@ – Match operator
  • 35. Full-Text Search (cont) SELECT 'phpbarcelona 2010 is a great conference'::tsvector @@ 'conference & great'::tsquery; Match Test 1 SELECT 'phpbarcelona 2010 is a great conference' @@ 'conference & bad' Match Test 2 ?column? --------- t (1 row) ?column? --------- f (1 row)
  • 36. Full-Text Search (cont) – to_ SELECT to_tsvector('phpbarcelona 2010 is a great conference‘) @@ plainto_tsquery('conference & great') ; to_tsvector & plainto_tsquery SELECT * FROM companies WHERE to_tsvector(company_name) @@ to_tsquery('unlimited'); Search through tables ?column? --------- t (1 row) company_id | company_name ------------+-------------- (0 rows)
  • 37. Full-Text Search • setweight – Possible weights are A, B, C, D • equivalent 1.0, 0.4, 0.2, 0.1 respectively • ts_rank – Normal ranking function • ts_rank_cd – uses the cover density method of ranking, as specified in Clarke, Cormack, and Tudhope’s “Relevance Ranking for One to Three Term Queries” in the journal, “Information Processing and Management”, 1999.
  • 38. Full-Text Search (cont) - Ranking SELECT case_id, file_name, ts_rank_cd(setweight(to_tsvector(coalesce(t1.file_name)), 'A') || setweight(to_tsvector(coalesce(t1.contents)), 'B'), query) AS rank FROM cases.cases t1, plainto_tsquery('copyright') query WHERE to_tsvector(file_name || ' ' || contents) @@ query ORDER BY rank DESC LIMIT 10 setweight & ts_rank_cd case_id | file_name | rank ---------+------------------------------------------------------+------ 101 | Harper & Row v Nation Enter 471 US 539.pdf | 84.8 113 | IN Re Literary Works Elec Databases 509 F3d 522.pdf | 76 215 | Lexmark Intl v Static Control 387 F3d 522.pdf | 75.2 283 | Feist Pubs v Rural Tel 499 US 340.pdf | 67.2 216 | Lucks Music Library v Ashcroft 321 F Supp 2d 107.pdf | 59.2 342 | Blue Nile v Ice 478 F Supp 2d 1240.pdf | 50.8 374 | Perfect 10 v Amazon 487 F3d 701.pdf | 43.6 85 | Pillsbury v Milky Way 215 USPQ 124.pdf | 43.6 197 | St Lukes Cataract v Sanderson 573 F3d 1186.pdf | 42 272 | Religious Technology v Netcom 907 F Supp 1361.pdf | 42 (10 rows)