Professional Documents
Culture Documents
Postgresql83 Cheatsheet
Postgresql83 Cheatsheet
Postgresql83 Cheatsheet
3/static/
We cover only a subset of what we feel are the most useful constructs that we could squash in a single cheatsheet page
COPY .. FROM .. pg_dump
COPY .. TO .. pg_dumpall commonly used
1 New in this release.
current_setting pg_restore
pg_cancel_backend psql DATA TYPES
pg_column_size
pg_database_size JOIN Types Below are common data types with common alternative names.
pg_relation_size Note: There are many more and one can define new types with create type. All table structures create an implicit type struct as well.
pg_size_pretty CROSS JOIN
pg_tablespace_size EXCEPT (ALL) datatype[] - e.g. varchar(50)[] (defines an array of a type)
pg_total_relation_size FULL JOIN bit numeric(length,precision)
set_config [INNER] JOIN boolean oid
vacuum analyze verbose INTERSECT (ALL) bytea serial - serial4
vacuum full LEFT JOIN
character varying(length) - varchar(length) bigserial - serial8
NATURAL JOIN
RIGHT JOIN
character(length) - char(length) text
Common Functions
UNION (ALL) date time without timezone - time
cast, :: enum 1 time with timezone - timez
coalesce SQL Keywords
double precision - float4 float8 timestamp without timezone - timestamp
generate_series integer - int4 timestamp with timezone - timestampz
BETWEEN .. AND
greatest
CASE WHEN .. END bigint - int8 xml 1
least
nullif DELETE FROM
DISTINCT
random
DISTINCT ON ADMIN EXAMPLES
Sequence (Serial) Functions EXISTS
FROM select pg_size_pretty(pg_tablespace_size('pg_default')) as tssize,
currval GROUP BY pg_size_pretty(pg_database_size('somedb')) as dbsize,
lastval HAVING pg_size_pretty(pg_relation_size('someschema.sometable')) as tblsize;
nextval ILIKE
IN(..) --Example importing data to table sometable
String Functions LIKE --from tab delimited where NULLs appear as NULL
LIMIT ..OFFSET COPY sometable FROM "/path/to/textfile.txt" USING DELIMITERS '\t' WITH NULL As 'NULL';
|| NOT
ascii NOT IN(..) --Example exporting a query to a comma separated (CSV) called textfile.csv
chr --setting NULLS to text NULL
initcap NULLS FIRST1
COPY (SELECT * FROM sometable WHERE somevalue LIKE '%') TO '/path/to/textfile.csv'
length NULLS LAST1
WITH NULL As 'NULL' CSV HEADER QUOTE AS '"';
lower ORDER BY
lpad SELECT
ltrim SET vacuum analyze verbose;
md5 SIMILAR TO vacuum sometable;
position TRUNCATE TABLE vacuum full;
quote_ident UPDATE
quote_literal USING --Kills all active queries in selected db and list out process id
regexp_matches WHERE --and usename of process and if kill successful
regexp_replace SELECT procpid, usename, pg_cancel_backend(procpid)
Aggregates
regexp_split_to_array FROM pg_stat_activity
regexp_split_to_table avg WHERE datname = 'somedb';
repeat bit_and
replace
rpad
bit_or JOIN EXAMPLES
boolean_and
rtrim boolean_or SELECT o.order_id, o.order_date, o.approved_date, SELECT 'x' As bucket, o.order_id, o.order_date,
split_part count COUNT(i.item_id) As nlineitems, COUNT(i.item_id) As nlineitems,
strpos count(DISTINCT) SUM(i.unit_price*i.num_units) As total SUM(i.unit_price*i.num_units) As total
substr every FROM orders o FROM xorders o
trim max INNER JOIN orderitems i ON o.order_id = i.order_id INNER JOIN xorderitems i ON o.order_id = i.order_id
upper min GROUP BY o.order_id, o.order_date, o.approved_date GROUP BY o.order_id, o.order_date
stddev HAVING SUM(i.unit_price*i.num_units) > 200 UNION ALL
Database Globals stddev_pop (a bunch more)
ORDER BY o.approved_date NULLS FIRST; SELECT 'y' as bucket, o.order_id, o.order_date,
sum COUNT(i.item_id) As nlineitems,
current_date
sum(DISTINCT) SUM(i.unit_price*i.num_units) As total
current_time
variance
current_timestamp FROM yorders o
current_user xml_agg1 INNER JOIN yorderitems i ON o.order_id = i.order_id
localtime GROUP BY o.order_id, o.order_date
DDL
ORDER BY 1,3,2;
Date Functions
ADD CONSTRAINT
age CREATE AGGREGATE
date_part(text, timestamp) CREATE CAST
DDL EXAMPLES
century CREATE (DEFAULT) CONVERSION CREATE DATABASE somedb CREATE TABLE orders(
day CREATE DATABASE WITH OWNER = somelogin order_id serial NOT NULL,
decade CREATE DOMAIN ENCODING = 'WIN1252'; order_addeddt timestamp without time zone,
dow CREATE [OR REPLACE] FUNCTION
order_rating rating,
doy CREATE (UNIQUE) INDEX
CREATE LANGUAGE
CONSTRAINT pk_orders_order_id PRIMARY KEY (order_id)
epoch
hour CREATE OPERATOR )
WITH (OIDS=FALSE);
month CREATE OPERATOR FAMILY 1
quarter CREATE ROLE
second CREATE RULE CREATE TYPE rating AS
week CREATE SCHEMA
year ENUM('none', 'bronze', 'silver',
CREATE SEQUENCE 'gold', 'platinum');
date_trunc CREATE TABLE
extract CREATE TABLESPACE
interval ALTER TABLE CREATE AGGREGATE sum(text) ( CREATE OR REPLACE FUNCTION cp_test(somearg integer)
to_char CREATE TYPE SFUNC=textcat, RETURNS SETOF sometable AS
to_date CREATE [OR REPLACE] VIEW STYPE=text $$SELECT * FROM sometable where msg_id = $1;$$
to_timestamp DROP [object] ); LANGUAGE 'sql' STABLE;
Date Predicates
http://www.postgresonline.com