52492-rc071 Postgresql 2
52492-rc071 Postgresql 2
Essential PostgreSQL
Get More Refcardz! Visit Refcardz.com
» About PostgreSQL
C O NT E NT S » Configuration
» Data Types
» Commonly Used Functions
» Database Objects and more...
By Leo Hsu and Regina Obe
FILE PURPOSE
© D Z O NE, INC. | DZ O NE .C O M
2 ESSENTIAL POSTGRESQL
same time. The rules are applied sequentially such that the
first match fitting a connection is the one that is used. This is NUMERIC TYPES
important to remember because if you have a more restrictive TYPE DESCRIPTION
rule above a less restrictive, then the more restrictive is the one
int, int8 4 byte and 8 byte integers.
that trumps.
The most commonly used authentication schemes are trust serial, serial4, Sequential integers; this can be used during
serial8 table creation to specify auto-numbered
(which allows connections without a password) and md5
fields.
(which authenticates with md5 encrypted passwords). Others
include: reject, crypt, password (this is plain text), krb5, ident numeric(s, p) Decimal numbers; s is scale and p is
precision.
(authenticate simply by identity of user in OS), pam, and ldap.
double precision Floating point numbers.
The example pg_hba.conf entries below allow all local
connections to connect to all databases without a password and numrange, Introduced in 9.2 for defining number
all remote connections to authenticate via md5. int4range ranges.
#TYPE DATABASE USER CIDR-ADDRESS METHOD An integer >= 1 and < 10.
SELECT ‘[1,10)’::int4range;
HOST ALL ALL 127.0.0.1/32 TRUST
HOST ALL ALL 0.0.0.0/0 MD5 percentile_cont, Continuous and discrete percentile
percentile_disc aggregate. Can take a numeric value
(between 0 and 1) for percentile rank or can
DATA T Y P E S take an array of numeric values between 0
and 1.
PostgreSQL has numerous built-in types. In addition, you can
define custom types. Furthermore, all tables are considered to STRING TYPES
be types in their own right, and can therefore be used within TYPE DESCRIPTION
another table’s column. Below are the common built-in types:
varchar(n) (a.k.a. Max of n characters, no trailing spaces.
DATE/TIME TYPES character varying)
© D Z O NE, INC . | DZ O NE .C O M
3 ESSENTIAL POSTGRESQL
jsonb Binary form of JSON—introduced in PostgreSQL Quotes keywords and expressions not
9.4. Can be indexed using GIN indexes and supports suitable for identity when unquoted.
quote_ident
intersects and containment operators in addition quote_ident('in') => "in"
to all the functions and operators JSON supports. quote_ident('big') => big
Performance is much faster than the JSON type. No
duplicate keys per object are allowed; sort of keys per quote_literal Escapes both single and double quotes.
object are not maintained.
Similar to quote_literal but doesn’t
quote_nullable
quote NULL.
COMMON GLOBAL VARIABLES
replace('1234abcv', '1234', 'joe') =>
TYPE DESCRIPTION replace joeabcv
CURRENT_ Takes a delimited string and returns the nth
Returns current date and time with timezone.
TIMESTAMP, now() split_part item.
CURRENT_DATE Returns current date without the time. split_part('abc|def', '|', 2) =>def
Nth value relative to current, -nth value Functions, These can be written in any enabled language
lead, lag relative to current (n defaults to 1) in current Triggers, and in the database, live in schemas. PostgreSQL
partition. Aggregates allows you to define your own custom aggregate
functions. Triggers are special classes of
first_value, last_ Absolute first/last/nth value in a partition
functions that have OLD and NEW variables
value, nth_value based on order regardless of current position.
available that hold a pointer to the OLD and NEW
data. Triggers are bound to table. New in
OB JECT DESCRIPTION PSQL runs in both a non-interactive mode (straight from the OS
shell prompt) and an interactive mode (PSQL terminal prompt).
Functions, PostgreSQL 9.3 are event triggers which are
In both modes, the following arguments apply:
Triggers, and bound to events such as creation of table or
Aggregates (cont.) deletion of table.
ARGUM ENT DESCRIPTION
Operators, Live in schemas. Many are predefined, but more
Database. Defaults to the user (via system
Operator Classes, can be added and allow you to define things such -d
identification if no user is specified).
Operator Families as +, =, etc. for custom data types.
-h Server host. Defaults to localhost if not specified.
Sequences Autocreated when defining columns as serial. In
PostgreSQL, sequences are objects in their own -p Port. Defaults to 5432 if not specified.
right and can be shared across many tables.
Username you are trying to log in with. Defaults to
Types Live in schemas. Don’t forget that you have the -U
system user name.
flexibility to create your own custom data types in
PostgreSQL.
PSQL NON-INTERACTIVE MODE
Foreign Data Foreign Data Wrappers are remote data source
Getting help
Wrappers, drivers that allow you to access data in a
Servers and User non-PostgreSQL or remote PostgreSQL table. $ psql –help
Mappings PostgreSQL 9.1 introduced these. 9.2 improved on
Execute an SQL script stored in a file
general performance, and 9.3 introduced a new
FDW called postgresfdw for connecting to other $ psql –h localhost -U postgres –p 5432 –f /path/to/
PostgreSQL servers, and also enhanced the API to pgdumpall.sql
support Foreign table updates.
Output data in html format
Extensions Packaging of functions, tables, and other objects $ psql -h someserver -p 5432 -U postgres -d dzone -H -c
[9.1+] for easy deployment in a database. These are "SELECT * FROM pg_tips" -o tips.html
installed using CREATE EXTENSION.
Execute a single statement against a db
CREATE EXTENSION hstore;
$ psql -U postgres –p 5432 -d dzone -c "CREATE TABLE
test(some_id serial PRIMARY KEY, some_text text);"
TOOLS
Execute an SQL batch script against a database and send output to file
PostgreSQL comes bundled with several tools useful for
$ psql -h localhost -U someuser -d dzone -f /path/to/
administration and query writing. scriptfile.sql -o /path/to/outputfile.txt
TOOL DESCRIPTION
PSQL INTERACTIVE MODE
psql Command-line client packaged with PostgreSQL.
Good for automating SQL jobs, copying data, To initiate interactive PSQL, type:
outputing simple HTML reports. psql –U username –p 5432 –h localhost –d dzone
pg_dump Command-line tool for doing backups. Great for :q Cancel out of more screen
automated backups.
\? Help on psql commands
pg_dumpall Command-line tool for dumping all databases
into a single backup. \h some_command Help on SQL commands
pgAgent A daemon/service that can be downloaded from \connect postgres Switch database
http://www.pgadmin.org/download/pgagent.php.
\l List all databases
Used for scheduling SQL jobs and batch shell
jobs. Jobs can be added easily and monitored \dtv p* List tables and views that start with p.
using the PgAdmin III job interface.
\du List user/group roles and their group
pg_basebackup Used for doing filesystem hot backup of db memberships and server level permissions.
data cluster.
\d sometable List columns, data types, and constraints
pg_upgrade Used for updating in place from one major for a table.
version of PostgreSQL to another.
\i somefile Execute SQL script stored in a file.
PSQL is a command-line tool that allows you to run ad-hoc Use up and down Retrieve prior commands.
arrows
queries, scripts, and other useful database management routines.
\timing Toggle query timing on and off; when on, -b, --blobs D Include large objects in dump.
query output includes timing information.
Specify name of database to restore
\copy Copy from client computer to server and -d, --dbname=NAME R
to.
from server to client computer. Example:
The following command string copies data Specify backup file format (c =
to local client computer in CSV format with compressed, t = tar, p = plain text,
header. -F, --format=c|t|p|d DR d = directory). Plain-text backups
must be restored with psql.
\copy (SELECT * FROM sometable) TO
'C:/sometable.csv' WITH HEADER CSV Directory new in [9.2].
FORCE QUOTE
Clean (drop) schema prior to create
\copy ... from Allows you to copy output from an external -c, --clean DRA (for pg_dumpall drop database prior
program program such as ls, dir, wget, curl. New in to create).
9.3.
Dump only global objects (roles,
-g, --globals-only A schemas, tablespaces), no
A D M I N TA S K S databases.
Output a table of contents from backup file -T, --exclude- Exclude named table(s) from
D
table=NAME backup.
pg_restore -l -f "C:/toc.txt" "C:/somedb.backup"
-v --verbose DRA Controls verbosity.
Restore only items in the table of contents
--exclude-table- Exclude dumping table data for
pg_restore -h localhost -d db_to_restore -U someuser -L D
"C:/toc.txt" "C:/somedb.backup" data=TABLE [9.2] specific table.
Create a group role with no CREATE ROLE somerole NOSUPERUSER Create or alter a CREATE OR REPLACE VIEW someview AS SELECT
login rights and members INHERIT NOCREATEDB NOCREATEROLE; view * FROM sometable;
inherit rights of role [Prior to version 8.4, adding new columns to a view
Add a role to another role GRANT somerole TO someotherrole; requires dropping and recreating].
Create a schema CREATE SCHEMA someschema; Add trigger to table CREATE TRIGGER sometrigger BEFORE UPDATE
ON sometable FOR EACH ROW
Changing database Sets the default schema to someschema.
schema search path EXECUTE PROCEDURE sometriggerupdate();
ALTER DATABASE postgresql_dzone SET
search_path = someschema, public; Suppress redundant A built-in trigger that prevents updates that would
updates not change any data.
Dropping A drop without a CASCADE clause will not drop an
objects with no object if there are objects that depend on it, such as CREATE TRIGGER trig_01_suppress_redundant
dependencies views, functions, and tables. BEFORE UPDATE ON sometable FOR EACH ROW
Create a table CREATE TABLE test_scores(student These are examples that show case some of PostgreSQL popular
varchar(100),
score integer, test_date date DEFAULT or unique query features.
CURRENT_DATE,
CONSTRAINT pk_test_scores PRIMARY KEY ADDING AND UPDATING DATA
(student, test_date));
Insert statement with INSERT INTO test_
Create a child table CREATE TABLE somechildtable (CONSTRAINT multirows scores(student,score,test_date)
pk_somepk PRIMARY KEY (id)) INHERITS VALUES ('robe', 95, '2014-01-15'),
(someparenttable); ('lhsu', 99, '2014-01-15'),
('robe', 98, '2014-07-15'),
Create a check ALTER TABLE sometable ADD CONSTRAINT ('lhsu', 92, '2014-07-15'),
constraint somecheckcontraint CHECK (id > 0); ('lhsu', 97,'2014-08-15');
Get median values SELECT student, percentile_cont(0.5) You can create set returning functions, simple scalar functions,
WITHIN GROUP (ORDER BY score) AS m_ triggers, and aggregate functions with most of these languages.
[9.4]
continuous,
percentile_disc(0.5) This allows for languages that are highly optimized for a
WITHIN GROUP (ORDER BY score) AS m_ particular task to work directly with data without having to
discrete
always copy it out to process as you normally would need with a
FROM test_scores GROUP BY student;
simple database storage device. Language handlers can be of two
student | m_continuous | m_discrete
--------+--------------+------------ flavors: trusted and untrusted. An untrusted language can access
lhsu | 97 | 97
robe | 96.5 | 95
the filesystem directly.
Built in and always enabled. Often used to Allows you to write functions in JavaScript.
extend PostgreSQL (e.g. postgis, pgsphere, CREATE FUNCTION
tablefunc) or, for example, to introduce fib(n int) RETURNS int AS $$
new windowing functions (introduced in function fib(n) {
plv8 return n<2 ? n : fib(n-1) +
PostgreSQL 8.4). Functions are referenced
c* none fib(n-2)
from a .so or .dll file. }
CREATE OR REPLACE FUNCTION return fib(n)
st_summary(geometry) $$ LANGUAGE plv8 IMMUTABLE STRICT;
RETURNS text AS
'$libdir/postgis-2.1', 'LWGEOM_summary'
LANGUAGE 'c' IMMUTABLE STRICT; COMMON PROCEDURAL TASKS
Not always enabled, but packaged so it can Create a table trigger and use in table
be installed.
CREATE OR REPLACE FUNCTION mytable_ft_trigger()
CREATE FUNCTION cp_upd(p_key integer, RETURNS trigger AS $$
p_value varchar) BEGIN
RETURNS void AS NEW.tsv :=
$$ setweight(to_tsvector('pg_catalog.english',
BEGIN coalesce(new.field1,'')), 'A') ||
IF EXISTS(SELECT test_id FROM setweight(to_tsvector('pg_catalog.english',
testtable WHERE test_id = p_key) THEN coalesce(NEW.field2,'')), 'B');
plpgsql* UPDATE testtable return NEW;
(trusted) SET test_stuff = p_value
none
END
WHERE test_id = p_key; $$ LANGUAGE plpgsql;
ELSE
INSERT INTO testtable (test_id, CREATE TRIGGER mytable_trigiu
test_stuff) BEFORE INSERT OR UPDATE OF field1,field2
VALUES(p_key, p_value); ON mytable
END IF; FOR EACH ROW EXECUTE PROCEDURE mytable_ft_trigger()
RETURN; Return sets and use out of params
END;
$$ CREATE OR REPLACE FUNCTION
LANGUAGE 'plpgsql' VOLATILE; fn_sqltestmulti(param_subject varchar,
OUT test_id integer,
Good for manipulating JSON objects,
OUT test_stuff text)
reusing existing Javascript libraries, RETURNS SETOF record
numeric processing. Comes packaged AS
with 3 language bindings: Plv8 (aka PL/ $$
Javascript), plls (LiveScript), plcoffee Google SELECT test_id, test_stuff
plv8 (trusted)
(CoffeeScript).
v8 FROM testtable
engine WHERE test_stuff LIKE $1;
To install: $$
LANGUAGE 'sql' STABLE;
CREATE EXTENSION plv8;
--example
CREATE EXTENSION plls;
SELECT * FROM fn_sqltestmulti('%stuff%');
CREATE EXTENSION plcoffee;
PostGIS
Adds support for geographic
objects allowing location http://postgis.net/
HOT see: http://www.postgresql.org/docs/current/static/
contrib.html
queries to be run using SQL. TIP To search for third party extensions see: http://pgxn.org/
Shards and replicates tables
https://github.com/
pg_shard for horizontal scaling and
citusdata/pg_shard
high availability.
CREDITS:
Editor: G. Ryan Spain | Designer: Yassee Mohebbi | Production: Chris Smith | Sponsor Relations: Brandon Rosser | Marketing: Chelsea Bosworth
JOIN NOW
DZONE, INC.
150 PRESTON EXECUTIVE DR.
CARY, NC 27513
DZone communities deliver over 6 million pages each month to more than 3.3 million software 888.678.0399
developers, architects and decision makers. DZone offers something for everyone, including news, 919.678.0300
tutorials, cheat sheets, research guides, feature articles, source code and more.
REFCARDZ FEEDBACK WELCOME
"DZone is a developer's dream," says PC Magazine. [email protected]
©© DZONE,
form or by means electronic, mechanical, photocopying, or otherwise, without prior written permission of the publisher.
DZONE, INC. INC. |
Copyright © 2015 DZone, Inc. All rights reserved. No part of this publication may be reproduced, stored in a retrieval system, or transmitted, in any SPONSORSHIP OPPORTUNITIES
DZONE.COM
DZONE.COM
[email protected] VERSION 1.0 $7.95