Admin Functions
COPY .. FROM ..
COPY .. TO ..
current_setting
pg_cancel_backend
pg_column_size
pg_database_size
pg_relation_size
pg_size_pretty
pg_tablespace_size
pg_total_relation_size
set_config
vacuum analyze verbose
vacuum full
Common Functions
cast, ::
coalesce
generate_series
greatest
least
nullif
random
Sequence (Serial) Functionscurrval
lastval
nextval
String Functions
||
ascii
chr
initcap
length
lower
lpad
ltrim
md5
position
quote_ident
quote_literal
regexp_matches
regexp_replace
regexp_split_to_array
regexp_split_to_table
repeat
replace
rpad
rtrim
split_part
strpos
substr
trim
upper
Database Globals
current_date
current_time
current_timestamp
current_user
localtime
Date Functions
age
date_part(text, timestamp)
century
day
decade
dow
doy
epoch
hour
month
quarter
second
week
year
date_trunc
extract
interval
to_char
to_date
to_timestamp
Date Predicates
overlaps
Array Constructs
ANY(array)
ARRAY[[4,5,6],..]
ARRAY()
array_append
array_cat
array_dims
array_lower
array_prepend
array_to_string
array_upper
SOME(array)
string_to_array
Array Operators
=
<>
<
>
<=
||
Math Operators
% , ^, |/
||/,!, !!
@, &, |
#,~, <<
>>
Math Functions
abs
cbrt
ceiling
degrees
exp
floor
log
ln
mod
pi
power
radians
random
sqrt
trunc
Trig Functions
acos
asin
atan
atan2
cos
cot
sin
tan
|
Command Line
pg_dump
pg_dumpall
pg_restore
psql
JOIN TypesCROSS JOIN
EXCEPT (ALL)
FULL JOIN
[INNER] JOIN
INTERSECT (ALL)
LEFT JOIN
NATURAL JOIN
RIGHT JOIN
UNION (ALL)
SQL KeywordsBETWEEN .. AND
CASE WHEN .. END
DELETE FROM
DISTINCT
DISTINCT ON
EXISTS
FROM
GROUP BY
HAVING
ILIKE
IN(..)
LIKE
LIMIT ..OFFSET
NOT
NOT IN(..)
NULLS FIRST1
NULLS LAST1
ORDER BY
SELECT
SET
SIMILAR TO
TRUNCATE TABLE
UPDATE
USING
WHERE
Aggregates
avg
bit_and
bit_or
boolean_and
boolean_or
count
count(DISTINCT)
every
max
min
stddev
stddev_pop (a bunch more)
sum
sum(DISTINCT)
variance
xml_agg1
DDL
ADD CONSTRAINT
CREATE AGGREGATE
CREATE CAST
CREATE (DEFAULT) CONVERSION
CREATE DATABASE
CREATE DOMAIN
CREATE [OR REPLACE] FUNCTION
CREATE (UNIQUE) INDEX
CREATE LANGUAGE
CREATE OPERATOR
CREATE OPERATOR FAMILY 1
CREATE ROLE
CREATE RULE
CREATE SCHEMA
CREATE SEQUENCE
CREATE TABLE
CREATE TABLESPACE
ALTER TABLE
CREATE TYPE
CREATE [OR REPLACE] VIEW
DROP [object]
Enums 1
> < <= >= =
enum_cmp
enum_first
enum_larger
enum_last
enum_range
enum_smaller
XML 1
database_to_xml
database_to_xmlschema
query_to_xml
query_to_xml_and_xmlschema
table_to_xml
xmlattributes
xmlcomment
xmlconcat
xmlelement
xmlforest
xpath
xmlpi
xmlroot
Languages
c
pljava
plpgsql
plperl(u)
plphp
plproxy
plpython
plr
plruby
plsh
pltcl
sql
Key information_schema Views
columns
sequences
tables
views
Key pg_catalog Tables/Views
pg_class
pg_rules
pg_settings
pg_stat_activity
pg_stat_database
pg_tablespaces
Large Object
Server
lo_creat
lo_create
lo_export
lo_import
lo_unlink
|
Client
lo_close
lo_creat
lo_create
lo_export
lo_import
lo_lseek
lo_open
lo_read
lo_tell
lo_unlink
lo_write
|
|
Official PostgreSQL 8.3 Documentation URL: http://www.postgresql.org/docs/8.3/static/
commonly used
Data Types
datatype[] - e.g. varchar(50)[] (defines an array of a type)
bit
boolean
bytea
character varying(length) - varchar(length)
character(length) - char(length)
date
enum 1
double precision - float4 float8
integer - int4
bigint - int8
|
numeric(length,precision)
oid
serial - serial4
bigserial - serial8
text
time without timezone - time
time with timezone - timez
timestamp without timezone - timestamp
timestamp with timezone - timestampz
xml 1
|
Admin Examplesselect pg_size_pretty(pg_tablespace_size('pg_default')) as tssize,
pg_size_pretty(pg_database_size('somedb')) as dbsize,
pg_size_pretty(pg_relation_size('someschema.sometable')) as tblsize;
COPY sometable FROM "/path/to/textfile.txt" USING DELIMITERS '\t' WITH NULL As 'NULL';
COPY (SELECT * FROM sometable WHERE somevalue LIKE '%') TO '/path/to/textfile.csv'
WITH NULL As 'NULL' CSV HEADER QUOTE AS '"';
vacuum analyze verbose;
vacuum sometable;
vacuum full;
SELECT procpid, usename, pg_cancel_backend(procpid)
FROM pg_stat_activity
WHERE datname = 'somedb';
JOIN EXAMPLES
SELECT o.order_id, o.order_date, o.approved_date,
COUNT(i.item_id) As nlineitems,
SUM(i.unit_price*i.num_units) As total
FROM orders o
INNER JOIN orderitems i ON o.order_id = i.order_id
GROUP BY o.order_id, o.order_date, o.approved_date
HAVING SUM(i.unit_price*i.num_units) > 200
ORDER BY o.approved_date NULLS FIRST;
|
SELECT 'x' As bucket, o.order_id, o.order_date,
COUNT(i.item_id) As nlineitems,
SUM(i.unit_price*i.num_units) As total
FROM xorders o
INNER JOIN xorderitems i ON o.order_id = i.order_id
GROUP BY o.order_id, o.order_date
UNION ALL
SELECT 'y' as bucket, o.order_id, o.order_date,
COUNT(i.item_id) As nlineitems,
SUM(i.unit_price*i.num_units) As total
FROM yorders o
INNER JOIN yorderitems i ON o.order_id = i.order_id
GROUP BY o.order_id, o.order_date
ORDER BY 1,3,2;
|
DDL Examples
CREATE DATABASE somedb
WITH OWNER = somelogin
ENCODING = 'WIN1252';
|
CREATE TABLE orders(
order_id serial NOT NULL,
order_addeddt timestamp without time zone,
order_rating rating,
CONSTRAINT pk_orders_order_id PRIMARY KEY (order_id)
)
WITH (OIDS=FALSE);
|
CREATE TYPE rating AS
ENUM('none', 'bronze', 'silver',
'gold', 'platinum');
|
CREATE AGGREGATE sum(text) (
SFUNC=textcat,
STYPE=text
);
|
CREATE OR REPLACE FUNCTION cp_test(somearg integer)
RETURNS SETOF sometable AS
$$SELECT * FROM sometable where msg_id = $1;$$
LANGUAGE 'sql' STABLE;
|
Update/Insert/Delete Examples
UPDATE sometable
SET somevalue = 5
WHERE sometable.somename = 'stuff';
|
UPDATE sometable
SET calccount = s.thecount
FROM (SELECT COUNT(someothertable.someid) as thecount,
someothertable.someid
FROM someothertable
GROUP BY someothertable.someid) s
WHERE sometable.someid = s.someid;
|
INSERT INTO orders(order_addeddt, order_rating)
VALUES ('2007-10-01 20:40', 'gold'),
('2007-09-01 11:00 AM', 'silver'),
('2007-09-02 10:00 PM', 'none'),
('2007-10-10 PM', 'bronze');
|
INSERT INTO orders(order_addeddt, order_rating)
VALUES ('2007-10-01 20:40', 'gold');
|
DELETE FROM sometable
WHERE somevalue = 'something';
|
TRUNCATE TABLE sometable;
|
MISCELLANEOUS EXAMPLES
SELECT *
FROM orders
WHERE order_rating
BETWEEN 'bronze' AND 'gold'
ORDER BY order_rating;
SELECT monthperiod.*,
array_to_string(ARRAY(SELECT (d + 1)::varchar(20)
FROM generate_series(0,30) d
WHERE monthperiod.start_date + (d || ' day')::interval
BETWEEN monthperiod.start_date
AND
monthperiod.end_date), ',') as thedays
FROM (SELECT (n + 1) As mnum,
trim(to_char(date '2007-01-01' + (n || ' month')::interval, 'Mon')) As short_mname,
trim(to_char(date '2007-01-01' + (n || ' month')::interval, 'Month')) As long_mname,
date '2007-01-01' + (n || ' month')::interval As start_date,
date '2007-01-01' + ((n + 1) || ' month')::interval + - '1 day'::interval As end_date
FROM generate_series(0,11) n) As monthperiod;
EXPLAIN ANALYZE SELECT * FROM sometable;
Command Line Examples
pg_dump -i -h someserver -p 5432 -U someuser -F c -b -v -f "\somepath\somedb.backup" somedb
pg_dumpall -i -h someserver -p 5432 -U someuser -c -o -f "\somepath\alldbs.sql"
pg_restore -i -h someserver -p 5432 -U someuser -d somedb -l "\somepath\somedb.backup"
psql -h someserver -p 5432 -U someuser -d somedb -f "\somepath\somefiletorun.sql"
psql -h someserver -p 5432 -U someuser -d somedb -c "CREATE TABLE sometable(st_id serial, st_name varchar(25))"
psql -h someserver -p 5432 -U someuser -d somedb -P "t" -c "SELECT query_to_xml('select * from sometable', false, false, 'sometable')" -o "outputfile.xml";
|